-- base_sys_user_role 角色授权去重
-- 只处理未软删除的有效授权；软删除历史记录不参与去重和唯一约束
-- 保留每组有效 userId + roleId 中 id 最小的一条，删除其余重复记录

-- 1. 执行前查看重复数据
SELECT
  "userId",
  "roleId",
  COUNT(*) AS cnt,
  MIN(id) AS keep_id,
  ARRAY_AGG(id ORDER BY id) AS ids
FROM base_sys_user_role
WHERE deleted_at IS NULL
GROUP BY "userId", "roleId"
HAVING COUNT(*) > 1
ORDER BY cnt DESC, "userId", "roleId";

-- 2. 删除重复数据
DELETE FROM base_sys_user_role a
USING base_sys_user_role b
WHERE a."userId" = b."userId"
  AND a."roleId" = b."roleId"
  AND a.deleted_at IS NULL
  AND b.deleted_at IS NULL
  AND a.id > b.id;

-- 3. 执行后复查，应返回 0 行
SELECT
  "userId",
  "roleId",
  COUNT(*) AS cnt
FROM base_sys_user_role
WHERE deleted_at IS NULL
GROUP BY "userId", "roleId"
HAVING COUNT(*) > 1;

-- 4. 建议约束：只限制未软删除授权唯一，允许历史软删除授权保留
ALTER TABLE base_sys_user_role
DROP CONSTRAINT IF EXISTS uk_base_sys_user_role_user_role;

DROP INDEX IF EXISTS uk_base_sys_user_role_user_role;

CREATE UNIQUE INDEX IF NOT EXISTS uk_base_sys_user_role_user_role
ON base_sys_user_role ("userId", "roleId")
WHERE deleted_at IS NULL;
