docs(docs): document organizing
This commit is contained in:
1 parent
cc53d29e76
commit
c7f25ec8a1
20 files changed
+1523
-1021
No files matched your search
@@ -0,0 +1,184 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate SQL to batch-grant agent permissions for users who lack them.
|
||||
|
||||
Default agents (from admin UI):
|
||||
- 通用入口
|
||||
- RoHS文件检核
|
||||
- MSDS文件检核
|
||||
|
||||
Two output modes:
|
||||
1. subquery (default): INSERT ... SELECT with NOT EXISTS, no DB connection needed
|
||||
2. explicit: connect to DATABASE_URL and emit concrete (user_id, agent_id) rows
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_AGENT_NAMES = ("通用入口", "RoHS文件检核", "MSDS文件检核")
|
||||
|
||||
|
||||
def _quote_sql_string(value: str) -> str:
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
|
||||
|
||||
def build_subquery_sql(
|
||||
agent_names: list[str],
|
||||
user_status: str | None = "active",
|
||||
) -> str:
|
||||
lines = [
|
||||
"-- Auto-generated by generate_missing_agent_permissions_sql.py",
|
||||
"-- Skips users who already have the target agent permission.",
|
||||
"",
|
||||
"BEGIN;",
|
||||
"",
|
||||
]
|
||||
|
||||
for name in agent_names:
|
||||
quoted = _quote_sql_string(name)
|
||||
status_clause = f" AND u.status = {_quote_sql_string(user_status)}\n" if user_status else ""
|
||||
lines.extend(
|
||||
[
|
||||
f"-- Agent: {name}",
|
||||
"INSERT INTO user_agent_permissions (user_id, agent_id)",
|
||||
"SELECT u.id, a.id",
|
||||
"FROM users u",
|
||||
"CROSS JOIN agents a",
|
||||
f"WHERE a.name = {quoted}",
|
||||
status_clause.rstrip(),
|
||||
" AND NOT EXISTS (",
|
||||
" SELECT 1",
|
||||
" FROM user_agent_permissions uap",
|
||||
" WHERE uap.user_id = u.id",
|
||||
" AND uap.agent_id = a.id",
|
||||
" );",
|
||||
"",
|
||||
]
|
||||
)
|
||||
|
||||
lines.append("COMMIT;")
|
||||
lines.append("")
|
||||
return "\n".join(line for line in lines if line is not None)
|
||||
|
||||
|
||||
def build_explicit_sql(agent_names: list[str], user_status: str | None = "active") -> str:
|
||||
backend_dir = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(backend_dir))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
|
||||
env = os.getenv("FLASK_ENV", "production")
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.name.in_(agent_names))
|
||||
.order_by(Agent.id)
|
||||
.all()
|
||||
)
|
||||
found_names = {a.name for a in agents}
|
||||
missing_names = [n for n in agent_names if n not in found_names]
|
||||
if missing_names:
|
||||
raise SystemExit(f"Agents not found in database: {missing_names}")
|
||||
|
||||
user_query = db.session.query(User)
|
||||
if user_status:
|
||||
user_query = user_query.filter(User.status == user_status)
|
||||
users = user_query.order_by(User.id).all()
|
||||
|
||||
existing = {
|
||||
(row.user_id, row.agent_id)
|
||||
for row in db.session.execute(
|
||||
db.text("SELECT user_id, agent_id FROM user_agent_permissions")
|
||||
)
|
||||
}
|
||||
|
||||
values: list[str] = []
|
||||
for user in users:
|
||||
for agent in agents:
|
||||
pair = (user.id, agent.id)
|
||||
if pair not in existing:
|
||||
values.append(f"({user.id}, {agent.id})")
|
||||
|
||||
if not values:
|
||||
return (
|
||||
"-- No missing permissions found.\n"
|
||||
"-- All target users already have the requested agent permissions.\n"
|
||||
)
|
||||
|
||||
agent_summary = ", ".join(f"{a.name}(id={a.id})" for a in agents)
|
||||
lines = [
|
||||
"-- Auto-generated explicit INSERT rows from live database",
|
||||
f"-- Agents: {agent_summary}",
|
||||
f"-- Rows to insert: {len(values)}",
|
||||
"",
|
||||
"BEGIN;",
|
||||
"",
|
||||
"INSERT INTO user_agent_permissions (user_id, agent_id)",
|
||||
"VALUES",
|
||||
" " + ",\n ".join(values),
|
||||
"ON CONFLICT DO NOTHING;",
|
||||
"",
|
||||
"COMMIT;",
|
||||
"",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate SQL to grant missing user_agent_permissions."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--agent-names",
|
||||
default=",".join(DEFAULT_AGENT_NAMES),
|
||||
help="Comma-separated agent names (default: three agents from admin UI).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-status",
|
||||
default="active",
|
||||
help="Only include users with this status (default: active). Use empty string for all users.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--mode",
|
||||
choices=("subquery", "explicit"),
|
||||
default="subquery",
|
||||
help="subquery: name-based INSERT SELECT (no DB). explicit: query DB for concrete rows.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default="backend/scripts/grant_three_agents_permissions.generated.sql",
|
||||
help="Output SQL file path.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
agent_names = [part.strip() for part in args.agent_names.split(",") if part.strip()]
|
||||
if not agent_names:
|
||||
raise SystemExit("agent-names cannot be empty")
|
||||
|
||||
user_status = args.user_status.strip() or None
|
||||
|
||||
if args.mode == "explicit":
|
||||
sql = build_explicit_sql(agent_names, user_status=user_status)
|
||||
else:
|
||||
sql = build_subquery_sql(agent_names, user_status=user_status)
|
||||
|
||||
output_path = Path(args.output)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(sql, encoding="utf-8")
|
||||
|
||||
print(f"Generated SQL: {output_path}")
|
||||
print(f"Mode: {args.mode}")
|
||||
print(f"Agents: {agent_names}")
|
||||
print(f"User status filter: {user_status or '(all)'}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user