"""数据库会话与建库建表。 生产上 ``database.auto_create_schema=false`` 时这里什么都不做,建表交 DBA 跑 ``sql/schema.sql``;开发/测试档默认打开,改了模型重启就生效,省去手工同步。 """ from __future__ import annotations import logging from collections.abc import Iterator from contextlib import contextmanager import pymysql from sqlalchemy import create_engine, inspect, text from sqlalchemy.engine import Engine from sqlalchemy.orm import Session, sessionmaker from .config import settings from .models import Base logger = logging.getLogger("pms.db") engine: Engine | None = None SessionLocal: sessionmaker[Session] | None = None #: 老系统留下的连接保活:容器里空闲连接常被中间设备掐断 POOL_PARAMETERS = {"pool_pre_ping": True, "pool_recycle": 1800} def get_engine() -> Engine: global engine if engine is None: engine = create_engine( settings.database.url, echo=settings.database.echo_sql, pool_size=settings.database.pool_size, max_overflow=settings.database.max_overflow, **POOL_PARAMETERS, ) return engine def get_session() -> Iterator[Session]: """FastAPI 依赖用。""" session = SessionFactory()() try: yield session finally: session.close() def SessionFactory() -> sessionmaker[Session]: global SessionLocal if SessionLocal is None: SessionLocal = sessionmaker(bind=get_engine(), autoflush=False, expire_on_commit=False) return SessionLocal @contextmanager def session_scope() -> Iterator[Session]: """脚本与定时任务用:正常提交、异常回滚。""" session = SessionFactory()() try: yield session session.commit() except Exception: session.rollback() raise finally: session.close() def ensure_database() -> None: """库不存在就建一个。只有引导配置能做这件事——连不上库就没地方读配置。""" config = settings.database if config.name.startswith("information_schema"): return connection = pymysql.connect( host=config.host, port=config.port, user=config.user, password=config.password, connect_timeout=10, charset="utf8mb4", autocommit=True, ) try: with connection.cursor() as cursor: cursor.execute( f"CREATE DATABASE IF NOT EXISTS `{config.name}` " "DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" ) finally: connection.close() def create_all() -> None: """建表 + 给已存在的表补新增列。 只做"加法":补列、补索引,永不删列改类型。删东西必须走 SQL 脚本,否则一次误改 配置就能把生产数据洗掉。 """ target = get_engine() Base.metadata.create_all(target) added = _add_missing_columns(target) if added: logger.info("已补齐 %d 个新增列:%s", len(added), "、".join(added[:12])) def _add_missing_columns(target: Engine) -> list[str]: inspector = inspect(target) existing_tables = set(inspector.get_table_names()) added: list[str] = [] with target.begin() as connection: for table in Base.metadata.sorted_tables: if table.name not in existing_tables: continue # create_all 刚建过,列一定是全的 present = {column["name"] for column in inspector.get_columns(table.name)} for column in table.columns: if column.name in present: continue column_type = column.type.compile(target.dialect) piece = f"ALTER TABLE `{table.name}` ADD COLUMN `{column.name}` {column_type}" if not column.nullable: default = _literal_default(column) if default is None: piece += " NULL" elif _large_type_needs_expression_default(column_type): # MySQL 8:BLOB/TEXT/JSON/GEOMETRY 不接受字面量默认值, # 只能写成表达式默认值 DEFAULT (''),否则整条 ADD COLUMN 直接报错。 piece += f" NOT NULL DEFAULT ({default})" else: piece += f" NOT NULL DEFAULT {default}" connection.execute(text(piece)) added.append(f"{table.name}.{column.name}") return added #: MySQL 里这几类大字段不能带字面量默认值(1101),得用括号包起来的表达式默认值 _LARGE_TYPE_PREFIXES = ("tinytext", "text", "mediumtext", "longtext", "tinyblob", "blob", "mediumblob", "longblob", "json", "geometry") def _large_type_needs_expression_default(column_type: str) -> bool: return column_type.lower().startswith(_LARGE_TYPE_PREFIXES) def _literal_default(column: object) -> str | None: server_default = getattr(column, "server_default", None) if server_default is not None and getattr(server_default, "arg", None): return str(server_default.arg) default = getattr(column, "default", None) if default is not None and default.is_scalar: value = default.arg if isinstance(value, bool): return "1" if value else "0" if isinstance(value, (int, float)): return str(value) return "'" + str(value).replace("'", "''") + "'" return None def legacy_engine() -> Engine | None: """老四算库的只读连接。迁移与对账用,没配就返回 None。""" if not settings.legacy.enabled: return None return create_engine(settings.legacy.url, pool_pre_ping=True, **{}) def ping() -> bool: try: with get_engine().connect() as connection: connection.execute(text("SELECT 1")) return True except Exception as exc: # pragma: no cover - 取决于环境 logger.warning("数据库不可用:%s", exc) return False