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