deletesql.go 959 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package sqlmodel
  2. import (
  3. "bytes"
  4. "strings"
  5. "text/template"
  6. )
  7. var deleteTemplate = `
  8. func ({{.pointer}} *{{.model}}Model) Delete({{.conditions}}) error {
  9. sql := ` + "`" + `delete from` + " ` + " + `{{.pointer}}.table ` + "+ `" + ` where {{.valueConditions}}` + "`\n" +
  10. ` _, err := {{.pointer}}.conn.Exec(sql, {{.values}})
  11. return err
  12. }
  13. `
  14. func (s *structExp) genDelete() (string, error) {
  15. idType := "string"
  16. if s.idAutoIncrement {
  17. idType = "int64"
  18. }
  19. conditionExp, valueConditions := s.buildCondition()
  20. t := template.Must(template.New("deleteTemplate").Parse(deleteTemplate))
  21. var tmplBytes bytes.Buffer
  22. err := t.Execute(&tmplBytes, map[string]string{
  23. "pointer": "m",
  24. "model": s.name,
  25. "idType": idType,
  26. "valueConditions": valueConditions,
  27. "conditions": conditionExp,
  28. "values": strings.Join(s.conditionNames(), ", "),
  29. })
  30. if err != nil {
  31. return "", err
  32. }
  33. return tmplBytes.String(), nil
  34. }