querysql.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package sqlmodel
  2. import (
  3. "bytes"
  4. "strings"
  5. "text/template"
  6. )
  7. var queryOneTemplate = `
  8. func ({{.pointer}} *{{.model}}Model) FindOne({{.conditions}}) (*{{.model}}, error) {
  9. sql :=` + " `" + "select " + "` +" + ` {{.modelWithLowerStart}}Rows + ` + "`" + ` from ` + "` + " + `{{.pointer}}.table +` + " ` " + `where {{.valueConditions}} limit 1` + "`" + `
  10. var resp {{.model}}
  11. err := {{.pointer}}.conn.QueryRow(&resp, sql, {{.values}})
  12. if err != nil {
  13. if err == sqlx.ErrNotFound {
  14. return nil, ErrNotFound
  15. }
  16. return nil, err
  17. }
  18. return &resp, nil
  19. }
  20. `
  21. var queryListTemplate = `
  22. func ({{.pointer}} *{{.model}}Model) Find({{.conditions}}) ([]{{.model}}, error) {
  23. sql :=` + " `" + "select " + "` +" + ` {{.modelWithLowerStart}}Rows + ` + "`" + ` from ` + "` + " + `{{.pointer}}.table +` + " ` " + `where {{.valueConditions}}` + "`" + `
  24. var resp []{{.model}}
  25. err := {{.pointer}}.conn.QueryRows(&resp, sql, {{.values}})
  26. if err != nil {
  27. return nil, err
  28. }
  29. return resp, nil
  30. }
  31. `
  32. func (s *structExp) genQueryOne() (string, error) {
  33. conditionExp, valueConditions := s.buildCondition()
  34. t := template.Must(template.New("queryOneTemplate").Parse(queryOneTemplate))
  35. var tmplBytes bytes.Buffer
  36. err := t.Execute(&tmplBytes, map[string]string{
  37. "pointer": "m",
  38. "model": s.name,
  39. "conditions": conditionExp,
  40. "valueConditions": valueConditions,
  41. "values": strings.Join(s.conditionNames(), ", "),
  42. "modelWithLowerStart": fmtUnderLine2Camel(s.name, false),
  43. })
  44. if err != nil {
  45. return "", err
  46. }
  47. return tmplBytes.String(), nil
  48. }
  49. func (s *structExp) genQueryList() (string, error) {
  50. if len(s.conditions) == 1 && s.conditions[0] == s.primaryKey {
  51. return "", nil
  52. }
  53. conditionExp, valueConditions := s.buildCondition()
  54. t := template.Must(template.New("queryListTemplate").Parse(queryListTemplate))
  55. var tmplBytes bytes.Buffer
  56. err := t.Execute(&tmplBytes, map[string]string{
  57. "pointer": "m",
  58. "model": s.name,
  59. "conditions": conditionExp,
  60. "valueConditions": valueConditions,
  61. "values": strings.Join(s.conditionNames(), ", "),
  62. "modelWithLowerStart": fmtUnderLine2Camel(s.name, false),
  63. })
  64. if err != nil {
  65. return "", err
  66. }
  67. return tmplBytes.String(), nil
  68. }