- env.py: 自动创建 alembic_version 表时使用 VARCHAR(255) 避免截断 - docker-compose: 添加 frontend nginx 服务 + alembic 挂载 - nginx.conf: SPA 路由 + API 代理
83 lines
2.5 KiB
Python
83 lines
2.5 KiB
Python
from logging.config import fileConfig
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import engine_from_config, pool, text
|
|
from alembic import context
|
|
|
|
# 把项目根加入 pythonpath,让 alembic 能找到 src 包
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
from src.db.base import Base # noqa: E402
|
|
from src.db.models import * # noqa: E402,F401,F403 # 导入所有模型确保注册
|
|
from src.core.config import settings # noqa: E402
|
|
|
|
# this is the Alembic Config object
|
|
config = context.config
|
|
|
|
# 用 settings 的 DATABASE_URL,但转成 sync 驱动
|
|
DB_URL = settings.DATABASE_URL
|
|
if DB_URL.startswith("postgresql+asyncpg"):
|
|
DB_URL = DB_URL.replace("postgresql+asyncpg", "postgresql+psycopg2", 1)
|
|
config.set_main_option("sqlalchemy.url", DB_URL)
|
|
|
|
# Interpret the config file for Python logging.
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def _ensure_version_table(connection):
|
|
"""确保 alembic_version 表存在且 version_num 列足够长。
|
|
|
|
Alembic 默认 version_num 是 String(32),但我们的迁移名较长(如
|
|
0005_prediction_status_and_stats_provenance 有 41 个字符),会导致
|
|
StringDataRightTruncation 错误。
|
|
"""
|
|
result = connection.execute(text(
|
|
"SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'alembic_version')"
|
|
))
|
|
if not result.scalar():
|
|
connection.execute(text(
|
|
"CREATE TABLE alembic_version (version_num VARCHAR(255) NOT NULL PRIMARY KEY)"
|
|
))
|
|
connection.commit()
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Run migrations in 'offline' mode."""
|
|
url = config.get_main_option("sqlalchemy.url")
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def run_migrations_online() -> None:
|
|
"""Run migrations in 'online' mode."""
|
|
connectable = engine_from_config(
|
|
config.get_section(config.config_ini_section, {}),
|
|
prefix="sqlalchemy.",
|
|
poolclass=pool.NullPool,
|
|
)
|
|
|
|
with connectable.connect() as connection:
|
|
_ensure_version_table(connection)
|
|
context.configure(connection=connection, target_metadata=target_metadata)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
if context.is_offline_mode():
|
|
run_migrations_offline()
|
|
else:
|
|
run_migrations_online()
|