insert.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package gen
  2. import (
  3. "strings"
  4. "github.com/tal-tech/go-zero/core/collection"
  5. "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
  6. "github.com/tal-tech/go-zero/tools/goctl/util"
  7. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  8. )
  9. func genInsert(table Table, withCache bool) (string, error) {
  10. keySet := collection.NewSet()
  11. keyVariableSet := collection.NewSet()
  12. for fieldName, key := range table.CacheKey {
  13. if fieldName == table.PrimaryKey.Name.Source() {
  14. continue
  15. }
  16. keySet.AddStr(key.DataKeyExpression)
  17. keyVariableSet.AddStr(key.Variable)
  18. }
  19. expressions := make([]string, 0)
  20. expressionValues := make([]string, 0)
  21. for _, filed := range table.Fields {
  22. camel := filed.Name.ToCamel()
  23. if camel == "CreateTime" || camel == "UpdateTime" {
  24. continue
  25. }
  26. if filed.IsPrimaryKey && table.PrimaryKey.AutoIncrement {
  27. continue
  28. }
  29. expressions = append(expressions, "?")
  30. expressionValues = append(expressionValues, "data."+camel)
  31. }
  32. camel := table.Name.ToCamel()
  33. text, err := util.LoadTemplate(category, insertTemplateFile, template.Insert)
  34. if err != nil {
  35. return "", err
  36. }
  37. output, err := util.With("insert").
  38. Parse(text).
  39. Execute(map[string]interface{}{
  40. "withCache": withCache,
  41. "containsIndexCache": table.ContainsUniqueKey,
  42. "upperStartCamelObject": camel,
  43. "lowerStartCamelObject": stringx.From(camel).UnTitle(),
  44. "expression": strings.Join(expressions, ", "),
  45. "expressionValues": strings.Join(expressionValues, ", "),
  46. "keys": strings.Join(keySet.KeysStr(), "\n"),
  47. "keyValues": strings.Join(keyVariableSet.KeysStr(), ", "),
  48. })
  49. if err != nil {
  50. return "", err
  51. }
  52. return output.String(), nil
  53. }