db.py 9.71 KB
"""数据库(外部 MySQL,SQLAlchemy Core):共享 MetaData、引擎、常用查询帮助函数,以及表结构只读检查。

用法:
    from app.core import db
    db.rows(db.select(t).where(t.c.store_id == sid))
"""
from __future__ import annotations

import datetime as dt
import json
from contextlib import contextmanager
from typing import Any, Iterator

from sqlalchemy import (JSON, BigInteger, Boolean, Column, Date, DateTime, Float, Index, Integer,  # noqa: F401
                        MetaData, String, Table, Text, UniqueConstraint, and_, create_engine, delete, desc, func,
                        insert, or_, select, text, update)
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.engine import Connection, Engine

from .config import C, SERVER_ROOT  # noqa: F401

NAMING = {"ix": "ix_%(table_name)s_%(column_0_N_name)s", "uq": "uq_%(table_name)s_%(column_0_N_name)s",
          "pk": "pk_%(table_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"}
metadata = MetaData(naming_convention=NAMING)
LongText = Text().with_variant(MEDIUMTEXT(), "mysql")
VERSION_TABLE = "atrs_sys_schema_version"   # 旧版 Alembic 版本表(已不再使用;表结构比对时忽略)
_engine: Engine | None = None


def init_engine(url: str | None = None) -> Engine:
    global _engine
    _engine = create_engine(url or C.db_url(), pool_pre_ping=True, pool_recycle=1800, pool_size=10, max_overflow=20,
                            future=True)
    return _engine


def engine() -> Engine:
    if _engine is None:
        raise RuntimeError("数据库还没有初始化")
    return _engine


def now() -> dt.datetime:
    """写库时间戳与调度用同一个时钟(测试时可快进)。"""
    from . import clock
    return clock.now()


@contextmanager
def tx() -> Iterator[Connection]:
    with engine().begin() as c:
        yield c


def q(stmt):
    with engine().begin() as c:
        return c.execute(stmt)


def rows(stmt) -> list[dict]:
    with engine().begin() as c:
        return [dict(r._mapping) for r in c.execute(stmt)]


def one(stmt) -> dict | None:
    r = rows(stmt)
    return r[0] if r else None


def scalar(stmt) -> Any:
    with engine().begin() as c:
        return c.execute(stmt).scalar()


def paged(stmt, page: int = 1, size: int = 20, max_size: int = 200) -> dict:
    """列表分页:stmt 是带 where / order_by 的 select;返回 {rows, total, page, size}(rows 未 plain)。"""
    size = max(1, min(int(size or 20), max_size))
    page = max(1, int(page or 1))
    total = scalar(select(func.count()).select_from(stmt.order_by(None).subquery())) or 0
    return {"rows": rows(stmt.limit(size).offset((page - 1) * size)), "total": total, "page": page, "size": size}


def jdump(o: Any) -> str:
    return json.dumps(o, ensure_ascii=False, default=str)


def jload(s: Any, default: Any = None) -> Any:
    if s is None or s == "":
        return default
    if isinstance(s, (dict, list)):
        return s
    try:
        return json.loads(s)
    except (TypeError, ValueError):
        return default


def plain(row: dict | None) -> dict | None:
    """把一行里的 datetime / date 转成字符串,便于直接作为 JSON 返回。"""
    if row is None:
        return None
    return {k: (v.isoformat(sep=" ") if isinstance(v, dt.datetime) else v.isoformat() if isinstance(v, dt.date) else v)
            for k, v in row.items()}


# ---------------- 表结构检查(只读) ----------------
# 程序不再自行修改数据库(不建库、不建表 / 改表 / 删表、不跑数据迁移)。所有 DDL / DML 都写在仓库根目录
# sql_script/<版本>/ 下,由人工按顺序执行(规则见 agent.md、sql_script/README.md)。
# 启动时 verify_schema() 只读检查:表结构和 app.models 一致、库里的版本标记不低于 REQUIRED_SCHEMA,否则拒绝启动。
# 改了 app/models.py:用 `python -m app.cli schema-sql` 打印差异 DDL(只打印不执行),整理进新的 sql_script 版本目录。
TABLE_PREFIX = "atrs_"
SCHEMA_MARK = "db_schema"     # atrs_sys_config 里的一行:{"version": "x.y.z"},由各版本 sql_script 的 999 脚本写入
REQUIRED_SCHEMA = "3.2.0"     # 本程序要求的最低表结构版本(与 sql_script/v<版本> 目录对应)


class SchemaError(RuntimeError):
    """库的表结构 / 版本标记和程序不一致:需要先执行 sql_script 里的脚本。"""


def _log():
    import logging
    return logging.getLogger("server.db")


def _include_name(name, type_, parent_names) -> bool:
    if type_ == "table":
        return bool(name) and name.startswith(TABLE_PREFIX) and name != VERSION_TABLE
    return True


