sysRolePermModel.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package roleperm
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/zeromicro/go-zero/core/stores/cache"
  7. "github.com/zeromicro/go-zero/core/stores/sqlx"
  8. )
  9. var _ SysRolePermModel = (*customSysRolePermModel)(nil)
  10. type (
  11. SysRolePermModel interface {
  12. sysRolePermModel
  13. FindPermIdsByRoleId(ctx context.Context, roleId int64) ([]int64, error)
  14. FindPermIdsByRoleIds(ctx context.Context, roleIds []int64) ([]int64, error)
  15. DeleteByRoleId(ctx context.Context, roleId int64) error
  16. DeleteByRoleIdTx(ctx context.Context, session sqlx.Session, roleId int64) error
  17. }
  18. customSysRolePermModel struct {
  19. *defaultSysRolePermModel
  20. }
  21. )
  22. func NewSysRolePermModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysRolePermModel {
  23. return &customSysRolePermModel{
  24. defaultSysRolePermModel: newSysRolePermModel(conn, c, cachePrefix, opts...),
  25. }
  26. }
  27. func (m *customSysRolePermModel) FindPermIdsByRoleId(ctx context.Context, roleId int64) ([]int64, error) {
  28. var ids []int64
  29. query := fmt.Sprintf("SELECT `permId` FROM %s WHERE `roleId` = ?", m.table)
  30. if err := m.QueryRowsNoCacheCtx(ctx, &ids, query, roleId); err != nil {
  31. return nil, err
  32. }
  33. return ids, nil
  34. }
  35. func (m *customSysRolePermModel) FindPermIdsByRoleIds(ctx context.Context, roleIds []int64) ([]int64, error) {
  36. if len(roleIds) == 0 {
  37. return nil, nil
  38. }
  39. placeholders := make([]string, len(roleIds))
  40. args := make([]interface{}, len(roleIds))
  41. for i, id := range roleIds {
  42. placeholders[i] = "?"
  43. args[i] = id
  44. }
  45. var ids []int64
  46. query := fmt.Sprintf("SELECT DISTINCT `permId` FROM %s WHERE `roleId` IN (%s)", m.table, strings.Join(placeholders, ","))
  47. if err := m.QueryRowsNoCacheCtx(ctx, &ids, query, args...); err != nil {
  48. return nil, err
  49. }
  50. return ids, nil
  51. }
  52. func (m *customSysRolePermModel) DeleteByRoleId(ctx context.Context, roleId int64) error {
  53. query := fmt.Sprintf("DELETE FROM %s WHERE `roleId` = ?", m.table)
  54. _, err := m.ExecNoCacheCtx(ctx, query, roleId)
  55. return err
  56. }
  57. func (m *customSysRolePermModel) DeleteByRoleIdTx(ctx context.Context, session sqlx.Session, roleId int64) error {
  58. query := fmt.Sprintf("DELETE FROM %s WHERE `roleId` = ?", m.table)
  59. _, err := session.ExecCtx(ctx, query, roleId)
  60. return err
  61. }