insert.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package gen
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/tal-tech/go-zero/core/collection"
  6. "github.com/tal-tech/go-zero/tools/goctl/model/sql/template"
  7. "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  9. )
  10. func genInsert(table Table, withCache, postgreSql bool) (string, string, error) {
  11. keySet := collection.NewSet()
  12. keyVariableSet := collection.NewSet()
  13. for _, key := range table.UniqueCacheKey {
  14. keySet.AddStr(key.DataKeyExpression)
  15. keyVariableSet.AddStr(key.KeyLeft)
  16. }
  17. expressions := make([]string, 0)
  18. expressionValues := make([]string, 0)
  19. var count int
  20. for _, field := range table.Fields {
  21. camel := field.Name.ToCamel()
  22. if camel == "CreateTime" || camel == "UpdateTime" {
  23. continue
  24. }
  25. if field.Name.Source() == table.PrimaryKey.Name.Source() {
  26. if table.PrimaryKey.AutoIncrement {
  27. continue
  28. }
  29. }
  30. count += 1
  31. if postgreSql {
  32. expressions = append(expressions, fmt.Sprintf("$%d", count))
  33. } else {
  34. expressions = append(expressions, "?")
  35. }
  36. expressionValues = append(expressionValues, "data."+camel)
  37. }
  38. camel := table.Name.ToCamel()
  39. text, err := util.LoadTemplate(category, insertTemplateFile, template.Insert)
  40. if err != nil {
  41. return "", "", err
  42. }
  43. output, err := util.With("insert").
  44. Parse(text).
  45. Execute(map[string]interface{}{
  46. "withCache": withCache,
  47. "containsIndexCache": table.ContainsUniqueCacheKey,
  48. "upperStartCamelObject": camel,
  49. "lowerStartCamelObject": stringx.From(camel).Untitle(),
  50. "expression": strings.Join(expressions, ", "),
  51. "expressionValues": strings.Join(expressionValues, ", "),
  52. "keys": strings.Join(keySet.KeysStr(), "\n"),
  53. "keyValues": strings.Join(keyVariableSet.KeysStr(), ", "),
  54. })
  55. if err != nil {
  56. return "", "", err
  57. }
  58. // interface method
  59. text, err = util.LoadTemplate(category, insertTemplateMethodFile, template.InsertMethod)
  60. if err != nil {
  61. return "", "", err
  62. }
  63. insertMethodOutput, err := util.With("insertMethod").Parse(text).Execute(map[string]interface{}{
  64. "upperStartCamelObject": camel,
  65. })
  66. if err != nil {
  67. return "", "", err
  68. }
  69. return output.String(), insertMethodOutput.String(), nil
  70. }