update.go 2.5 KB

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