Files

79 lines
2.0 KiB
Python
Raw Permalink Normal View History

from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# 导入模型
from app.models.user import Base
# 导入配置
from app.core.config import settings
# 确保Python能够找到app模块
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# 这是Alembic Config对象它提供对.ini文件中值的访问
config = context.config
# 解释配置文件并设置日志记录器
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# 添加你的模型元数据对象
target_metadata = Base.metadata
# 其他值来自config可以通过以下方式定义
# my_important_option = config.get_main_option("my_important_option")
# ... 等等。
def run_migrations_offline() -> None:
"""'offline'模式下运行迁移。
这配置了上下文只需要一个URL并且不要求引擎可用
跳过引擎创建甚至不需要DBAPI可用
调用context.execute()来执行迁移
"""
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:
"""'online'模式下运行迁移。
在这种情况下我们创建了一个Engine并将其与迁移上下文关联
"""
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
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()