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

91 lines
2.4 KiB
Go
Raw Normal View History

2020-07-29 17:11:41 +08:00
package gen
import (
"fmt"
"sort"
2020-07-29 17:11:41 +08:00
"strings"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
"github.com/zeromicro/go-zero/tools/goctl/util/stringx"
2020-07-29 17:11:41 +08:00
)
func genInsert(table Table, withCache, postgreSql bool) (string, string, error) {
keySet := collection.NewSet()
keyVariableSet := collection.NewSet()
2021-10-29 09:55:41 +08:00
keySet.AddStr(table.PrimaryCacheKey.DataKeyExpression)
keyVariableSet.AddStr(table.PrimaryCacheKey.KeyLeft)
2021-03-01 17:29:07 +08:00
for _, key := range table.UniqueCacheKey {
keySet.AddStr(key.DataKeyExpression)
2021-03-01 17:29:07 +08:00
keyVariableSet.AddStr(key.KeyLeft)
}
keys := keySet.KeysStr()
sort.Strings(keys)
keyVars := keyVariableSet.KeysStr()
sort.Strings(keyVars)
2020-07-29 17:11:41 +08:00
expressions := make([]string, 0)
expressionValues := make([]string, 0)
var count int
for _, field := range table.Fields {
camel := util.SafeString(field.Name.ToCamel())
if table.isIgnoreColumns(field.Name.Source()) {
continue
}
2021-03-01 17:29:07 +08:00
if field.Name.Source() == table.PrimaryKey.Name.Source() {
if table.PrimaryKey.AutoIncrement {
continue
}
2020-07-29 17:11:41 +08:00
}
2021-03-01 17:29:07 +08:00
count += 1
if postgreSql {
expressions = append(expressions, fmt.Sprintf("$%d", count))
} else {
expressions = append(expressions, "?")
}
expressionValues = append(expressionValues, "data."+camel)
2020-07-29 17:11:41 +08:00
}
2021-03-01 17:29:07 +08:00
camel := table.Name.ToCamel()
text, err := pathx.LoadTemplate(category, insertTemplateFile, template.Insert)
if err != nil {
return "", "", err
}
output, err := util.With("insert").
Parse(text).
Execute(map[string]any{
"withCache": withCache,
"upperStartCamelObject": camel,
2020-12-08 23:01:25 +08:00
"lowerStartCamelObject": stringx.From(camel).Untitle(),
"expression": strings.Join(expressions, ", "),
"expressionValues": strings.Join(expressionValues, ", "),
"keys": strings.Join(keys, "\n"),
"keyValues": strings.Join(keyVars, ", "),
"data": table,
})
2020-07-29 17:11:41 +08:00
if err != nil {
return "", "", err
2020-07-29 17:11:41 +08:00
}
// interface method
text, err = pathx.LoadTemplate(category, insertTemplateMethodFile, template.InsertMethod)
if err != nil {
return "", "", err
}
insertMethodOutput, err := util.With("insertMethod").Parse(text).Execute(map[string]any{
2021-03-01 17:29:07 +08:00
"upperStartCamelObject": camel,
"data": table,
2021-03-01 17:29:07 +08:00
})
if err != nil {
return "", "", err
}
return output.String(), insertMethodOutput.String(), nil
2020-07-29 17:11:41 +08:00
}