env.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """
  2. Alembic 环境配置
  3. 本模块配置 Alembic 迁移环境,包括数据库连接和模型元数据。
  4. """
  5. from logging.config import fileConfig
  6. import os
  7. import sys
  8. from pathlib import Path
  9. from sqlalchemy import engine_from_config
  10. from sqlalchemy import pool
  11. from alembic import context
  12. # 添加项目根目录到 Python 路径
  13. sys.path.insert(0, str(Path(__file__).parent.parent))
  14. # 导入配置和模型
  15. from src.config.settings import get_settings
  16. from src.infrastructure.database.models import Base
  17. # this is the Alembic Config object, which provides
  18. # access to the values within the .ini file in use.
  19. config = context.config
  20. # Interpret the config file for Python logging.
  21. # This line sets up loggers basically.
  22. if config.config_file_name is not None:
  23. fileConfig(config.config_file_name)
  24. # 从环境变量获取数据库 URL
  25. settings = get_settings()
  26. config.set_main_option("sqlalchemy.url", settings.database.url)
  27. # add your model's MetaData object here
  28. # for 'autogenerate' support
  29. # from myapp import mymodel
  30. # target_metadata = mymodel.Base.metadata
  31. target_metadata = Base.metadata
  32. # other values from the config, defined by the needs of env.py,
  33. # can be acquired:
  34. # my_important_option = config.get_main_option("my_important_option")
  35. # ... etc.
  36. def run_migrations_offline() -> None:
  37. """
  38. 在 'offline' 模式下运行迁移。
  39. 这会配置上下文只使用 URL,而不是 Engine,
  40. 尽管这里也可以接受 Engine。通过跳过 Engine 的创建,
  41. 我们甚至不需要 DBAPI 可用。
  42. 调用 context.execute() 会将给定的字符串输出到脚本输出。
  43. """
  44. url = config.get_main_option("sqlalchemy.url")
  45. context.configure(
  46. url=url,
  47. target_metadata=target_metadata,
  48. literal_binds=True,
  49. dialect_opts={"paramstyle": "named"},
  50. )
  51. with context.begin_transaction():
  52. context.run_migrations()
  53. def run_migrations_online() -> None:
  54. """
  55. 在 'online' 模式下运行迁移。
  56. 在这种情况下,我们需要创建一个 Engine
  57. 并将连接与上下文关联。
  58. """
  59. connectable = engine_from_config(
  60. config.get_section(config.config_ini_section, {}),
  61. prefix="sqlalchemy.",
  62. poolclass=pool.NullPool,
  63. )
  64. with connectable.connect() as connection:
  65. context.configure(
  66. connection=connection,
  67. target_metadata=target_metadata
  68. )
  69. with context.begin_transaction():
  70. context.run_migrations()
  71. if context.is_offline_mode():
  72. run_migrations_offline()
  73. else:
  74. run_migrations_online()