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

52 lines
1.9 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gen
import (
2020-08-12 09:19:37 +08:00
"fmt"
2020-07-29 17:11:41 +08:00
2020-08-12 09:19:37 +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
)
type (
2020-08-12 09:19:37 +08:00
// tableName:user
// {{prefix}}=cache
// key:id
2020-07-29 17:11:41 +08:00
Key struct {
2020-08-12 09:19:37 +08:00
VarExpression string // cacheUserIdPrefix="cache#user#id#"
Left string // cacheUserIdPrefix
Right string // cache#user#id#
Variable string // userIdKey
KeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", userId)
DataKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", data.userId)
RespKeyExpression string // userIdKey: = fmt.Sprintf("cache#user#id#%v", resp.userId)
2020-07-29 17:11:41 +08:00
}
)
2020-08-12 09:19:37 +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
2020-08-12 09:19:37 +08:00
m := make(map[string]Key)
camelTableName := table.Name.Snake2Camel()
lowerStartCamelTableName := stringx.From(camelTableName).LowerStart()
2020-07-29 17:11:41 +08:00
for _, field := range fields {
2020-08-12 09:19:37 +08:00
if !field.IsKey {
2020-07-29 17:11:41 +08:00
continue
}
2020-08-12 09:19:37 +08:00
camelFieldName := field.Name.Snake2Camel()
lowerStartCamelFieldName := stringx.From(camelFieldName).LowerStart()
left := fmt.Sprintf("cache%s%sPrefix", camelTableName, camelFieldName)
right := fmt.Sprintf("cache#%s#%s#", lowerStartCamelTableName, lowerStartCamelFieldName)
variable := fmt.Sprintf("%s%sKey", lowerStartCamelTableName, camelFieldName)
m[field.Name.Source()] = Key{
VarExpression: fmt.Sprintf(`%s = "%s"`, left, right),
Left: left,
Right: right,
Variable: variable,
KeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("cache#user#id#%s", %s)`, variable, "%s", lowerStartCamelFieldName),
DataKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("cache#user#id#%s", data.%s)`, variable, "%s", lowerStartCamelFieldName),
RespKeyExpression: fmt.Sprintf(`%s := fmt.Sprintf("cache#user#id#%s", resp.%s)`, variable, "%s", lowerStartCamelFieldName),
2020-07-29 17:11:41 +08:00
}
}
return m, nil
}