fix: Useless delete cache logic in update (#1923)

* Fix bug: useless delete cache logic in update

* Format code
master
anqiansong 3 years ago committed by GitHub
parent ca88b69d24
commit 58787746db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -29,6 +29,5 @@ CREATE TABLE `student`
) DEFAULT NULL, ) DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT NULL, `update_time` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`type`) USING BTREE, PRIMARY KEY (`type`) USING BTREE
UNIQUE KEY `class_name_index` (`class`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

@ -11,8 +11,13 @@ import (
"github.com/zeromicro/go-zero/tools/goctl/util/stringx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx"
) )
func genUpdate(table Table, withCache, postgreSql bool) (string, string, error) { func genUpdate(table Table, withCache, postgreSql bool) (
string, string, error) {
expressionValues := make([]string, 0) expressionValues := make([]string, 0)
var pkg = "data."
if table.ContainsUniqueCacheKey {
pkg = "newData."
}
for _, field := range table.Fields { for _, field := range table.Fields {
camel := util.SafeString(field.Name.ToCamel()) camel := util.SafeString(field.Name.ToCamel())
if camel == "CreateTime" || camel == "UpdateTime" { if camel == "CreateTime" || camel == "UpdateTime" {
@ -23,7 +28,7 @@ func genUpdate(table Table, withCache, postgreSql bool) (string, string, error)
continue continue
} }
expressionValues = append(expressionValues, "data."+camel) expressionValues = append(expressionValues, pkg+camel)
} }
keySet := collection.NewSet() keySet := collection.NewSet()
@ -40,9 +45,14 @@ func genUpdate(table Table, withCache, postgreSql bool) (string, string, error)
sort.Strings(keyVars) sort.Strings(keyVars)
if postgreSql { if postgreSql {
expressionValues = append([]string{"data." + table.PrimaryKey.Name.ToCamel()}, expressionValues...) expressionValues = append(
[]string{pkg + table.PrimaryKey.Name.ToCamel()},
expressionValues...,
)
} else { } else {
expressionValues = append(expressionValues, "data."+table.PrimaryKey.Name.ToCamel()) expressionValues = append(
expressionValues, pkg+table.PrimaryKey.Name.ToCamel(),
)
} }
camelTableName := table.Name.ToCamel() camelTableName := table.Name.ToCamel()
text, err := pathx.LoadTemplate(category, updateTemplateFile, template.Update) text, err := pathx.LoadTemplate(category, updateTemplateFile, template.Update)
@ -50,21 +60,29 @@ func genUpdate(table Table, withCache, postgreSql bool) (string, string, error)
return "", "", err return "", "", err
} }
output, err := util.With("update"). output, err := util.With("update").Parse(text).Execute(
Parse(text). map[string]interface{}{
Execute(map[string]interface{}{
"withCache": withCache, "withCache": withCache,
"containsIndexCache": table.ContainsUniqueCacheKey,
"upperStartCamelObject": camelTableName, "upperStartCamelObject": camelTableName,
"keys": strings.Join(keys, "\n"), "keys": strings.Join(keys, "\n"),
"keyValues": strings.Join(keyVars, ", "), "keyValues": strings.Join(keyVars, ", "),
"primaryCacheKey": table.PrimaryCacheKey.DataKeyExpression, "primaryCacheKey": table.PrimaryCacheKey.DataKeyExpression,
"primaryKeyVariable": table.PrimaryCacheKey.KeyLeft, "primaryKeyVariable": table.PrimaryCacheKey.KeyLeft,
"lowerStartCamelObject": stringx.From(camelTableName).Untitle(), "lowerStartCamelObject": stringx.From(camelTableName).Untitle(),
"originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source(), postgreSql), "upperStartCamelPrimaryKey": util.EscapeGolangKeyword(
"expressionValues": strings.Join(expressionValues, ", "), stringx.From(table.PrimaryKey.Name.ToCamel()).Title(),
"postgreSql": postgreSql, ),
"data": table, "originalPrimaryKey": wrapWithRawString(
}) table.PrimaryKey.Name.Source(), postgreSql,
),
"expressionValues": strings.Join(
expressionValues, ", ",
),
"postgreSql": postgreSql,
"data": table,
},
)
if err != nil { if err != nil {
return "", "", nil return "", "", nil
} }
@ -75,12 +93,12 @@ func genUpdate(table Table, withCache, postgreSql bool) (string, string, error)
return "", "", err return "", "", err
} }
updateMethodOutput, err := util.With("updateMethod"). updateMethodOutput, err := util.With("updateMethod").Parse(text).Execute(
Parse(text). map[string]interface{}{
Execute(map[string]interface{}{
"upperStartCamelObject": camelTableName, "upperStartCamelObject": camelTableName,
"data": table, "data": table,
}) },
)
if err != nil { if err != nil {
return "", "", nil return "", "", nil
} }

