insert.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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, 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 _, field := range table.Fields {
  22. camel := field.Name.ToCamel()
  23. if camel == "CreateTime" || camel == "UpdateTime" {
  24. continue
  25. }
  26. if field.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. // interface method
  53. text, err = util.LoadTemplate(category, insertTemplateMethodFile, template.InsertMethod)
  54. if err != nil {
  55. return "", "", err
  56. }
  57. insertMethodOutput, err := util.With("insertMethod").
  58. Parse(text).
  59. Execute(map[string]interface{}{
  60. "upperStartCamelObject": camel,
  61. })
  62. if err != nil {
  63. return "", "", err
  64. }
  65. return output.String(), insertMethodOutput.String(), nil
  66. }