bookmodel.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package model
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "strings"
  6. "github.com/tal-tech/go-zero/core/stores/cache"
  7. "github.com/tal-tech/go-zero/core/stores/sqlc"
  8. "github.com/tal-tech/go-zero/core/stores/sqlx"
  9. "github.com/tal-tech/go-zero/core/stringx"
  10. "github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
  11. )
  12. var (
  13. bookFieldNames = builderx.FieldNames(&Book{})
  14. bookRows = strings.Join(bookFieldNames, ",")
  15. bookRowsExpectAutoSet = strings.Join(stringx.Remove(bookFieldNames, "create_time", "update_time"), ",")
  16. bookRowsWithPlaceHolder = strings.Join(stringx.Remove(bookFieldNames, "book", "create_time", "update_time"), "=?,") + "=?"
  17. cacheBookBookPrefix = "cache#Book#book#"
  18. )
  19. type (
  20. BookModel struct {
  21. sqlc.CachedConn
  22. table string
  23. }
  24. Book struct {
  25. Book string `db:"book"` // book name
  26. Price int64 `db:"price"` // book price
  27. }
  28. )
  29. func NewBookModel(conn sqlx.SqlConn, c cache.CacheConf, table string) *BookModel {
  30. return &BookModel{
  31. CachedConn: sqlc.NewConn(conn, c),
  32. table: table,
  33. }
  34. }
  35. func (m *BookModel) Insert(data Book) (sql.Result, error) {
  36. query := `insert into ` + m.table + ` (` + bookRowsExpectAutoSet + `) values (?, ?)`
  37. return m.ExecNoCache(query, data.Book, data.Price)
  38. }
  39. func (m *BookModel) FindOne(book string) (*Book, error) {
  40. bookBookKey := fmt.Sprintf("%s%v", cacheBookBookPrefix, book)
  41. var resp Book
  42. err := m.QueryRow(&resp, bookBookKey, func(conn sqlx.SqlConn, v interface{}) error {
  43. query := `select ` + bookRows + ` from ` + m.table + ` where book = ? limit 1`
  44. return conn.QueryRow(v, query, book)
  45. })
  46. switch err {
  47. case nil:
  48. return &resp, nil
  49. case sqlc.ErrNotFound:
  50. return nil, ErrNotFound
  51. default:
  52. return nil, err
  53. }
  54. }
  55. func (m *BookModel) Update(data Book) error {
  56. bookBookKey := fmt.Sprintf("%s%v", cacheBookBookPrefix, data.Book)
  57. _, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
  58. query := `update ` + m.table + ` set ` + bookRowsWithPlaceHolder + ` where book = ?`
  59. return conn.Exec(query, data.Price, data.Book)
  60. }, bookBookKey)
  61. return err
  62. }
  63. func (m *BookModel) Delete(book string) error {
  64. bookBookKey := fmt.Sprintf("%s%v", cacheBookBookPrefix, book)
  65. _, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
  66. query := `delete from ` + m.table + ` where book = ?`
  67. return conn.Exec(query, book)
  68. }, bookBookKey)
  69. return err
  70. }