package userperm import ( "context" "database/sql" "fmt" "perms-system-server/internal/consts" "github.com/zeromicro/go-zero/core/stores/cache" "github.com/zeromicro/go-zero/core/stores/sqlx" ) var _ SysUserPermModel = (*customSysUserPermModel)(nil) type ( SysUserPermModel interface { sysUserPermModel FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error) DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error } customSysUserPermModel struct { *defaultSysUserPermModel } ) func NewSysUserPermModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysUserPermModel { return &customSysUserPermModel{ defaultSysUserPermModel: newSysUserPermModel(conn, c, cachePrefix, opts...), } } func (m *customSysUserPermModel) FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error) { var ids []int64 query := fmt.Sprintf( "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` = ?", m.table) if err := m.QueryRowsNoCacheCtx(ctx, &ids, query, userId, effect, productCode, consts.StatusEnabled); err != nil { return nil, err } return ids, nil } func (m *customSysUserPermModel) DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error { var list []*SysUserPerm findQuery := fmt.Sprintf("SELECT %s FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?) FOR UPDATE", sysUserPermRows, m.table) if err := session.QueryRowsCtx(ctx, &list, findQuery, userId, productCode); err != nil { return err } if len(list) == 0 { return nil } keys := make([]string, 0, len(list)*2) for _, data := range list { keys = append(keys, fmt.Sprintf("%s%v", cacheSysUserPermIdPrefix, data.Id), fmt.Sprintf("%s%v:%v", cacheSysUserPermUserIdPermIdPrefix, data.UserId, data.PermId), ) } _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) { query := fmt.Sprintf("DELETE FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?)", m.table) return session.ExecCtx(ctx, query, userId, productCode) }, keys...) return err }