env.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import asyncio
  2. from logging.config import fileConfig
  3. from sqlalchemy.engine import Connection
  4. from sqlalchemy.ext.asyncio import create_async_engine
  5. from sqlalchemy import pool
  6. from alembic import context
  7. from app.config.path_conf import ALEMBIC_VERSION_DIR
  8. from app.utils.import_util import ImportUtil
  9. from app.core.base_model import MappedBase
  10. from app.config.setting import settings
  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. url = alembic_config.get_main_option("sqlalchemy.url")
  51. # 确保URL不为None
  52. if url is None:
  53. raise ValueError("数据库URL未正确配置,请检查环境配置文件")
  54. context.configure(
  55. url=url,
  56. target_metadata=target_metadata,
  57. literal_binds=True,
  58. dialect_opts={"paramstyle": "named"},
  59. )
  60. with context.begin_transaction():
  61. context.run_migrations()
  62. def run_migrations_online() -> None:
  63. """Run migrations in 'online' mode.
  64. In this scenario we need to create an Engine
  65. and associate a connection with the context.
  66. """
  67. url = alembic_config.get_main_option("sqlalchemy.url")
  68. # 确保URL不为None
  69. if url is None:
  70. raise ValueError("数据库URL未正确配置,请检查环境配置文件")
  71. connectable = create_async_engine(url, poolclass=pool.NullPool)
  72. async def run_async_migrations():
  73. async with connectable.connect() as connection:
  74. await connection.run_sync(do_run_migrations)
  75. await connectable.dispose()
  76. def do_run_migrations(connection: Connection) -> None:
  77. def process_revision_directives(context, revision, directives):
  78. script = directives[0]
  79. # 检查所有操作集是否为空
  80. all_empty = all(ops.is_empty() for ops in script.upgrade_ops_list)
  81. if all_empty:
  82. # 如果没有实际变更,不生成迁移文件
  83. directives[:] = []
  84. print('❎️ 未检测到模型变更,不生成迁移文件')
  85. else:
  86. print('✅️ 检测到模型变更,生成迁移文件')
  87. context.configure(
  88. connection=connection,
  89. target_metadata=target_metadata,
  90. compare_type=True,
  91. compare_server_default=True,
  92. transaction_per_migration=True,
  93. process_revision_directives=process_revision_directives,
  94. )
  95. with context.begin_transaction():
  96. context.run_migrations()
  97. asyncio.run(run_async_migrations())
  98. if context.is_offline_mode():
  99. run_migrations_offline()
  100. else:
  101. run_migrations_online()