Files
syops/backend/scripts/grant_three_agents_permissions.sql
T

62 lines
2.4 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- =============================================================================
-- 批量补授 Agent 权限:通用入口 / RoHS文件检核 / MSDS文件检核
--
-- 【常见执行问题】
-- 1. 只运行了文件末尾的「验证 SELECT」→ 不会写入任何数据
-- 2. 用 Ctrl+Enter 只执行当前光标语句 → 需单独选中 INSERT 段执行
-- 3. BEGIN/COMMIT 在部分客户端未提交 → 已改为单条 INSERT,自动提交
--
-- 【正确做法】在 DBeaver / pgAdmin 中:
-- - 选中下方「★ 请只执行这一段 ★」到分号为止,单独执行
-- - 执行后应看到 inserted_rows 约等于 346×3 减去已有权限数
-- =============================================================================
-- -----------------------------------------------------------------------------(可选,预览,不写入)
-- SELECT id, name FROM agents
-- WHERE name IN ('通用入口', 'RoHS文件检核', 'MSDS文件检核');
-- SELECT a.name, COUNT(*) AS users_to_grant
-- FROM users u
-- CROSS JOIN agents a
-- WHERE a.name IN ('通用入口', 'RoHS文件检核', 'MSDS文件检核')
-- AND u.status = 'active'
-- AND NOT EXISTS (
-- SELECT 1 FROM user_agent_permissions uap
-- WHERE uap.user_id = u.id AND uap.agent_id = a.id
-- )
-- GROUP BY a.id, a.name;
-- ★ 请只执行这一段 ★
WITH missing AS (
SELECT u.id AS user_id, a.id AS agent_id, a.name AS agent_name
FROM users u
CROSS JOIN agents a
WHERE a.name IN ('通用入口', 'RoHS文件检核', 'MSDS文件检核')
AND u.status = 'active'
AND NOT EXISTS (
SELECT 1
FROM user_agent_permissions uap
WHERE uap.user_id = u.id
AND uap.agent_id = a.id
)
),
inserted AS (
INSERT INTO user_agent_permissions (user_id, agent_id)
SELECT user_id, agent_id FROM missing
RETURNING user_id, agent_id
)
SELECT
(SELECT COUNT(*) FROM inserted) AS inserted_rows,
(SELECT COUNT(*) FROM missing) AS expected_rows;
-- ★ 执行完成后,再跑验证 ★
SELECT a.name AS agent_name,
COUNT(DISTINCT uap.user_id) AS users_with_permission,
(SELECT COUNT(*) FROM users WHERE status = 'active') AS total_active_users
FROM agents a
LEFT JOIN user_agent_permissions uap ON uap.agent_id = a.id
WHERE a.name IN ('通用入口', 'RoHS文件检核', 'MSDS文件检核')
GROUP BY a.id, a.name
ORDER BY a.id;