feature 1.1.5 (#411)

This commit is contained in:
anqiansong
2021-03-01 17:29:07 +08:00
committed by GitHub
parent 791e76bcf0
commit d894b88c3e
27 changed files with 1037 additions and 443 deletions

View File

@@ -12,13 +12,11 @@ import (
func genDelete(table Table, withCache bool) (string, string, error) {
keySet := collection.NewSet()
keyVariableSet := collection.NewSet()
for fieldName, key := range table.CacheKey {
if fieldName == table.PrimaryKey.Name.Source() {
keySet.AddStr(key.KeyExpression)
} else {
keySet.AddStr(key.DataKeyExpression)
}
keyVariableSet.AddStr(key.Variable)
keySet.AddStr(table.PrimaryCacheKey.KeyExpression)
keyVariableSet.AddStr(table.PrimaryCacheKey.KeyLeft)
for _, key := range table.UniqueCacheKey {
keySet.AddStr(key.DataKeyExpression)
keyVariableSet.AddStr(key.KeyLeft)
}
camel := table.Name.ToCamel()
@@ -32,7 +30,7 @@ func genDelete(table Table, withCache bool) (string, string, error) {
Execute(map[string]interface{}{
"upperStartCamelObject": camel,
"withCache": withCache,
"containsIndexCache": table.ContainsUniqueKey,
"containsIndexCache": table.ContainsUniqueCacheKey,
"lowerStartCamelPrimaryKey": stringx.From(table.PrimaryKey.Name.ToCamel()).Untitle(),
"dataType": table.PrimaryKey.DataType,
"keys": strings.Join(keySet.KeysStr(), "\n"),

View File

@@ -8,7 +8,7 @@ import (
"github.com/tal-tech/go-zero/tools/goctl/util"
)
func genFields(fields []parser.Field) (string, error) {
func genFields(fields []*parser.Field) (string, error) {
var list []string
for _, field := range fields {
@@ -23,7 +23,7 @@ func genFields(fields []parser.Field) (string, error) {
return strings.Join(list, "\n"), nil
}
func genField(field parser.Field) (string, error) {
func genField(field *parser.Field) (string, error) {
tag, err := genTag(field.Name.Source())
if err != nil {
return "", err

View File

@@ -22,8 +22,8 @@ func genFindOne(table Table, withCache bool) (string, string, error) {
"originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source()),
"lowerStartCamelPrimaryKey": stringx.From(table.PrimaryKey.Name.ToCamel()).Untitle(),
"dataType": table.PrimaryKey.DataType,
"cacheKey": table.CacheKey[table.PrimaryKey.Name.Source()].KeyExpression,
"cacheKeyVariable": table.CacheKey[table.PrimaryKey.Name.Source()].Variable,
"cacheKey": table.PrimaryCacheKey.KeyExpression,
"cacheKeyVariable": table.PrimaryCacheKey.KeyLeft,
})
if err != nil {
return "", "", err

View File

@@ -24,22 +24,40 @@ func genFindOneByField(table Table, withCache bool) (*findOneCode, error) {
t := util.With("findOneByField").Parse(text)
var list []string
camelTableName := table.Name.ToCamel()
for _, field := range table.Fields {
if field.IsPrimaryKey || !field.IsUniqueKey {
continue
for _, key := range table.UniqueCacheKey {
var inJoin, paramJoin, argJoin Join
for _, f := range key.Fields {
param := stringx.From(f.Name.ToCamel()).Untitle()
inJoin = append(inJoin, fmt.Sprintf("%s %s", param, f.DataType))
paramJoin = append(paramJoin, param)
argJoin = append(argJoin, fmt.Sprintf("%s = ?", wrapWithRawString(f.Name.Source())))
}
camelFieldName := field.Name.ToCamel()
var in string
if len(inJoin) > 0 {
in = inJoin.With(", ").Source()
}
var paramJoinString string
if len(paramJoin) > 0 {
paramJoinString = paramJoin.With(",").Source()
}
var originalFieldString string
if len(argJoin) > 0 {
originalFieldString = argJoin.With(" and ").Source()
}
output, err := t.Execute(map[string]interface{}{
"upperStartCamelObject": camelTableName,
"upperField": camelFieldName,
"in": fmt.Sprintf("%s %s", stringx.From(camelFieldName).Untitle(), field.DataType),
"upperField": key.FieldNameJoin.Camel().With("").Source(),
"in": in,
"withCache": withCache,
"cacheKey": table.CacheKey[field.Name.Source()].KeyExpression,
"cacheKeyVariable": table.CacheKey[field.Name.Source()].Variable,
"cacheKey": key.KeyExpression,
"cacheKeyVariable": key.KeyLeft,
"lowerStartCamelObject": stringx.From(camelTableName).Untitle(),
"lowerStartCamelField": stringx.From(camelFieldName).Untitle(),
"lowerStartCamelField": paramJoinString,
"upperStartCamelPrimaryKey": table.PrimaryKey.Name.ToCamel(),
"originalField": wrapWithRawString(field.Name.Source()),
"originalField": originalFieldString,
})
if err != nil {
return nil, err
@@ -55,15 +73,22 @@ func genFindOneByField(table Table, withCache bool) (*findOneCode, error) {
t = util.With("findOneByFieldMethod").Parse(text)
var listMethod []string
for _, field := range table.Fields {
if field.IsPrimaryKey || !field.IsUniqueKey {
continue
for _, key := range table.UniqueCacheKey {
var inJoin, paramJoin Join
for _, f := range key.Fields {
param := stringx.From(f.Name.ToCamel()).Untitle()
inJoin = append(inJoin, fmt.Sprintf("%s %s", param, f.DataType))
paramJoin = append(paramJoin, param)
}
var in string
if len(inJoin) > 0 {
in = inJoin.With(", ").Source()
}
camelFieldName := field.Name.ToCamel()
output, err := t.Execute(map[string]interface{}{
"upperStartCamelObject": camelTableName,
"upperField": camelFieldName,
"in": fmt.Sprintf("%s %s", stringx.From(camelFieldName).Untitle(), field.DataType),
"upperField": key.FieldNameJoin.Camel().With("").Source(),
"in": in,
})
if err != nil {
return nil, err
@@ -80,7 +105,7 @@ func genFindOneByField(table Table, withCache bool) (*findOneCode, error) {
out, err := util.With("findOneByFieldExtraMethod").Parse(text).Execute(map[string]interface{}{
"upperStartCamelObject": camelTableName,
"primaryKeyLeft": table.CacheKey[table.PrimaryKey.Name.Source()].Left,
"primaryKeyLeft": table.PrimaryCacheKey.VarLeft,
"lowerStartCamelObject": stringx.From(camelTableName).Untitle(),
"originalPrimaryField": wrapWithRawString(table.PrimaryKey.Name.Source()),
})

View File

@@ -99,10 +99,10 @@ func (g *defaultGenerator) StartFromDDL(source string, withCache bool) error {
return g.createFile(modelList)
}
func (g *defaultGenerator) StartFromInformationSchema(db string, columns map[string][]*model.Column, withCache bool) error {
func (g *defaultGenerator) StartFromInformationSchema(tables map[string]*model.Table, withCache bool) error {
m := make(map[string]string)
for tableName, column := range columns {
table, err := parser.ConvertColumn(db, tableName, column)
for _, each := range tables {
table, err := parser.ConvertDataType(each)
if err != nil {
return err
}
@@ -182,10 +182,12 @@ func (g *defaultGenerator) genFromDDL(source string, withCache bool) (map[string
if err != nil {
return nil, err
}
code, err := g.genModel(*table, withCache)
if err != nil {
return nil, err
}
m[table.Name.Source()] = code
}
@@ -195,8 +197,9 @@ func (g *defaultGenerator) genFromDDL(source string, withCache bool) (map[string
// Table defines mysql table
type Table struct {
parser.Table
CacheKey map[string]Key
ContainsUniqueKey bool
PrimaryCacheKey Key
UniqueCacheKey []Key
ContainsUniqueCacheKey bool
}
func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, error) {
@@ -204,10 +207,7 @@ func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, er
return "", fmt.Errorf("table %s: missing primary key", in.Name.Source())
}
m, err := genCacheKeys(in)
if err != nil {
return "", err
}
primaryKey, uniqueKey := genCacheKeys(in)
importsCode, err := genImports(withCache, in.ContainsTime())
if err != nil {
@@ -216,15 +216,9 @@ func (g *defaultGenerator) genModel(in parser.Table, withCache bool) (string, er
var table Table
table.Table = in
table.CacheKey = m
var containsUniqueCache = false
for _, item := range table.Fields {
if item.IsUniqueKey {
containsUniqueCache = true
break
}
}
table.ContainsUniqueKey = containsUniqueCache
table.PrimaryCacheKey = primaryKey
table.UniqueCacheKey = uniqueKey
table.ContainsUniqueCacheKey = len(uniqueKey) > 0
varsCode, err := genVars(table, withCache)
if err != nil {

View File

@@ -16,18 +16,15 @@ import (
)
var (
source = "CREATE TABLE `test_user_info` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `nanosecond` bigint NOT NULL DEFAULT '0',\n `data` varchar(255) DEFAULT '',\n `content` json DEFAULT NULL,\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `nanosecond_unique` (`nanosecond`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;"
source = "CREATE TABLE `test_user` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `mobile` varchar(255) COLLATE utf8mb4_bin NOT NULL,\n `class` bigint NOT NULL,\n `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `mobile_unique` (`mobile`),\n UNIQUE KEY `class_name_unique` (`class`,`name`),\n KEY `create_index` (`create_time`),\n KEY `name_index` (`name`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;"
)
func TestCacheModel(t *testing.T) {
logx.Disable()
_ = Clean()
dir, _ := filepath.Abs("./testmodel")
dir := filepath.Join(t.TempDir(), "./testmodel")
cacheDir := filepath.Join(dir, "cache")
noCacheDir := filepath.Join(dir, "nocache")
defer func() {
_ = os.RemoveAll(dir)
}()
g, err := NewDefaultGenerator(cacheDir, &config.Config{
NamingFormat: "GoZero",
})
@@ -36,7 +33,7 @@ func TestCacheModel(t *testing.T) {
err = g.StartFromDDL(source, true)
assert.Nil(t, err)
assert.True(t, func() bool {
_, err := os.Stat(filepath.Join(cacheDir, "TestUserInfoModel.go"))
_, err := os.Stat(filepath.Join(cacheDir, "TestUserModel.go"))
return err == nil
}())
g, err = NewDefaultGenerator(noCacheDir, &config.Config{
@@ -47,7 +44,7 @@ func TestCacheModel(t *testing.T) {
err = g.StartFromDDL(source, false)
assert.Nil(t, err)
assert.True(t, func() bool {
_, err := os.Stat(filepath.Join(noCacheDir, "testuserinfomodel.go"))
_, err := os.Stat(filepath.Join(noCacheDir, "testusermodel.go"))
return err == nil
}())
}
@@ -69,7 +66,7 @@ func TestNamingModel(t *testing.T) {
err = g.StartFromDDL(source, true)
assert.Nil(t, err)
assert.True(t, func() bool {
_, err := os.Stat(filepath.Join(camelDir, "TestUserInfoModel.go"))
_, err := os.Stat(filepath.Join(camelDir, "TestUserModel.go"))
return err == nil
}())
g, err = NewDefaultGenerator(snakeDir, &config.Config{
@@ -80,7 +77,7 @@ func TestNamingModel(t *testing.T) {
err = g.StartFromDDL(source, true)
assert.Nil(t, err)
assert.True(t, func() bool {
_, err := os.Stat(filepath.Join(snakeDir, "test_user_info_model.go"))
_, err := os.Stat(filepath.Join(snakeDir, "test_user_model.go"))
return err == nil
}())
}

View File

@@ -12,12 +12,9 @@ import (
func genInsert(table Table, withCache bool) (string, string, error) {
keySet := collection.NewSet()
keyVariableSet := collection.NewSet()
for fieldName, key := range table.CacheKey {
if fieldName == table.PrimaryKey.Name.Source() {
continue
}
for _, key := range table.UniqueCacheKey {
keySet.AddStr(key.DataKeyExpression)
keyVariableSet.AddStr(key.Variable)
keyVariableSet.AddStr(key.KeyLeft)
}
expressions := make([]string, 0)
@@ -27,12 +24,17 @@ func genInsert(table Table, withCache bool) (string, string, error) {
if camel == "CreateTime" || camel == "UpdateTime" {
continue
}
if field.IsPrimaryKey && table.PrimaryKey.AutoIncrement {
continue
if field.Name.Source() == table.PrimaryKey.Name.Source() {
if table.PrimaryKey.AutoIncrement {
continue
}
}
expressions = append(expressions, "?")
expressionValues = append(expressionValues, "data."+camel)
}
camel := table.Name.ToCamel()
text, err := util.LoadTemplate(category, insertTemplateFile, template.Insert)
if err != nil {
@@ -43,7 +45,7 @@ func genInsert(table Table, withCache bool) (string, string, error) {
Parse(text).
Execute(map[string]interface{}{
"withCache": withCache,
"containsIndexCache": table.ContainsUniqueKey,
"containsIndexCache": table.ContainsUniqueCacheKey,
"upperStartCamelObject": camel,
"lowerStartCamelObject": stringx.From(camel).Untitle(),
"expression": strings.Join(expressions, ", "),
@@ -61,11 +63,9 @@ func genInsert(table Table, withCache bool) (string, string, error) {
return "", "", err
}
insertMethodOutput, err := util.With("insertMethod").
Parse(text).
Execute(map[string]interface{}{
"upperStartCamelObject": camel,
})
insertMethodOutput, err := util.With("insertMethod").Parse(text).Execute(map[string]interface{}{
"upperStartCamelObject": camel,
})
if err != nil {
return "", "", err
}

View File

@@ -2,61 +2,163 @@ package gen
import (
"fmt"
"sort"
"strings"
"github.com/tal-tech/go-zero/tools/goctl/model/sql/parser"
"github.com/tal-tech/go-zero/tools/goctl/util/stringx"
)
// Key defines cache key variable for generating code
// Key describes cache key
type Key struct {
// VarExpression likes cacheUserIdPrefix = "cache#User#id#"
// VarLeft describes the varible of cache key expression which likes cacheUserIdPrefix
VarLeft string
// VarRight describes the value of cache key expression which likes "cache#user#id#"
VarRight string
// VarExpression describes the cache key expression which 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)
// KeyLeft describes the varible of key definiation expression which likes userKey
KeyLeft string
// KeyRight describes the value of key definiation expression which likes fmt.Sprintf("%s%v", cacheUserPrefix, user)
KeyRight string
// DataKeyRight describes data key likes fmt.Sprintf("%s%v", cacheUserPrefix, data.User)
DataKeyRight string
// KeyExpression describes key expression likes userKey := fmt.Sprintf("%s%v", cacheUserPrefix, user)
KeyExpression string
// DataKeyExpression likes userIdKey: = fmt.Sprintf("cache#user#id#%v", data.userId)
// DataKeyExpression describes data key expression likes userKey := fmt.Sprintf("%s%v", cacheUserPrefix, data.User)
DataKeyExpression string
// RespKeyExpression likes userIdKey: = fmt.Sprintf("cache#user#id#%v", resp.userId)
RespKeyExpression string
// FieldNameJoin describes the filed slice of table
FieldNameJoin Join
// Fields describes the fields of table
Fields []*parser.Field
}
// key-数据库原始字段名,value-缓存key相关数据
func genCacheKeys(table parser.Table) (map[string]Key, error) {
fields := table.Fields
m := make(map[string]Key)
camelTableName := table.Name.ToCamel()
lowerStartCamelTableName := stringx.From(camelTableName).Untitle()
for _, field := range fields {
if field.IsUniqueKey || field.IsPrimaryKey {
camelFieldName := field.Name.ToCamel()
lowerStartCamelFieldName := stringx.From(camelFieldName).Untitle()
left := fmt.Sprintf("cache%s%sPrefix", camelTableName, camelFieldName)
if strings.ToLower(camelFieldName) == strings.ToLower(camelTableName) {
left = fmt.Sprintf("cache%sPrefix", camelTableName)
}
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)
}
// Join describes an alias of string slice
type Join []string
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),
}
}
func genCacheKeys(table parser.Table) (Key, []Key) {
var primaryKey Key
var uniqueKey []Key
primaryKey = genCacheKey(table.Name, []*parser.Field{&table.PrimaryKey.Field})
for _, each := range table.UniqueIndex {
uniqueKey = append(uniqueKey, genCacheKey(table.Name, each))
}
sort.Slice(uniqueKey, func(i, j int) bool {
return uniqueKey[i].VarLeft < uniqueKey[j].VarLeft
})
return primaryKey, uniqueKey
}
func genCacheKey(table stringx.String, in []*parser.Field) Key {
var (
varLeftJoin, varRightJon, fieldNameJoin Join
varLeft, varRight, varExpression string
keyLeftJoin, keyRightJoin, keyRightArgJoin, dataRightJoin Join
keyLeft, keyRight, dataKeyRight, keyExpression, dataKeyExpression string
)
varLeftJoin = append(varLeftJoin, "cache", table.Source())
varRightJon = append(varRightJon, "cache", table.Source())
keyLeftJoin = append(keyLeftJoin, table.Source())
for _, each := range in {
varLeftJoin = append(varLeftJoin, each.Name.Source())
varRightJon = append(varRightJon, each.Name.Source())
keyLeftJoin = append(keyLeftJoin, each.Name.Source())
keyRightJoin = append(keyRightJoin, stringx.From(each.Name.ToCamel()).Untitle())
keyRightArgJoin = append(keyRightArgJoin, "%v")
dataRightJoin = append(dataRightJoin, "data."+each.Name.ToCamel())
fieldNameJoin = append(fieldNameJoin, each.Name.Source())
}
varLeftJoin = append(varLeftJoin, "prefix")
keyLeftJoin = append(keyLeftJoin, "key")
varLeft = varLeftJoin.Camel().With("").Untitle()
varRight = fmt.Sprintf(`"%s"`, varRightJon.Camel().Untitle().With("#").Source()+"#")
varExpression = fmt.Sprintf(`%s = %s`, varLeft, varRight)
keyLeft = keyLeftJoin.Camel().With("").Untitle()
keyRight = fmt.Sprintf(`fmt.Sprintf("%s%s", %s, %s)`, "%s", keyRightArgJoin.With("").Source(), varLeft, keyRightJoin.With(", ").Source())
dataKeyRight = fmt.Sprintf(`fmt.Sprintf("%s%s", %s, %s)`, "%s", keyRightArgJoin.With("").Source(), varLeft, dataRightJoin.With(", ").Source())
keyExpression = fmt.Sprintf("%s := %s", keyLeft, keyRight)
dataKeyExpression = fmt.Sprintf("%s := %s", keyLeft, dataKeyRight)
return Key{
VarLeft: varLeft,
VarRight: varRight,
VarExpression: varExpression,
KeyLeft: keyLeft,
KeyRight: keyRight,
DataKeyRight: dataKeyRight,
KeyExpression: keyExpression,
DataKeyExpression: dataKeyExpression,
Fields: in,
FieldNameJoin: fieldNameJoin,
}
}
// Title convert items into Title and return
func (j Join) Title() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).Title())
}
return m, nil
return join
}
// Camel convert items into Camel and return
func (j Join) Camel() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).ToCamel())
}
return join
}
// Snake convert items into Snake and return
func (j Join) Snake() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).ToSnake())
}
return join
}
// Snake convert items into Untitle and return
func (j Join) Untitle() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).Untitle())
}
return join
}
// Upper convert items into Upper and return
func (j Join) Upper() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).Upper())
}
return join
}
// Lower convert items into Lower and return
func (j Join) Lower() Join {
var join Join
for _, each := range j {
join = append(join, stringx.From(each).Lower())
}
return join
}
// With convert items into With and return
func (j Join) With(sep string) stringx.String {
return stringx.From(strings.Join(j, sep))
}

View File

@@ -1,7 +1,7 @@
package gen
import (
"fmt"
"sort"
"testing"
"github.com/stretchr/testify/assert"
@@ -10,62 +10,156 @@ import (
)
func TestGenCacheKeys(t *testing.T) {
m, err := genCacheKeys(parser.Table{
primaryField := &parser.Field{
Name: stringx.From("id"),
DataBaseType: "bigint",
DataType: "int64",
Comment: "自增id",
SeqInIndex: 1,
}
mobileField := &parser.Field{
Name: stringx.From("mobile"),
DataBaseType: "varchar",
DataType: "string",
Comment: "手机号",
SeqInIndex: 1,
}
classField := &parser.Field{
Name: stringx.From("class"),
DataBaseType: "varchar",
DataType: "string",
Comment: "班级",
SeqInIndex: 1,
}
nameField := &parser.Field{
Name: stringx.From("name"),
DataBaseType: "varchar",
DataType: "string",
Comment: "姓名",
SeqInIndex: 2,
}
primariCacheKey, uniqueCacheKey := genCacheKeys(parser.Table{
Name: stringx.From("user"),
PrimaryKey: parser.Primary{
Field: parser.Field{
Name: stringx.From("id"),
DataBaseType: "bigint",
DataType: "int64",
IsPrimaryKey: true,
IsUniqueKey: false,
Comment: "自增id",
},
Field: *primaryField,
AutoIncrement: true,
},
Fields: []parser.Field{
{
Name: stringx.From("mobile"),
DataBaseType: "varchar",
DataType: "string",
IsPrimaryKey: false,
IsUniqueKey: true,
Comment: "手机号",
UniqueIndex: map[string][]*parser.Field{
"mobile_unique": []*parser.Field{
mobileField,
},
{
Name: stringx.From("name"),
DataBaseType: "varchar",
DataType: "string",
IsPrimaryKey: false,
IsUniqueKey: true,
Comment: "姓名",
"class_name_unique": []*parser.Field{
classField,
nameField,
},
},
NormalIndex: nil,
Fields: []*parser.Field{
primaryField,
mobileField,
classField,
nameField,
{
Name: stringx.From("createTime"),
DataBaseType: "timestamp",
DataType: "time.Time",
IsPrimaryKey: false,
IsUniqueKey: false,
Comment: "创建时间",
},
{
Name: stringx.From("updateTime"),
DataBaseType: "timestamp",
DataType: "time.Time",
IsPrimaryKey: false,
IsUniqueKey: false,
Comment: "更新时间",
},
},
})
assert.Nil(t, err)
for fieldName, key := range m {
name := stringx.From(fieldName)
assert.Equal(t, fmt.Sprintf(`cacheUser%sPrefix = "cache#User#%s#"`, name.ToCamel(), name.Untitle()), key.VarExpression)
assert.Equal(t, fmt.Sprintf(`cacheUser%sPrefix`, name.ToCamel()), key.Left)
assert.Equal(t, fmt.Sprintf(`cache#User#%s#`, name.Untitle()), key.Right)
assert.Equal(t, fmt.Sprintf(`user%sKey`, name.ToCamel()), key.Variable)
assert.Equal(t, `user`+name.ToCamel()+`Key := fmt.Sprintf("%s%v", cacheUser`+name.ToCamel()+`Prefix,`+name.Untitle()+`)`, key.KeyExpression)
}
t.Run("primaryCacheKey", func(t *testing.T) {
assert.Equal(t, true, func() bool {
return cacheKeyEqual(primariCacheKey, Key{
VarLeft: "cacheUserIdPrefix",
VarRight: `"cache#user#id#"`,
VarExpression: `cacheUserIdPrefix = "cache#user#id#"`,
KeyLeft: "userIdKey",
KeyRight: `fmt.Sprintf("%s%v", cacheUserIdPrefix, id)`,
DataKeyRight: `fmt.Sprintf("%s%v", cacheUserIdPrefix, data.Id)`,
KeyExpression: `userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, id)`,
DataKeyExpression: `userIdKey := fmt.Sprintf("%s%v", cacheUserIdPrefix, data.Id)`,
FieldNameJoin: []string{"id"},
})
}())
})
t.Run("uniqueCacheKey", func(t *testing.T) {
assert.Equal(t, true, func() bool {
expected := []Key{
{
VarLeft: "cacheUserClassNamePrefix",
VarRight: `"cache#user#class#name#"`,
VarExpression: `cacheUserClassNamePrefix = "cache#user#class#name#"`,
KeyLeft: "userClassNameKey",
KeyRight: `fmt.Sprintf("%s%v%v", cacheUserClassNamePrefix, class, name)`,
DataKeyRight: `fmt.Sprintf("%s%v%v", cacheUserClassNamePrefix, data.Class, data.Name)`,
KeyExpression: `userClassNameKey := fmt.Sprintf("%s%v%v", cacheUserClassNamePrefix, class, name)`,
DataKeyExpression: `userClassNameKey := fmt.Sprintf("%s%v%v", cacheUserClassNamePrefix, data.Class, data.Name)`,
FieldNameJoin: []string{"class", "name"},
},
{
VarLeft: "cacheUserMobilePrefix",
VarRight: `"cache#user#mobile#"`,
VarExpression: `cacheUserMobilePrefix = "cache#user#mobile#"`,
KeyLeft: "userMobileKey",
KeyRight: `fmt.Sprintf("%s%v", cacheUserMobilePrefix, mobile)`,
DataKeyRight: `fmt.Sprintf("%s%v", cacheUserMobilePrefix, data.Mobile)`,
KeyExpression: `userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, mobile)`,
DataKeyExpression: `userMobileKey := fmt.Sprintf("%s%v", cacheUserMobilePrefix, data.Mobile)`,
FieldNameJoin: []string{"mobile"},
},
}
sort.Slice(uniqueCacheKey, func(i, j int) bool {
return uniqueCacheKey[i].VarLeft < uniqueCacheKey[j].VarLeft
})
if len(expected) != len(uniqueCacheKey) {
return false
}
for index, each := range uniqueCacheKey {
expecting := expected[index]
if !cacheKeyEqual(expecting, each) {
return false
}
}
return true
}())
})
}
func cacheKeyEqual(k1 Key, k2 Key) bool {
k1Join := k1.FieldNameJoin
k2Join := k2.FieldNameJoin
sort.Strings(k1Join)
sort.Strings(k2Join)
if len(k1Join) != len(k2Join) {
return false
}
for index, each := range k1Join {
k2Item := k2Join[index]
if each != k2Item {
return false
}
}
return k1.VarLeft == k2.VarLeft &&
k1.VarRight == k2.VarRight &&
k1.VarExpression == k2.VarExpression &&
k1.KeyLeft == k2.KeyLeft &&
k1.KeyRight == k2.KeyRight &&
k1.DataKeyRight == k2.DataKeyRight &&
k1.DataKeyExpression == k2.DataKeyExpression &&
k1.KeyExpression == k2.KeyExpression
}

View File

@@ -16,7 +16,7 @@ func genUpdate(table Table, withCache bool) (string, string, error) {
continue
}
if field.IsPrimaryKey {
if field.Name.Source() == table.PrimaryKey.Name.Source() {
continue
}
@@ -35,8 +35,8 @@ func genUpdate(table Table, withCache bool) (string, string, error) {
Execute(map[string]interface{}{
"withCache": withCache,
"upperStartCamelObject": camelTableName,
"primaryCacheKey": table.CacheKey[table.PrimaryKey.Name.Source()].DataKeyExpression,
"primaryKeyVariable": table.CacheKey[table.PrimaryKey.Name.Source()].Variable,
"primaryCacheKey": table.PrimaryCacheKey.DataKeyExpression,
"primaryKeyVariable": table.PrimaryCacheKey.KeyLeft,
"lowerStartCamelObject": stringx.From(camelTableName).Untitle(),
"originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source()),
"expressionValues": strings.Join(expressionValues, ", "),

View File

@@ -10,26 +10,26 @@ import (
func genVars(table Table, withCache bool) (string, error) {
keys := make([]string, 0)
for _, v := range table.CacheKey {
keys = append(keys, table.PrimaryCacheKey.VarExpression)
for _, v := range table.UniqueCacheKey {
keys = append(keys, v.VarExpression)
}
camel := table.Name.ToCamel()
text, err := util.LoadTemplate(category, varTemplateFile, template.Vars)
if err != nil {
return "", err
}
output, err := util.With("var").
Parse(text).
GoFmt(true).
Execute(map[string]interface{}{
"lowerStartCamelObject": stringx.From(camel).Untitle(),
"upperStartCamelObject": camel,
"cacheKeys": strings.Join(keys, "\n"),
"autoIncrement": table.PrimaryKey.AutoIncrement,
"originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source()),
"withCache": withCache,
})
output, err := util.With("var").Parse(text).
GoFmt(true).Execute(map[string]interface{}{
"lowerStartCamelObject": stringx.From(camel).Untitle(),
"upperStartCamelObject": camel,
"cacheKeys": strings.Join(keys, "\n"),
"autoIncrement": table.PrimaryKey.AutoIncrement,
"originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source()),
"withCache": withCache,
})
if err != nil {
return "", err
}