env.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import asyncio
  2. from logging.config import fileConfig
  3. from alembic import context
  4. from sqlalchemy import pool
  5. from sqlalchemy.engine import Connection
  6. from sqlalchemy.ext.asyncio import create_async_engine
  7. from app.config.path_conf import ALEMBIC_VERSION_DIR
  8. from app.config.setting import settings
  9. from app.core.base_model import MappedBase
  10. from app.utils.import_util import ImportUtil
  11. # 确保 alembic 版本目录存在
  12. ALEMBIC_VERSION_DIR.mkdir(parents=True, exist_ok=True)
  13. # 清除MappedBase.metadata中的表定义,避免重复注册
  14. if hasattr(MappedBase, "metadata") and MappedBase.metadata.tables:
  15. print(f"🧹 清除已存在的表定义,当前有 {len(MappedBase.metadata.tables)} 个表")
  16. # 创建一个新的空metadata对象
  17. from sqlalchemy import MetaData
  18. MappedBase.metadata = MetaData()
  19. print("✅️ 已重置metadata")
  20. # 自动查找所有模型
  21. print("🔍 开始查找模型...")
  22. found_models = ImportUtil.find_models(MappedBase)
  23. print(f"📊 找到 {len(found_models)} 个有效模型")
  24. # this is the Alembic Config object, which provides
  25. # access to the values within the .ini file in use.
  26. alembic_config = context.config
  27. # Interpret the config file for Python logging.
  28. # This line sets up loggers basically.
  29. if alembic_config.config_file_name is not None:
  30. fileConfig(alembic_config.config_file_name)
  31. # add your model's MetaData object here
  32. # for 'autogenerate' support
  33. # from myapp import mymodel
  34. # target_metadata = mymodel.Base.metadata
  35. target_metadata = MappedBase.metadata
  36. # other values from the config, defined by the needs of env.py,
  37. # can be acquired:
  38. # my_important_option = config.get_main_option("my_important_option")
  39. # ... etc.
  40. alembic_config.set_main_option("sqlalchemy.url", settings.ASYNC_DB_URI)
  41. def run_migrations_offline() -> None:
  42. """Run migrations in 'offline' mode.
  43. This configures the context with just a URL
  44. and not an Engine, though an Engine is acceptable
  45. here as well. By skipping the Engine creation
  46. we don't even need a DBAPI to be available.
  47. Calls to context.execute() here emit the given string to the
  48. script output.
  49. 返回:
  50. - None
  51. """
  52. url = alembic_config.get_main_option("sqlalchemy.url")
  53. # 确保URL不为None
  54. if url is None:
  55. raise ValueError("数据库URL未正确配置,请检查环境配置文件")
  56. context.configure(
  57. url=url,
  58. target_metadata=target_metadata,
  59. literal_binds=True,
  60. dialect_opts={"paramstyle": "named"},
  61. )
  62. with context.begin_transaction():
  63. context.run_migrations()
  64. def run_migrations_online() -> None:
  65. """Run migrations in 'online' mode.
  66. In this scenario we need to create an Engine
  67. and associate a connection with the context.
  68. 返回:
  69. - None
  70. """
  71. url = alembic_config.get_main_option("sqlalchemy.url")
  72. # 确保URL不为None
  73. if url is None:
  74. raise ValueError("数据库URL未正确配置,请检查环境配置文件")
  75. connectable = create_async_engine(url, poolclass=pool.NullPool)
  76. async def run_async_migrations() -> None:
  77. async with connectable.connect() as connection:
  78. await connection.run_sync(do_run_migrations)
  79. await connectable.dispose()
  80. def do_run_migrations(connection: Connection) -> None:
  81. def process_revision_directives(context, revision, directives) -> None:
  82. script = directives[0]
  83. # 检查所有操作集是否为空
  84. all_empty = all(ops.is_empty() for ops in script.upgrade_ops_list)
  85. if all_empty:
  86. # 如果没有实际变更,不生成迁移文件
  87. directives[:] = []
  88. print("❎️ 未检测到模型变更,不生成迁移文件")
  89. else:
  90. print("✅️ 检测到模型变更,生成迁移文件")
  91. context.configure(
  92. connection=connection,
  93. target_metadata=target_metadata,
  94. compare_type=True,
  95. compare_server_default=True,
  96. transaction_per_migration=True,
  97. process_revision_directives=process_revision_directives,
  98. )
  99. with context.begin_transaction():
  100. context.run_migrations()
  101. asyncio.run(run_async_migrations())
  102. if context.is_offline_mode():
  103. run_migrations_offline()
  104. else:
  105. run_migrations_online()