insert.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package gen
  2. import (
  3. "strings"
  4. "git.i2edu.net/i2/go-zero/core/collection"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/model/sql/template"
  6. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  7. "git.i2edu.net/i2/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 _, key := range table.UniqueCacheKey {
  13. keySet.AddStr(key.DataKeyExpression)
  14. keyVariableSet.AddStr(key.KeyLeft)
  15. }
  16. expressions := make([]string, 0)
  17. expressionValues := make([]string, 0)
  18. for _, field := range table.Fields {
  19. camel := field.Name.ToCamel()
  20. if camel == "CreateTime" || camel == "UpdateTime" {
  21. continue
  22. }
  23. if field.Name.Source() == table.PrimaryKey.Name.Source() {
  24. if table.PrimaryKey.AutoIncrement {
  25. continue
  26. }
  27. }
  28. expressions = append(expressions, "?")
  29. expressionValues = append(expressionValues, "data."+camel)
  30. }
  31. camel := table.Name.ToCamel()
  32. text, err := util.LoadTemplate(category, insertTemplateFile, template.Insert)
  33. if err != nil {
  34. return "", "", err
  35. }
  36. output, err := util.With("insert").
  37. Parse(text).
  38. Execute(map[string]interface{}{
  39. "withCache": withCache,
  40. "containsIndexCache": table.ContainsUniqueCacheKey,
  41. "upperStartCamelObject": camel,
  42. "lowerStartCamelObject": stringx.From(camel).Untitle(),
  43. "expression": strings.Join(expressions, ", "),
  44. "expressionValues": strings.Join(expressionValues, ", "),
  45. "keys": strings.Join(keySet.KeysStr(), "\n"),
  46. "keyValues": strings.Join(keyVariableSet.KeysStr(), ", "),
  47. })
  48. if err != nil {
  49. return "", "", err
  50. }
  51. // interface method
  52. text, err = util.LoadTemplate(category, insertTemplateMethodFile, template.InsertMethod)
  53. if err != nil {
  54. return "", "", err
  55. }
  56. insertMethodOutput, err := util.With("insertMethod").Parse(text).Execute(map[string]interface{}{
  57. "upperStartCamelObject": camel,
  58. })
  59. if err != nil {
  60. return "", "", err
  61. }
  62. return output.String(), insertMethodOutput.String(), nil
  63. }