| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- """
- Alembic 环境配置
- 本模块配置 Alembic 迁移环境,包括数据库连接和模型元数据。
- """
- from logging.config import fileConfig
- import os
- import sys
- from pathlib import Path
- from sqlalchemy import engine_from_config
- from sqlalchemy import pool
- from alembic import context
- # 添加项目根目录到 Python 路径
- sys.path.insert(0, str(Path(__file__).parent.parent))
- # 导入配置和模型
- from src.config.settings import get_settings
- from src.infrastructure.database.models import Base
- # this is the Alembic Config object, which provides
- # access to the values within the .ini file in use.
- config = context.config
- # Interpret the config file for Python logging.
- # This line sets up loggers basically.
- if config.config_file_name is not None:
- fileConfig(config.config_file_name)
- # 从环境变量获取数据库 URL
- settings = get_settings()
- config.set_main_option("sqlalchemy.url", settings.database.url)
- # add your model's MetaData object here
- # for 'autogenerate' support
- # from myapp import mymodel
- # target_metadata = mymodel.Base.metadata
- target_metadata = Base.metadata
- # other values from the config, defined by the needs of env.py,
- # can be acquired:
- # my_important_option = config.get_main_option("my_important_option")
- # ... etc.
- def run_migrations_offline() -> None:
- """
- 在 'offline' 模式下运行迁移。
- 这会配置上下文只使用 URL,而不是 Engine,
- 尽管这里也可以接受 Engine。通过跳过 Engine 的创建,
- 我们甚至不需要 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()
|