@ -3,9 +3,14 @@ package template
const ( const (
// Update defines a template for generating update codes // Update defines a template for generating update codes
Update = ` Update = `
func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, data *{{.upperStartCamelObject}}) error { func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, {{if .containsIndexCache}}newData{{else}}data{{end}} *{{.upperStartCamelObject}}) error {
{{if .withCache}}{{.keys}} {{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, newData.{{.upperStartCamelPrimaryKey}})
_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { if err!=nil{
return err
}
{{end}} {{.keys}}
_, {{if .containsIndexCache}}err{{else}}err:{{end}}= m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, {{.expressionValues}}) return conn.ExecCtx(ctx, query, {{.expressionValues}})
}, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
@ -15,5 +20,5 @@ func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, dat
` `
// UpdateMethod defines an interface method template for generating update codes // UpdateMethod defines an interface method template for generating update codes
UpdateMethod = `Update(ctx context.Context, data *{{.upperStartCamelObject}}) error` UpdateMethod = `Update(ctx context.Context, newData *{{.upperStartCamelObject}}) error`
) )

@ -3,16 +3,18 @@ package template
import "fmt" import "fmt"
// Vars defines a template for var block in model // Vars defines a template for var block in model
var Vars = fmt.Sprintf(` var Vars = fmt.Sprintf(
`
var ( var (
{{.lowerStartCamelObject}}FieldNames = builder.RawFieldNames(&{{.upperStartCamelObject}}{}{{if .postgreSql}},true{{end}}) {{.lowerStartCamelObject}}FieldNames = builder.RawFieldNames(&{{.upperStartCamelObject}}{}{{if .postgreSql}},true{{end}})
{{.lowerStartCamelObject}}Rows = strings.Join({{.lowerStartCamelObject}}FieldNames, ",") {{.lowerStartCamelObject}}Rows = strings.Join({{.lowerStartCamelObject}}FieldNames, ",")
{{.lowerStartCamelObject}}RowsExpectAutoSet = {{if .postgreSql}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "%screate_time%s", "%supdate_time%s"), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "%screate_time%s", "%supdate_time%s"), ","){{end}} {{.lowerStartCamelObject}}RowsExpectAutoSet = {{if .postgreSql}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "%screate_time%s", "%supdate_time%s", "%screate_t%s", "%supdate_at%s"), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "%screate_time%s", "%supdate_time%s", "%screate_at%s", "%supdate_at%s"), ","){{end}}
{{.lowerStartCamelObject}}RowsWithPlaceHolder = {{if .postgreSql}}builder.PostgreSqlJoin(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "%screate_time%s", "%supdate_time%s")){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "%screate_time%s", "%supdate_time%s"), "=?,") + "=?"{{end}} {{.lowerStartCamelObject}}RowsWithPlaceHolder = {{if .postgreSql}}builder.PostgreSqlJoin(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "%screate_time%s", "%supdate_time%s", "%screate_at%s", "%supdate_at%s")){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "%screate_time%s", "%supdate_time%s", "%screate_at%s", "%supdate_at%s"), "=?,") + "=?"{{end}}
{{if .withCache}}{{.cacheKeys}}{{end}} {{if .withCache}}{{.cacheKeys}}{{end}}
) )
`, "", "", "", "", // postgreSql mode `, "", "", "", "", "", "", "", "", // postgreSql mode
"`", "`", "`", "`", "`", "`", "`", "`", "`", "`", "`", "`",
"", "", "", "", // postgreSql mode "", "", "", "", "", "", "", "", // postgreSql mode
"`", "`", "`", "`") "`", "`", "`", "`", "`", "`", "`", "`",
)

Loading…
Cancel
Save