keys.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package gen
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
  6. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  7. )
  8. // tableName:user
  9. // {{prefix}}=cache
  10. // key:id
  11. type Key struct {
  12. VarExpression string // cacheUserIdPrefix = "cache#User#id#"
  13. Left string // cacheUserIdPrefix
  14. Right string // cache#user#id#
  15. Variable string // userIdKey
  16. KeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", userId)
  17. DataKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", data.userId)
  18. RespKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", resp.userId)
  19. }
  20. // key-数据库原始字段名,value-缓存key相关数据
  21. func genCacheKeys(table parser.Table) (map[string]Key, error) {
  22. fields := table.Fields
  23. m := make(map[string]Key)
  24. camelTableName := table.Name.ToCamel()
  25. lowerStartCamelTableName := stringx.From(camelTableName).Untitle()
  26. for _, field := range fields {
  27. if field.IsUniqueKey || field.IsPrimaryKey {
  28. camelFieldName := field.Name.ToCamel()
  29. lowerStartCamelFieldName := stringx.From(camelFieldName).Untitle()
  30. left := fmt.Sprintf("cache%s%sPrefix", camelTableName, camelFieldName)
  31. if strings.ToLower(camelFieldName) == strings.ToLower(camelTableName) {
  32. left = fmt.Sprintf("cache%sPrefix", camelTableName)
  33. }
  34. right := fmt.Sprintf("cache#%s#%s#", camelTableName, lowerStartCamelFieldName)
  35. variable := fmt.Sprintf("%s%sKey", lowerStartCamelTableName, camelFieldName)
  36. if strings.ToLower(lowerStartCamelTableName) == strings.ToLower(camelFieldName) {
  37. variable = fmt.Sprintf("%sKey", lowerStartCamelTableName)
  38. }
  39. m[field.Name.Source()] = Key{
  40. VarExpression: fmt.Sprintf(`%s = "%s"`, left, right),
  41. Left: left,
  42. Right: right,
  43. Variable: variable,
  44. KeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,%s)`, variable, "%s", "%v", left, lowerStartCamelFieldName),
  45. DataKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s",%s, data.%s)`, variable, "%s", "%v", left, camelFieldName),
  46. RespKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,resp.%s)`, variable, "%s", "%v", left, camelFieldName),
  47. }
  48. }
  49. }
  50. return m, nil
  51. }