keys.go 1.9 KB

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