langchain-learning-kit/app/db/alembic/env.py

80 lines
2.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Alembic 环境配置。
"""
from logging.config import fileConfig
import os
import sys
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# 将父目录添加到路径以进行导入
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
# 从项目根目录加载 .env从 alembic 目录向上 3 级)
from dotenv import load_dotenv
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
env_path = os.path.join(project_root, '.env')
load_dotenv(env_path)
from app.config import Settings
from app.db.models import Base
# 这是 Alembic 配置对象
config = context.config
# 为 Python 日志解释配置文件
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# 加载设置并设置数据库 URL
settings = Settings()
config.set_main_option("sqlalchemy.url", settings.database_url)
# 为 'autogenerate' 支持添加模型的 MetaData 对象
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""
'offline' 模式下运行迁移。
"""
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' 模式下运行迁移。
"""
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()