def _schema_ops(conn: Connection) -> list:
    """库里的表结构和 app.models 的差异(alembic 自动比对),返回一条条 DDL 操作。只读。"""
    from alembic.autogenerate import produce_migrations
    from alembic.migration import MigrationContext
    from alembic.operations.ops import ModifyTableOps

    from .. import models  # noqa: F401  注册全部表
    mc = MigrationContext.configure(conn, opts={"compare_type": True, "include_name": _include_name})
    out = []
    for o in produce_migrations(mc, metadata).upgrade_ops.ops:
        out.extend(o.ops if isinstance(o, ModifyTableOps) else [o])
    return out


def _is_drop(o) -> bool:
    from alembic.operations import ops
    return isinstance(o, (ops.DropTableOp, ops.DropColumnOp))


def describe_op(o) -> str:
    from alembic.operations import ops
    t = getattr(o, "table_name", "")
    if isinstance(o, ops.CreateTableOp):
        return f"建表 {t}"
    if isinstance(o, ops.DropTableOp):
        return f"删表 {t}"
    if isinstance(o, ops.AddColumnOp):
        return f"加字段 {t}.{o.column.name}"
    if isinstance(o, ops.DropColumnOp):
        return f"删字段 {t}.{o.column_name}"
    if isinstance(o, ops.AlterColumnOp):
        what = [n for n, changed in (("类型", o.modify_type is not None), ("可空", o.modify_nullable is not None),
                                     ("注释", o.modify_comment is not False),
                                     ("默认值", o.modify_server_default is not False)) if changed]
        return f"改字段 {t}.{o.column_name}({'、'.join(what) or '定义'})"
    if isinstance(o, ops.CreateIndexOp):
        return f"建索引 {t}.{o.index_name}"
    if isinstance(o, ops.DropIndexOp):
        return f"删索引 {t}.{o.index_name}"
    if isinstance(o, ops.AddConstraintOp):
        return f"建约束 {t}.{getattr(o, 'constraint_name', '')}"
    if isinstance(o, ops.DropConstraintOp):
        return f"删约束 {t}.{o.constraint_name}"
    if isinstance(o, (ops.CreateTableCommentOp, ops.DropTableCommentOp)):
        return f"改表注释 {t}"
    return f"{type(o).__name__} {t}"


def schema_diff() -> list[str]:
    """库里的表结构和代码还差哪些(只读)。"""
    with engine().connect() as c:
        return [describe_op(o) for o in _schema_ops(c)]


def schema_sql() -> str:
    """把库和代码的差异渲染成 MySQL DDL 文本(alembic 离线模式,只生成文字,不执行)。给开发人员整理 sql_script 用。"""
    import io

    from alembic.migration import MigrationContext
    from alembic.operations import Operations
    with engine().connect() as c:
        todo = _schema_ops(c)
    buf = io.StringIO()
    mc = MigrationContext.configure(dialect_name="mysql", opts={"as_sql": True, "output_buffer": buf})
    op = Operations(mc)
    for o in todo:
        buf.write(f"-- {describe_op(o)}\n")
        op.invoke(o)
    return buf.getvalue()


def _version_tuple(v: str) -> tuple:
    return tuple(int(x) if x.isdigit() else 0 for x in str(v or "0").split("."))


def schema_mark() -> str:
    """库里的表结构版本标记(atrs_sys_config.db_schema),没有返回空串。只读。"""
    with engine().connect() as c:
        if not c.execute(text("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() "
                              "AND table_name = 'atrs_sys_config'")).first():
            return ""
        v = c.execute(text("SELECT v FROM atrs_sys_config WHERE k = :k"), {"k": SCHEMA_MARK}).scalar()
    return str((jload(v, {}) or {}).get("version") or "")


def schema_problems() -> tuple[list[str], list[str]]:
    """(错误, 提醒)。错误 = 缺表 / 缺字段 / 字段定义不一致 / 版本标记偏低;提醒 = 库里多出来的字段 / 表(不影响使用)。只读。"""
    errors: list[str] = []
    mark = schema_mark()
    if _version_tuple(mark) < _version_tuple(REQUIRED_SCHEMA):
        errors.append(f"库里的表结构版本是 {mark or '(没有)'},程序要求 {REQUIRED_SCHEMA}:"
                      f"请 DBA 按顺序执行 sql_script/ 下 {mark or '全部'} 之后各版本目录里的脚本"
                      f"(到 v{REQUIRED_SCHEMA} 为止)")
    pending = schema_diff()
    drops = [p for p in pending if p.startswith(("删字段", "删表"))]
    if len(pending) > len(drops):
        errors.append("表结构和代码不一致:" + ";".join(p for p in pending if p not in drops) +
                      f"(请执行 sql_script/v{REQUIRED_SCHEMA}/ 下的脚本;开发人员可用 python -m app.cli schema-sql 查看差异 DDL)")
    warns = ["库里有代码已不再使用的字段 / 表(程序不会删除,需要的话由 DBA 写脚本处理):" + ";".join(drops)] if drops else []
    return errors, warns


def verify_schema() -> None:
    """启动检查(只读,不改库):不一致就抛 SchemaError 拒绝启动。"""
    errors, warns = schema_problems()
    for w in warns:
        _log().warning(w)
    if errors:
        for e in errors:
            _log().error(e)
        raise SchemaError("数据库表结构和程序版本不一致,已拒绝启动:" + ";".join(errors))