637 lines
28 KiB
Python
637 lines
28 KiB
Python
"""SQLAlchemy engine / session plumbing."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from collections.abc import Iterator
|
||
from contextlib import contextmanager
|
||
|
||
import logging
|
||
|
||
import re
|
||
|
||
from sqlalchemy import JSON, LargeBinary, Text, create_engine, text
|
||
from sqlalchemy.engine import Engine
|
||
from sqlalchemy.orm import Session, declarative_base, sessionmaker
|
||
|
||
from .config import settings
|
||
|
||
logger = logging.getLogger("unisoa.db")
|
||
|
||
engine: Engine = create_engine(
|
||
settings.database_url,
|
||
pool_pre_ping=True,
|
||
pool_recycle=1800,
|
||
pool_size=10,
|
||
max_overflow=20,
|
||
future=True,
|
||
)
|
||
|
||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
||
|
||
Base = declarative_base()
|
||
|
||
|
||
@contextmanager
|
||
def advisory_lock(name: str, *, timeout_seconds: float = 60.0):
|
||
"""跨进程串行化一段代码的命名锁(MySQL ``GET_LOCK``),拿到返回 True。
|
||
|
||
为什么建表与初始化不能用 :meth:`app.service.leader.acquire`:那把租约存在
|
||
``oa_worker_lease`` 里,而**建表之前那张表还不存在**——先有鸡还是先有蛋。
|
||
``GET_LOCK`` 是服务端命名的会话锁,不依赖任何表,正是为这种场景准备的。
|
||
|
||
锁跟着连接走,所以这里单独占一条连接,用完显式释放并关掉(连接断了 MySQL 也会
|
||
自动释放,进程被 ``kill -9`` 不会留下解不开的锁)。数据库不支持命名锁时(非 MySQL)
|
||
直接当作"拿到锁",退化成单进程时代的照常跑。
|
||
"""
|
||
try:
|
||
with engine.connect() as conn:
|
||
got = conn.execute(text("SELECT GET_LOCK(:name, :timeout)"),
|
||
{"name": name, "timeout": int(max(0, timeout_seconds))}).scalar()
|
||
try:
|
||
yield bool(got)
|
||
finally:
|
||
if got:
|
||
conn.execute(text("SELECT RELEASE_LOCK(:name)"), {"name": name})
|
||
conn.commit()
|
||
except Exception: # pragma: no cover - 非 MySQL 或没有命名锁权限时不拦启动
|
||
logger.warning("advisory lock %s 不可用,本进程直接继续(多副本部署时请确认数据库支持 GET_LOCK)", name,
|
||
exc_info=True)
|
||
yield True
|
||
|
||
|
||
def get_db() -> Iterator[Session]:
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
def ensure_database() -> None:
|
||
"""库不存在时建库;库名不在白名单里就当场停下,不许悄悄长出一个新库。
|
||
|
||
为什么加这一道闸(2026-10):引导配置默认拿 root 连库、``auto_create_schema`` 又开着,
|
||
于是 ``OA_DB_NAME`` 打错一个字、或者某次验收临时库名懒得想,MySQL 上就多出一个
|
||
全套表 + 演示数据的库;脚本被打断或 ``--only`` 少跑一步就不删它。开发机上一次攒出
|
||
六个来路说不清的库(dictkeep / uidemo / ui / prodtest / hubtest9 / runall),
|
||
而这台 MySQL 上还跑着别人的库。
|
||
|
||
只管"要新建"这一种情况:库已经存在就直接返回,连的是既有库、不建库,
|
||
老部署和「指到已同步过组织的库」那类验收都不受影响。白名单见
|
||
``config.DEFAULT_DB_CREATE_ALLOWLIST``,填 ``*`` 等于关掉这道闸。
|
||
"""
|
||
name = str(settings.db_name or "").strip()
|
||
if database_exists(name):
|
||
return
|
||
|
||
patterns = create_allowlist()
|
||
if not _SCHEMA_IDENT.fullmatch(name):
|
||
raise SchemaCreationRefused(
|
||
f"库名 {name!r} 不合法(只允许字母、数字、下划线、$ 和 -,长度 1-64),后端不建库。"
|
||
)
|
||
if not schema_name_allowed(name, patterns):
|
||
raise SchemaCreationRefused(
|
||
f"库 {name} 在 {settings.db_host}:{settings.db_port} 上不存在,"
|
||
f"而它不在建库白名单里,后端拒绝自己新建一个库。\n"
|
||
f" 白名单:[database] create_allowlist / 环境变量 OA_DB_CREATE_ALLOWLIST,"
|
||
f"现在是 {'、'.join(patterns) or '(空 = 一个都不许建)'}\n"
|
||
" 三选一:① 库名写错了 → 把 OA_DB_NAME 或 [database] name 改回真正的库;"
|
||
"② 确实要新建这个库 → 把它(或 unis_oa_xxx* 这样的前缀)加进白名单;"
|
||
"③ 生产库归 DBA 管 → 先照 sql/schema.sql 手工建库建表,再把 auto_create_schema 关掉。"
|
||
)
|
||
|
||
conn = _server_connection()
|
||
try:
|
||
with conn.cursor() as cursor:
|
||
cursor.execute(
|
||
f"CREATE DATABASE IF NOT EXISTS `{name}` "
|
||
"DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||
)
|
||
conn.commit()
|
||
logger.warning(
|
||
"schema: 库 %s 原本不存在,已按白名单新建(白名单:%s);用完记得删",
|
||
name,
|
||
"、".join(patterns),
|
||
)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
class SchemaCreationRefused(RuntimeError):
|
||
"""目标库不存在,而库名不在建库白名单里:八成是 ``OA_DB_NAME`` 打错了。"""
|
||
|
||
|
||
#: 白名单里单独一个 ``*`` = 不设限(给"我确实要随便建库"的部署留的口子)
|
||
ALLOW_EVERYTHING = "*"
|
||
#: 能拼进反引号的库名字符。名字要拼进 SQL,所以先卡死再拼
|
||
_SCHEMA_IDENT = re.compile(r"[A-Za-z0-9_$-]{1,64}")
|
||
|
||
|
||
def create_allowlist(value: object = None) -> tuple[str, ...]:
|
||
"""把 ``[database] create_allowlist`` 拆成模式清单。
|
||
|
||
逗号分隔(中文逗号也认),TOML 数组写法也认;小写比较,MySQL 的库名在
|
||
这台服务器的 ``utf8mb4_unicode_ci`` 下不分大小写。
|
||
"""
|
||
raw = settings.db_create_allowlist if value is None else value
|
||
if isinstance(raw, (list, tuple)):
|
||
parts = [str(part) for part in raw]
|
||
else:
|
||
parts = re.split(r"[,,\s]+", str(raw or ""))
|
||
return tuple(part.strip().lower() for part in parts if part.strip())
|
||
|
||
|
||
def schema_name_allowed(name: str, patterns: tuple[str, ...] | None = None) -> bool:
|
||
"""这个库名许不许新建:命中精确名,或命中 ``前缀*`` 这种通配。"""
|
||
target = str(name or "").strip().lower()
|
||
if not target:
|
||
return False
|
||
for pattern in create_allowlist() if patterns is None else patterns:
|
||
if pattern == ALLOW_EVERYTHING:
|
||
return True
|
||
if pattern.endswith("*"):
|
||
if target.startswith(pattern[:-1]):
|
||
return True
|
||
elif target == pattern:
|
||
return True
|
||
return False
|
||
|
||
|
||
def stray_schemas(names: object, current: str, patterns: tuple[str, ...] | None = None) -> tuple[str, ...]:
|
||
"""从一堆库名里挑出"看着也是本系统的库",排除当前库与白名单里点名的库。
|
||
|
||
一个环境一个库是规矩,但库名长得像本系统的库最容易是**某次验收被打断留下的残留**
|
||
(历史上攒出过六个)。启动时把它们报出来,比半年后有人在 `SHOW DATABASES` 里
|
||
对着六个名字回忆哪个是哪个便宜。白名单里的名字不算残留——那是配置里明说要用的。
|
||
"""
|
||
cur = str(current or "").strip().lower()
|
||
allowed = create_allowlist() if patterns is None else patterns
|
||
out = []
|
||
for raw in list(names or []):
|
||
name = str(raw or "").strip().lower()
|
||
if not name or name == cur:
|
||
continue
|
||
if not (name == "unis_oa" or name.startswith("unis_oa_") or name.startswith("unisoa_")):
|
||
continue
|
||
if schema_name_allowed(name, allowed):
|
||
continue
|
||
out.append(name)
|
||
return tuple(sorted(out))
|
||
|
||
|
||
def list_stray_schemas() -> tuple[str, ...]:
|
||
"""查这台 MySQL 上还有没有别的"像本系统的库"。账号没权限查就安静返回空。"""
|
||
try:
|
||
conn = _server_connection()
|
||
except Exception: # pragma: no cover - 连不上 MySQL 时后面自有更响的报错
|
||
return ()
|
||
try:
|
||
with conn.cursor() as cursor:
|
||
cursor.execute("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA")
|
||
return stray_schemas([row[0] for row in cursor.fetchall()], settings.db_name)
|
||
except Exception: # pragma: no cover - 没有 information_schema 权限时不拦启动
|
||
logger.debug("查有哪些库失败(没有 information_schema 权限?),跳过残留库检查", exc_info=True)
|
||
return ()
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def _server_connection():
|
||
"""不带库名连 MySQL:判断库在不在、建库,都得这么连。"""
|
||
import pymysql # noqa: PLC0415 (only needed for the bootstrap connection)
|
||
|
||
return pymysql.connect(
|
||
host=settings.db_host,
|
||
port=settings.db_port,
|
||
user=settings.db_user,
|
||
password=settings.db_password,
|
||
charset="utf8mb4",
|
||
connect_timeout=8,
|
||
)
|
||
|
||
|
||
def database_exists(name: str) -> bool:
|
||
"""这台 MySQL 上有没有这个库(不要求程序当前能连上那个库)。"""
|
||
conn = _server_connection()
|
||
try:
|
||
with conn.cursor() as cursor:
|
||
cursor.execute(
|
||
"SELECT 1 FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = %s LIMIT 1",
|
||
(name,),
|
||
)
|
||
return cursor.fetchone() is not None
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def create_schema() -> list[str]:
|
||
"""建表 + 补列 + 补索引 + 收尾,一趟跑完;返回"没做成"的清单,空列表代表结构可信。
|
||
|
||
每一步单独兜一层:以前是一路直着跑到底,任何一步炸(最常见是老库上一句 ALTER 撞车、
|
||
或者某张表上有长事务压着元数据锁)后面的补列补索引就全都不做了,而 ``app.main`` 把整个
|
||
引导包在一个 try 里,日志只剩一句 ``database bootstrap failed``,服务照旧对外接客——
|
||
于是库里缺的那列没人补,模型带着它去 INSERT,第一次登录就报
|
||
``Unknown column 'last_used_at' in 'field list'``(2026-10 那次)。坏一步不挡后面的路,
|
||
失败攒起来交给调用方喊人。
|
||
"""
|
||
from . import models # noqa: F401 (register mappers)
|
||
|
||
problems: list[str] = []
|
||
|
||
def _step(label: str, action) -> None:
|
||
try:
|
||
action()
|
||
except Exception as exc: # noqa: BLE001 - 一步坏不挡整趟,但必须留下名字和原因
|
||
logger.exception("schema: %s 失败", label)
|
||
problems.append(f"{label}失败:{exc.__class__.__name__}: {exc}")
|
||
|
||
_step("建表", lambda: Base.metadata.create_all(bind=engine))
|
||
_step("补列", ensure_columns)
|
||
_step("补索引", ensure_indexes)
|
||
_step("补列注释", sync_column_comments)
|
||
_step("搬移被取代的老列", drop_replaced_columns)
|
||
_step("清理退役表列", drop_retired_storage_schema)
|
||
return problems
|
||
|
||
|
||
def ensure_columns() -> list[str]:
|
||
"""Add columns that were introduced after a table already existed.
|
||
|
||
``create_all`` is a no-op for existing tables, so a model change such as a new
|
||
``oa_file.source`` column would otherwise blow up on the next INSERT. Only
|
||
missing columns are touched, and the whole pass is safe to run on every boot.
|
||
"""
|
||
from sqlalchemy import inspect
|
||
|
||
from . import models # noqa: F401 (register mappers)
|
||
|
||
inspector = inspect(engine)
|
||
existing_tables = set(inspector.get_table_names())
|
||
added: list[str] = []
|
||
with engine.begin() as conn:
|
||
for table in Base.metadata.sorted_tables:
|
||
if table.name not in existing_tables:
|
||
continue
|
||
present = {column["name"] for column in inspector.get_columns(table.name)}
|
||
for column in table.columns:
|
||
if column.name in present:
|
||
continue
|
||
sql_type = column.type.compile(engine.dialect)
|
||
comment = f" COMMENT '{_comment_literal(column)}'" if column.comment else ""
|
||
if column.nullable:
|
||
# 可空列一律加 NULL。``_default_literal`` 会把 BIGINT 的 None 兜成
|
||
# 0,而 ``users.hub_user_id`` 这类"还没同步过"的列写 0 会被读成一条
|
||
# 真实的外来主键。
|
||
clause = f"ADD COLUMN `{column.name}` {sql_type} NULL{comment}"
|
||
conn.execute(text(f"ALTER TABLE `{table.name}` {clause}"))
|
||
elif _supports_default(column):
|
||
literal = _default_literal(column)
|
||
clause = f"ADD COLUMN `{column.name}` {sql_type} NOT NULL DEFAULT {literal}{comment}" if literal else \
|
||
f"ADD COLUMN `{column.name}` {sql_type} NULL{comment}"
|
||
conn.execute(text(f"ALTER TABLE `{table.name}` {clause}"))
|
||
else:
|
||
# MySQL 8 不给 JSON / TEXT / BLOB 写 DEFAULT 子句
|
||
# (`BLOB, TEXT, GEOMETRY or JSON column ... can't have a default value`),
|
||
# 所以这三类 NOT NULL 列走"先可空 -> 回填 -> 再收紧"三步,
|
||
# 老行了有值,模型里的 NOT NULL 也守得住。
|
||
conn.execute(text(f"ALTER TABLE `{table.name}` ADD COLUMN `{column.name}` {sql_type} NULL"))
|
||
backfill = _backfill_literal(column)
|
||
if backfill:
|
||
conn.execute(text(f"UPDATE `{table.name}` SET `{column.name}` = {backfill} WHERE `{column.name}` IS NULL"))
|
||
conn.execute(text(f"ALTER TABLE `{table.name}` MODIFY COLUMN `{column.name}` {sql_type} NOT NULL{comment}"))
|
||
added.append(f"{table.name}.{column.name}")
|
||
logger.info("schema: 新增列 %s.%s", table.name, column.name)
|
||
return added
|
||
|
||
|
||
def drop_replaced_columns() -> list[str]:
|
||
"""搬完数据后删掉被新列取代的老列。
|
||
|
||
``ensure_columns`` 只会加列,不会收尾:``oa_unit.enabled`` 换成 ``oa_unit.status``
|
||
之后,老库会长期留着两列表示同一件事,谁都说不清以哪个为准。所以先把老值搬进
|
||
新列,再在同一次启动里把老列删掉。规则都写在这里,一次只处理一列,删之前必须
|
||
确认新列已经在库里。
|
||
"""
|
||
from sqlalchemy import inspect
|
||
|
||
replacements = (
|
||
# (表, 新列, 老列, 搬运语句)
|
||
# 新列带默认值落库时所有行都是 1,所以两个方向都要写一遍,否则停用的部门会被洗成启用。
|
||
("oa_unit", "status", "enabled", "UPDATE `oa_unit` SET `status` = CASE WHEN `enabled` <> 0 THEN 1 ELSE 0 END"),
|
||
)
|
||
inspector = inspect(engine)
|
||
existing_tables = set(inspector.get_table_names())
|
||
dropped: list[str] = []
|
||
with engine.begin() as conn:
|
||
for table, new_column, old_column, backfill in replacements:
|
||
if table not in existing_tables:
|
||
continue
|
||
present = {column["name"] for column in inspector.get_columns(table)}
|
||
if new_column not in present or old_column not in present:
|
||
continue
|
||
conn.execute(text(backfill))
|
||
conn.execute(text(f"ALTER TABLE `{table}` DROP COLUMN `{old_column}`"))
|
||
dropped.append(f"{table}.{old_column}")
|
||
logger.info("schema: %s.%s 已搬进 %s,老列已删除", table, old_column, new_column)
|
||
return dropped
|
||
|
||
|
||
# 老库里已经存在、但建表时没带上注释的列:注释写在这里,启动时补一次。
|
||
# 口径以 models.py 为准,补完之后 sql/schema.sql 才是可信的。
|
||
COLUMN_COMMENTS = (
|
||
# (表, 列, 完整列定义)
|
||
(
|
||
"oa_unit",
|
||
"status",
|
||
"MODIFY COLUMN `status` TINYINT UNSIGNED NOT NULL DEFAULT 1 "
|
||
"COMMENT '1=active, 0=disabled, 2=pending, 3=rejected'",
|
||
),
|
||
)
|
||
|
||
|
||
def sync_column_comments() -> list[str]:
|
||
"""给缺注释的已有列补上模型里声明的注释。
|
||
|
||
``ensure_columns`` 之前只会 ``ADD COLUMN``,把 ``status`` 上的取值说明丢了,
|
||
于是老库的 ``SHOW CREATE TABLE`` 和模型对不上,看结构的人只能靠猜。这里只改注释、
|
||
不动类型与默认值,缺列缺表都跳过,每次启动都安全。
|
||
"""
|
||
from sqlalchemy import inspect
|
||
|
||
inspector = inspect(engine)
|
||
existing_tables = set(inspector.get_table_names())
|
||
fixed: list[str] = []
|
||
with engine.begin() as conn:
|
||
for table, column, definition in COLUMN_COMMENTS:
|
||
if table not in existing_tables:
|
||
continue
|
||
info = {item["name"]: item for item in inspector.get_columns(table)}
|
||
if column not in info or (info[column].get("comment") or ""):
|
||
continue
|
||
conn.execute(text(f"ALTER TABLE `{table}` {definition}"))
|
||
fixed.append(f"{table}.{column}")
|
||
logger.info("schema: 补列注释 %s.%s", table, column)
|
||
return fixed
|
||
|
||
|
||
# NAS 网盘下线后不再被任何代码读写的表与列,老库启动时按名字清一遍。
|
||
RETIRED_TABLES = ("oa_drive_mount", "oa_drive_grant")
|
||
RETIRED_COLUMNS = (
|
||
("oa_file", "source"),
|
||
("oa_file", "mount"),
|
||
("oa_file", "nas_path"),
|
||
)
|
||
|
||
|
||
#: 唯一身份列撞车时的保优规则:``(表, 列, 保留哪一行的排序 SQL)``。
|
||
#: 老版本的同步会把同一个 Hub 主键盖到两行上(人员按账号认领过、部门删掉又重同步出来),
|
||
#: 带着重复值唯一索引建不起来,而索引建不起来 = 这一列当身份就不可信,所以升级前先把
|
||
#: 多出来的行**解绑**(置 NULL,行本身不动):多出来的那个人变成普通本地账号,
|
||
#: 多出来的那个部门变成本地自建部门,都不删数据。
|
||
UNIQUE_KEY_DEDUPE = (
|
||
(
|
||
"users",
|
||
"hub_user_id",
|
||
"ORDER BY (source = 'hub') DESC, hub_synced_at DESC, id DESC",
|
||
),
|
||
(
|
||
"oa_unit",
|
||
"hub_org_id",
|
||
# 人多的那个更可能是真的那一支,平手留后建的。
|
||
"ORDER BY (SELECT COUNT(*) FROM users u WHERE u.organization_id = oa_unit.id) DESC, id DESC",
|
||
),
|
||
)
|
||
|
||
#: 历史上按普通索引建的 Hub 主键列,唯一索引补好之后就把这些旧名字删掉:
|
||
#: 同一列上挂两个索引只会让写入多付一次维护成本。
|
||
#: 两个部门索引名都要列:``index=True`` 自动生成的叫 ``ix_...``,早先手写的是 ``idx_...``。
|
||
RETIRED_INDEXES = (
|
||
("users", "idx_users_hub_user_id"),
|
||
("oa_unit", "ix_oa_unit_hub_org_id"),
|
||
("oa_unit", "idx_oa_unit_hub_org_id"),
|
||
)
|
||
|
||
|
||
def _dedupe_unique_keys(conn, inspector, table_name: str) -> list[str]:
|
||
"""把 ``hub_user_id`` / ``hub_org_id`` 上的重复值解开,让唯一索引建得起来。"""
|
||
fixed: list[str] = []
|
||
for table, column, keep_order in UNIQUE_KEY_DEDUPE:
|
||
if table != table_name or table not in inspector.get_table_names():
|
||
continue
|
||
columns = {item["name"] for item in inspector.get_columns(table)}
|
||
if column not in columns:
|
||
continue
|
||
dupes = conn.execute(
|
||
text(
|
||
f"SELECT `{column}` AS k FROM `{table}` WHERE `{column}` IS NOT NULL "
|
||
f"GROUP BY `{column}` HAVING COUNT(*) > 1"
|
||
)
|
||
).fetchall()
|
||
for row in dupes:
|
||
key = row[0]
|
||
ids = [
|
||
item[0]
|
||
for item in conn.execute(
|
||
text(f"SELECT id FROM `{table}` WHERE `{column}` = :k {keep_order}"),
|
||
{"k": key},
|
||
).fetchall()
|
||
]
|
||
if len(ids) < 2:
|
||
continue
|
||
losers = ids[1:]
|
||
conn.execute(
|
||
text(f"UPDATE `{table}` SET `{column}` = NULL WHERE id IN ({','.join(str(i) for i in losers)})")
|
||
)
|
||
if table == "users":
|
||
# 解下 Hub 身份的人退回本地账号:他不再由同步维护,
|
||
# 也就不会被"Hub 里查不到"这条规则误停用。
|
||
conn.execute(
|
||
text(f"UPDATE `users` SET source = 'local' WHERE id IN ({','.join(str(i) for i in losers)})")
|
||
)
|
||
fixed.append(f"{table}.{column}={key} 解绑 {len(losers)} 行(保留 id={ids[0]})")
|
||
logger.warning(
|
||
"schema: %s.%s=%s 上有 %s 行撞同一个 Hub 主键,已解绑 %s 行(保留 id=%s)",
|
||
table,
|
||
column,
|
||
key,
|
||
len(ids),
|
||
len(losers),
|
||
ids[0],
|
||
)
|
||
return fixed
|
||
|
||
|
||
def ensure_indexes() -> list[str]:
|
||
"""补上老表上缺失的索引,顺手把老库里撞车的 Hub 主键解开。
|
||
|
||
``create_all`` 只在建表那一刻建索引,所以「先有表、后加 ``index=True`` 的列」这种
|
||
改动会永远缺一个索引:``users.hub_user_id`` 就是典型,Hub 每次登录都要按它查一次人
|
||
(``api/auth.py``),没索引就是每次登录一趟全表扫。这里按模型声明补建,跑多少次都
|
||
一样,只认索引名在不在。
|
||
|
||
唯一索引(``uq_users_hub_user_id`` / ``uq_oa_unit_hub_org_id``)在老库上可能因为
|
||
历史重复值建不起来:先自动解绑重复行再试一次,还是不行就只记日志、不阻断启动
|
||
——缺一个索引比起不来好,日志会把话说清楚。
|
||
"""
|
||
from sqlalchemy import inspect
|
||
from sqlalchemy.schema import CreateIndex
|
||
|
||
from . import models # noqa: F401 (register mappers)
|
||
|
||
inspector = inspect(engine)
|
||
existing_tables = set(inspector.get_table_names())
|
||
created: list[str] = []
|
||
with engine.begin() as conn:
|
||
for table in Base.metadata.sorted_tables:
|
||
if table.name not in existing_tables:
|
||
continue
|
||
columns = {column["name"] for column in inspector.get_columns(table.name)}
|
||
present = {index["name"] for index in inspector.get_indexes(table.name)}
|
||
if any(index.unique and index.name not in present for index in table.indexes):
|
||
for item in _dedupe_unique_keys(conn, inspector, table.name):
|
||
created.append(item)
|
||
for index in table.indexes:
|
||
names = [column.name for column in index.columns]
|
||
if index.name in present or not set(names) <= columns:
|
||
continue
|
||
try:
|
||
conn.execute(CreateIndex(index))
|
||
except Exception as exc: # noqa: BLE001 - 老库脏数据不该把服务带崩
|
||
if not index.unique:
|
||
raise
|
||
logger.warning(
|
||
"schema: 唯一索引 %s.%s 建失败(%s)。这一列上的 Hub 主键暂时不保证唯一,"
|
||
"组织人员同步仍会按主键认人,但请手工清理重复值后重启补齐。",
|
||
table.name,
|
||
index.name,
|
||
exc.__class__.__name__,
|
||
)
|
||
created.append(f"{table.name}.{index.name} 失败")
|
||
continue
|
||
created.append(f"{table.name}.{index.name}")
|
||
logger.info(
|
||
"schema: 新增%s索引 %s.%s(%s)",
|
||
"唯一" if index.unique else "",
|
||
table.name,
|
||
index.name,
|
||
",".join(names),
|
||
)
|
||
# 唯一索引就位之后,把被它取代的普通索引删掉。
|
||
for table_name, index_name in RETIRED_INDEXES:
|
||
if table_name not in existing_tables:
|
||
continue
|
||
present = {index["name"] for index in inspector.get_indexes(table_name)}
|
||
if index_name not in present:
|
||
continue
|
||
conn.execute(text(f"DROP INDEX `{index_name}` ON `{table_name}`"))
|
||
created.append(f"{table_name}.{index_name} 已删除")
|
||
logger.info("schema: 退役索引已删除 %s.%s", table_name, index_name)
|
||
return created
|
||
|
||
|
||
#: 运行配置改存数据库之后,早期那几行 ``hub`` / ``site`` / ``runtime`` 由
|
||
#: ``dbconfig.migrate_legacy()`` 负责并进 ``config:*`` 行,这里不再随手删库里的配置。
|
||
|
||
|
||
def drop_retired_storage_schema() -> list[str]:
|
||
"""删掉 NAS 网盘退役后遗留的表与列。
|
||
|
||
``create_all`` 只建不删,老库会一直留着这些没人读的东西。表里如果还有 NAS 记录,
|
||
文件也已经不在网盘页的可见范围内了,所以这里直接清掉;缺表缺列都跳过,每次启动都安全。
|
||
"""
|
||
from sqlalchemy import inspect
|
||
|
||
inspector = inspect(engine)
|
||
existing_tables = set(inspector.get_table_names())
|
||
dropped: list[str] = []
|
||
with engine.begin() as conn:
|
||
for table in RETIRED_TABLES:
|
||
if table not in existing_tables:
|
||
continue
|
||
conn.execute(text(f"DROP TABLE IF EXISTS `{table}`"))
|
||
dropped.append(table)
|
||
logger.info("schema: 退役表已删除 %s", table)
|
||
for table, column in RETIRED_COLUMNS:
|
||
if table not in existing_tables:
|
||
continue
|
||
present = {item["name"] for item in inspector.get_columns(table)}
|
||
if column not in present:
|
||
continue
|
||
conn.execute(text(f"ALTER TABLE `{table}` DROP COLUMN `{column}`"))
|
||
dropped.append(f"{table}.{column}")
|
||
logger.info("schema: 退役列已删除 %s.%s", table, column)
|
||
return dropped
|
||
|
||
|
||
def _comment_literal(column) -> str:
|
||
"""Escape a column comment for inline DDL."""
|
||
return (column.comment or "").replace("\\", "").replace("'", "''")
|
||
|
||
|
||
def _default_literal(column) -> str:
|
||
"""Backfill literal for an added NOT NULL column, taken from the model default."""
|
||
from sqlalchemy import BigInteger, Boolean, DateTime, Float, Integer
|
||
|
||
default = column.default
|
||
value = None
|
||
if default is not None and getattr(default, "is_scalar", False):
|
||
value = default.arg
|
||
# ``users`` uses dialect variants (BIGINT UNSIGNED / DATETIME(3)), which wrap
|
||
# the generic type and would otherwise fall through to the string branch.
|
||
column_type = getattr(column.type, "impl", column.type)
|
||
if isinstance(column.type, BigInteger) or isinstance(column_type, BigInteger):
|
||
return str(int(value)) if isinstance(value, (int, float)) else "0"
|
||
if isinstance(column.type, Boolean):
|
||
if value is None:
|
||
return "0"
|
||
return "1" if value else "0"
|
||
if isinstance(column.type, Integer) or isinstance(column_type, Integer):
|
||
return str(int(value)) if isinstance(value, (int, float)) else "0"
|
||
if isinstance(column.type, Float) or isinstance(column_type, Float):
|
||
return str(float(value)) if isinstance(value, (int, float)) else "0"
|
||
if isinstance(column.type, DateTime) or isinstance(column_type, DateTime):
|
||
return "" if value is None else "CURRENT_TIMESTAMP"
|
||
if value is None:
|
||
return "''"
|
||
return "'" + str(value).replace("'", "''") + "'"
|
||
|
||
|
||
#: MySQL 不允许写 DEFAULT 子句的列类型:JSON、TEXT/BLOB 家族、二进制。
|
||
_NO_DEFAULT_TYPES = (JSON, Text, LargeBinary)
|
||
|
||
|
||
def _supports_default(column) -> bool:
|
||
"""这一列能不能在 ADD COLUMN 里直接写 DEFAULT。"""
|
||
column_type = getattr(column.type, "impl", column.type)
|
||
return not isinstance(column.type, _NO_DEFAULT_TYPES) and not isinstance(column_type, _NO_DEFAULT_TYPES)
|
||
|
||
|
||
def _backfill_literal(column) -> str:
|
||
"""不能写 DEFAULT 的列,用模型默认值回填存量行。"""
|
||
default = column.default
|
||
value = default.arg if default is not None and getattr(default, "is_scalar", False) else None
|
||
if isinstance(column.type, JSON) or isinstance(getattr(column.type, "impl", column.type), JSON):
|
||
# ``default=list`` 在 SQLAlchemy 里是 callable 默认值,``is_scalar`` 为 False、
|
||
# ``value`` 取不到东西,老写法靠函数名猜形状,结果新加的 JsonList 列全被回填成
|
||
# ``{}``(oa_auth_role.data_unit_ids 第一趟就是这么脏的)。直接认这两个内置函数。
|
||
arg = default.arg if default is not None else None
|
||
if isinstance(value, list) or arg is list:
|
||
return "'[]'"
|
||
return "'{}'"
|
||
if isinstance(column.type, LargeBinary) or isinstance(getattr(column.type, "impl", column.type), LargeBinary):
|
||
return "''"
|
||
return "''"
|
||
|
||
|
||
def drop_schema() -> None:
|
||
Base.metadata.drop_all(bind=engine)
|
||
|
||
|
||
def ping() -> bool:
|
||
try:
|
||
with engine.connect() as conn:
|
||
conn.execute(text("SELECT 1"))
|
||
return True
|
||
except Exception:
|
||
return False
|