""" database/init_db.py 按需建表:仅创建本模块用到的三张表,已存在则跳过(checkfirst=True)。 """ from __future__ import annotations import logging from sqlalchemy import inspect, text from database.core import engine from database.models import Base logger = logging.getLogger(__name__) def _ensure_reference_template_id_column() -> None: """为已存在的 report_section_references 表补充 template_id 字段(幂等)。 create_all(checkfirst=True) 只建缺失的表,不会给已存在的表加列, 因此这里对历史表做一次轻量级 ALTER(仅在缺列时执行)。 """ insp = inspect(engine) if "report_section_references" not in insp.get_table_names(): return columns = {c["name"] for c in insp.get_columns("report_section_references")} if "template_id" in columns: return with engine.begin() as conn: conn.execute( text( "ALTER TABLE report_section_references " "ADD COLUMN template_id VARCHAR(64) NULL" ) ) conn.execute( text( "ALTER TABLE report_section_references " "ADD INDEX ix_report_section_references_template_id (template_id)" ) ) logger.info("init_database: report_section_references.template_id 字段已补充") def init_database() -> None: """在远程 MySQL 中创建本模块所需表(若不存在)。""" Base.metadata.create_all(bind=engine, checkfirst=True) _ensure_reference_template_id_column() logger.info("init_database: report_templates / report_template_sections / report_section_references 已就绪")