70 lines
1.9 KiB
Python
70 lines
1.9 KiB
Python
"""Alembic 运行环境。
|
||
|
||
设计目标:同一套模型先在 SQLite 上开发,之后无损迁移到 MySQL。
|
||
因此
|
||
|
||
* DSN 来自 ``settings.sync_database_url``(自动把 aiosqlite/aiomysql 换成同步驱动)
|
||
* SQLite 下统一使用 ``render_as_batch`` 以支持 ALTER
|
||
* 全部表名/约束名遵循 ``db.base.NAMING_CONVENTION``,autogenerate 结果稳定
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from logging.config import fileConfig
|
||
|
||
from alembic import context
|
||
from sqlalchemy import engine_from_config, pool
|
||
|
||
from app.core.config import settings
|
||
from app.db.base import Base
|
||
from app import models # noqa: F401 -- 注册全部映射
|
||
|
||
config = context.config
|
||
if config.config_file_name is not None:
|
||
fileConfig(config.config_file_name)
|
||
|
||
config.set_main_option("sqlalchemy.url", settings.sync_database_url)
|
||
target_metadata = Base.metadata
|
||
|
||
|
||
def _offline_url() -> str:
|
||
return config.get_main_option("sqlalchemy.url")
|
||
|
||
|
||
def run_migrations_offline() -> None:
|
||
context.configure(
|
||
url=_offline_url(),
|
||
target_metadata=target_metadata,
|
||
literal_binds=True,
|
||
dialect_opts={"paramstyle": "named"},
|
||
compare_type=True,
|
||
compare_server_default=True,
|
||
render_as_batch=settings.is_sqlite,
|
||
)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
|
||
|
||
def run_migrations_online() -> None:
|
||
connectable = engine_from_config(
|
||
config.get_section(config.config_ini_section, {}),
|
||
prefix="sqlalchemy.",
|
||
poolclass=pool.NullPool,
|
||
)
|
||
with connectable.connect() as connection:
|
||
context.configure(
|
||
connection=connection,
|
||
target_metadata=target_metadata,
|
||
compare_type=True,
|
||
compare_server_default=True,
|
||
render_as_batch=settings.is_sqlite,
|
||
)
|
||
with context.begin_transaction():
|
||
context.run_migrations()
|
||
|
||
|
||
if context.is_offline_mode():
|
||
run_migrations_offline()
|
||
else:
|
||
run_migrations_online()
|