insert.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. output, err := util.With("insert").
  34. Parse(template.Insert).
  35. Execute(map[string]interface{}{
  36. "withCache": withCache,
  37. "containsIndexCache": table.ContainsUniqueKey,
  38. "upperStartCamelObject": camel,
  39. "lowerStartCamelObject": stringx.From(camel).UnTitle(),
  40. "expression": strings.Join(expressions, ", "),
  41. "expressionValues": strings.Join(expressionValues, ", "),
  42. "keys": strings.Join(keySet.KeysStr(), "\n"),
  43. "keyValues": strings.Join(keyVariableSet.KeysStr(), ", "),
  44. })
  45. if err != nil {
  46. return "", err
  47. }
  48. return output.String(), nil
  49. }