xxy 43f3e0b746 Initial commit
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 18:41:06 +08:00

53 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
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 已就绪")