updatesql.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package sqlmodel
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. "text/template"
  7. "github.com/tal-tech/go-zero/core/stringx"
  8. )
  9. var updateTemplate = `
  10. func ({{.pointer}} *{{.model}}Model) Update(data {{.model}}{{.conditions}}) error {
  11. sql := ` + "`" + `update ` + "` + " + `{{.pointer}}.table` + " + `" + ` set ` + "` +" + ` {{.modelWithLowerStart}}RowsWithPlaceHolder + ` + "` where" + ` {{.valueConditions}}` + "`\n" +
  12. ` _, err := {{.pointer}}.conn.Exec(sql, {{.values}})
  13. return err
  14. }
  15. `
  16. func (s *structExp) genUpdate() (string, error) {
  17. var updateValues []string
  18. var conditionsValues []string
  19. for _, field := range s.Fields {
  20. key := fmt.Sprintf("data.%s", field.name)
  21. if stringx.Contains(s.conditions, field.tag) ||
  22. stringx.Contains(s.conditions, field.name) {
  23. conditionsValues = append(conditionsValues, key)
  24. } else if !stringx.Contains(s.ignoreFields, field.name) && !stringx.Contains(s.ignoreFields, field.tag) {
  25. updateValues = append(updateValues, key)
  26. }
  27. }
  28. conditionExp, valueConditions := s.buildCondition()
  29. if len(s.conditions) == 1 && s.conditions[0] == s.primaryKey {
  30. conditionExp = ""
  31. } else {
  32. conditionExp = ", " + conditionExp
  33. }
  34. t := template.Must(template.New("updateTemplate").Parse(updateTemplate))
  35. var tmplBytes bytes.Buffer
  36. err := t.Execute(&tmplBytes, map[string]string{
  37. "pointer": "m",
  38. "model": s.name,
  39. "values": strings.Join(append(updateValues, conditionsValues...), ", "),
  40. "primaryKey": s.primaryKey,
  41. "valueConditions": valueConditions,
  42. "conditions": conditionExp,
  43. "modelWithLowerStart": fmtUnderLine2Camel(s.name, false),
  44. })
  45. if err != nil {
  46. return "", err
  47. }
  48. return tmplBytes.String(), nil
  49. }