tkeymodel.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/zeromicro/go-zero/core/stores/sqlx"
  6. )
  7. var _ TKeyModel = (*customTKeyModel)(nil)
  8. type (
  9. // TKeyModel is an interface to be customized, add more methods here,
  10. // and implement the added methods in customTKeyModel.
  11. TKeyModel interface {
  12. tKeyModel
  13. FindPage(ctx context.Context, page, pageSize int64) ([]TKey, int64, error)
  14. withSession(session sqlx.Session) TKeyModel
  15. }
  16. customTKeyModel struct {
  17. *defaultTKeyModel
  18. }
  19. )
  20. // NewTKeyModel returns a model for the database table.
  21. func NewTKeyModel(conn sqlx.SqlConn) TKeyModel {
  22. return &customTKeyModel{
  23. defaultTKeyModel: newTKeyModel(conn),
  24. }
  25. }
  26. func (m *customTKeyModel) FindPage(ctx context.Context, page, pageSize int64) ([]TKey, int64, error) {
  27. var total int64
  28. if err := m.conn.QueryRowCtx(ctx, &total, fmt.Sprintf("select count(*) from %s", m.table)); err != nil {
  29. return nil, 0, err
  30. }
  31. if total == 0 {
  32. return nil, 0, nil
  33. }
  34. offset := (page - 1) * pageSize
  35. query := fmt.Sprintf("select %s from %s order by `id` limit ? offset ?", tKeyRows, m.table)
  36. var resp []TKey
  37. if err := m.conn.QueryRowsCtx(ctx, &resp, query, pageSize, offset); err != nil {
  38. return nil, 0, err
  39. }
  40. return resp, total, nil
  41. }
  42. func (m *customTKeyModel) withSession(session sqlx.Session) TKeyModel {
  43. return NewTKeyModel(sqlx.NewSqlConnFromSession(session))
  44. }