go-zero/tools/goctl/model/sql/gen/keys.go

63 lines
2.3 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gen
import (
"fmt"
"strings"
2020-07-29 17:11:41 +08:00
"github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx"
2020-07-29 17:11:41 +08:00
)
// Key defines cache key variable for generating code
2021-01-14 13:24:24 +08:00
type Key struct {
// VarExpression likes cacheUserIdPrefix = "cache#User#id#"
VarExpression string
// Left likes cacheUserIdPrefix
Left string
// Right likes cache#user#id#
Right string
// Variable likes userIdKey
Variable string
// KeyExpression likes userIdKey: = fmt.Sprintf("cache#user#id#%v", userId)
KeyExpression string
// DataKeyExpression likes userIdKey: = fmt.Sprintf("cache#user#id#%v", data.userId)
DataKeyExpression string
// RespKeyExpression likes userIdKey: = fmt.Sprintf("cache#user#id#%v", resp.userId)
RespKeyExpression string
2021-01-14 13:24:24 +08:00
}
2020-07-29 17:11:41 +08:00
// key-数据库原始字段名,value-缓存key相关数据
func genCacheKeys(table parser.Table) (map[string]Key, error) {
2020-07-29 17:11:41 +08:00
fields := table.Fields
m := make(map[string]Key)
camelTableName := table.Name.ToCamel()
2020-12-08 23:01:25 +08:00
lowerStartCamelTableName := stringx.From(camelTableName).Untitle()
2020-07-29 17:11:41 +08:00
for _, field := range fields {
2020-09-11 16:46:45 +08:00
if field.IsUniqueKey || field.IsPrimaryKey {
camelFieldName := field.Name.ToCamel()
2020-12-08 23:01:25 +08:00
lowerStartCamelFieldName := stringx.From(camelFieldName).Untitle()
2020-09-11 16:46:45 +08:00
left := fmt.Sprintf("cache%s%sPrefix", camelTableName, camelFieldName)
if strings.ToLower(camelFieldName) == strings.ToLower(camelTableName) {
left = fmt.Sprintf("cache%sPrefix", camelTableName)
}
2020-09-11 16:46:45 +08:00
right := fmt.Sprintf("cache#%s#%s#", camelTableName, lowerStartCamelFieldName)
variable := fmt.Sprintf("%s%sKey", lowerStartCamelTableName, camelFieldName)
if strings.ToLower(lowerStartCamelTableName) == strings.ToLower(camelFieldName) {
variable = fmt.Sprintf("%sKey", lowerStartCamelTableName)
}
2021-01-14 13:24:24 +08:00
2020-09-11 16:46:45 +08:00
m[field.Name.Source()] = Key{
VarExpression: fmt.Sprintf(`%s = "%s"`, left, right),
Left: left,
Right: right,
Variable: variable,
KeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,%s)`, variable, "%s", "%v", left, lowerStartCamelFieldName),
DataKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s",%s, data.%s)`, variable, "%s", "%v", left, camelFieldName),
RespKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("%s%s", %s,resp.%s)`, variable, "%s", "%v", left, camelFieldName),
}
2020-07-29 17:11:41 +08:00
}
}
2021-01-14 13:24:24 +08:00
2020-07-29 17:11:41 +08:00
return m, nil
}