sysUserPermModel.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package userperm
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "github.com/zeromicro/go-zero/core/stores/cache"
  7. "github.com/zeromicro/go-zero/core/stores/sqlx"
  8. )
  9. var _ SysUserPermModel = (*customSysUserPermModel)(nil)
  10. type (
  11. SysUserPermModel interface {
  12. sysUserPermModel
  13. FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error)
  14. DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error
  15. }
  16. customSysUserPermModel struct {
  17. *defaultSysUserPermModel
  18. }
  19. )
  20. func NewSysUserPermModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysUserPermModel {
  21. return &customSysUserPermModel{
  22. defaultSysUserPermModel: newSysUserPermModel(conn, c, cachePrefix, opts...),
  23. }
  24. }
  25. func (m *customSysUserPermModel) FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error) {
  26. var ids []int64
  27. query := fmt.Sprintf(
  28. "SELECT up.`permId` FROM %s up INNER JOIN `sys_perm` p ON up.`permId` = p.`id` WHERE up.`userId` = ? AND up.`effect` = ? AND p.`productCode` = ? AND p.`status` = 1",
  29. m.table)
  30. if err := m.QueryRowsNoCacheCtx(ctx, &ids, query, userId, effect, productCode); err != nil {
  31. return nil, err
  32. }
  33. return ids, nil
  34. }
  35. func (m *customSysUserPermModel) DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error {
  36. var list []*SysUserPerm
  37. findQuery := fmt.Sprintf("SELECT %s FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?) FOR UPDATE", sysUserPermRows, m.table)
  38. if err := session.QueryRowsCtx(ctx, &list, findQuery, userId, productCode); err != nil {
  39. return err
  40. }
  41. if len(list) == 0 {
  42. return nil
  43. }
  44. keys := make([]string, 0, len(list)*2)
  45. for _, data := range list {
  46. keys = append(keys,
  47. fmt.Sprintf("%s%v", cacheSysUserPermIdPrefix, data.Id),
  48. fmt.Sprintf("%s%v:%v", cacheSysUserPermUserIdPermIdPrefix, data.UserId, data.PermId),
  49. )
  50. }
  51. _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) {
  52. query := fmt.Sprintf("DELETE FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?)", m.table)
  53. return session.ExecCtx(ctx, query, userId, productCode)
  54. }, keys...)
  55. return err
  56. }