update.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 genUpdate(table Table, withCache bool) (string, string, error) {
  10. expressionValues := make([]string, 0)
  11. for _, field := range table.Fields {
  12. camel := field.Name.ToCamel()
  13. if camel == "CreateTime" || camel == "UpdateTime" {
  14. continue
  15. }
  16. if field.Name.Source() == table.PrimaryKey.Name.Source() {
  17. continue
  18. }
  19. expressionValues = append(expressionValues, "data."+camel)
  20. }
  21. keySet := collection.NewSet()
  22. keyVariableSet := collection.NewSet()
  23. keySet.AddStr(table.PrimaryCacheKey.DataKeyExpression)
  24. keyVariableSet.AddStr(table.PrimaryCacheKey.KeyLeft)
  25. for _, key := range table.UniqueCacheKey {
  26. keySet.AddStr(key.DataKeyExpression)
  27. keyVariableSet.AddStr(key.KeyLeft)
  28. }
  29. expressionValues = append(expressionValues, "data."+table.PrimaryKey.Name.ToCamel())
  30. camelTableName := table.Name.ToCamel()
  31. text, err := util.LoadTemplate(category, updateTemplateFile, template.Update)
  32. if err != nil {
  33. return "", "", err
  34. }
  35. output, err := util.With("update").
  36. Parse(text).
  37. Execute(map[string]interface{}{
  38. "withCache": withCache,
  39. "upperStartCamelObject": camelTableName,
  40. "keys": strings.Join(keySet.KeysStr(), "\n"),
  41. "keyValues": strings.Join(keyVariableSet.KeysStr(), ", "),
  42. "primaryCacheKey": table.PrimaryCacheKey.DataKeyExpression,
  43. "primaryKeyVariable": table.PrimaryCacheKey.KeyLeft,
  44. "lowerStartCamelObject": stringx.From(camelTableName).Untitle(),
  45. "originalPrimaryKey": wrapWithRawString(table.PrimaryKey.Name.Source()),
  46. "expressionValues": strings.Join(expressionValues, ", "),
  47. })
  48. if err != nil {
  49. return "", "", nil
  50. }
  51. // update interface method
  52. text, err = util.LoadTemplate(category, updateMethodTemplateFile, template.UpdateMethod)
  53. if err != nil {
  54. return "", "", err
  55. }
  56. updateMethodOutput, err := util.With("updateMethod").
  57. Parse(text).
  58. Execute(map[string]interface{}{
  59. "upperStartCamelObject": camelTableName,
  60. })
  61. if err != nil {
  62. return "", "", nil
  63. }
  64. return output.String(), updateMethodOutput.String(), nil
  65. }