90 lines
2.4 KiB
Python
90 lines
2.4 KiB
Python
from alembic import context
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
from logging.config import fileConfig
|
|
|
|
# 导入你的配置
|
|
from config import settings
|
|
|
|
# 这是 Alembic 配置对象,提供对 .ini 文件中的值的访问。
|
|
config = context.config
|
|
|
|
# 动态设置 sqlalchemy.url
|
|
config.set_main_option("sqlalchemy.url", (
|
|
settings.DB_URL or
|
|
'{scheme}://{user}:{password}@{host}:{port}/{db}'.format(
|
|
scheme=settings.DB_SCHEMA,
|
|
user=settings.DB_USER,
|
|
password=settings.DB_PASSWORD,
|
|
host=settings.DB_HOST,
|
|
port=settings.DB_PORT,
|
|
db=settings.DB_NAME,
|
|
)
|
|
))
|
|
|
|
# 设置 target_metadata
|
|
from core.db.models import BaseModel # 假设你的 SQLAlchemy 模型在 models.py 中
|
|
|
|
target_metadata = BaseModel.metadata
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Run migrations in 'offline' mode.
|
|
|
|
This configures the context with just a URL
|
|
and not an Engine, though an Engine is acceptable
|
|
here as well. By skipping the Engine creation
|
|
we don't even need a DBAPI to be available.
|
|
|
|
Calls to context.execute() here emit the given string to the
|
|
script output.
|
|
|
|
"""
|
|
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 do_run_migrations(connection):
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
compare_type=True,
|
|
include_schemas=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_migrations_online():
|
|
# 创建异步引擎
|
|
connectable = create_async_engine(config.get_main_option("sqlalchemy.url"))
|
|
|
|
async with connectable.connect() as connection:
|
|
await connection.run_sync(do_run_migrations)
|
|
|
|
|
|
if context.is_offline_mode():
|
|
# 离线模式(同步)
|
|
run_migrations_offline()
|
|
else:
|
|
import asyncio
|
|
|
|
# 在线模式(异步)
|
|
# 检查是否已经有事件循环
|
|
try:
|
|
loop = asyncio.get_event_loop()
|
|
except RuntimeError:
|
|
loop = asyncio.new_event_loop()
|
|
asyncio.set_event_loop(loop)
|
|
|
|
# 运行迁移
|
|
loop.run_until_complete(run_migrations_online())
|