first init
This commit is contained in:
65
alembic/env.py
Normal file
65
alembic/env.py
Normal file
@@ -0,0 +1,65 @@
|
||||
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 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())
|
||||
Reference in New Issue
Block a user