tdirectorymodel.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/zeromicro/go-zero/core/stores/sqlx"
  6. )
  7. var _ TDirectoryModel = (*customTDirectoryModel)(nil)
  8. type (
  9. // TDirectoryModel is an interface to be customized, add more methods here,
  10. // and implement the added methods in customTDirectoryModel.
  11. TDirectoryModel interface {
  12. tDirectoryModel
  13. FindPage(ctx context.Context, page, pageSize int64) ([]TDirectory, int64, error)
  14. DeleteByServiceId(ctx context.Context, serviceId int64) error
  15. WithSession(session sqlx.Session) TDirectoryModel
  16. }
  17. customTDirectoryModel struct {
  18. *defaultTDirectoryModel
  19. }
  20. )
  21. // NewTDirectoryModel returns a model for the database table.
  22. func NewTDirectoryModel(conn sqlx.SqlConn) TDirectoryModel {
  23. return &customTDirectoryModel{
  24. defaultTDirectoryModel: newTDirectoryModel(conn),
  25. }
  26. }
  27. func (m *customTDirectoryModel) FindPage(ctx context.Context, page, pageSize int64) ([]TDirectory, int64, error) {
  28. var total int64
  29. if err := m.conn.QueryRowCtx(ctx, &total, fmt.Sprintf("select count(*) from %s", m.table)); err != nil {
  30. return nil, 0, err
  31. }
  32. if total == 0 {
  33. return nil, 0, nil
  34. }
  35. offset := (page - 1) * pageSize
  36. query := fmt.Sprintf("select %s from %s order by `id` limit ? offset ?", tDirectoryRows, m.table)
  37. var resp []TDirectory
  38. if err := m.conn.QueryRowsCtx(ctx, &resp, query, pageSize, offset); err != nil {
  39. return nil, 0, err
  40. }
  41. return resp, total, nil
  42. }
  43. // DeleteByServiceId 删除某个服务下的全部保护目录,配合服务删除做级联清理。
  44. func (m *customTDirectoryModel) DeleteByServiceId(ctx context.Context, serviceId int64) error {
  45. query := fmt.Sprintf("delete from %s where `service_id` = ?", m.table)
  46. _, err := m.conn.ExecCtx(ctx, query, serviceId)
  47. return err
  48. }
  49. func (m *customTDirectoryModel) WithSession(session sqlx.Session) TDirectoryModel {
  50. return NewTDirectoryModel(sqlx.NewSqlConnFromSession(session))
  51. }