env.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """
  2. Alembic environment configuration for async SQLAlchemy.
  3. """
  4. import asyncio
  5. from logging.config import fileConfig
  6. from sqlalchemy import pool
  7. from sqlalchemy.engine import Connection
  8. from sqlalchemy.ext.asyncio import async_engine_from_config
  9. from alembic import context
  10. # Import Base and all models so Alembic can detect them
  11. from app.core.database import Base
  12. from app.models import * # noqa: F403, F401
  13. from app.config import settings
  14. # Alembic Config object
  15. config = context.config
  16. # Override sqlalchemy.url with the one from settings
  17. config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
  18. # Interpret the config file for Python logging
  19. if config.config_file_name is not None:
  20. fileConfig(config.config_file_name)
  21. # Target metadata for 'autogenerate' support
  22. target_metadata = Base.metadata
  23. def run_migrations_offline() -> None:
  24. """
  25. Run migrations in 'offline' mode.
  26. This configures the context with just a URL and not an Engine.
  27. Calls to context.execute() here emit the given string to the script output.
  28. """
  29. url = config.get_main_option("sqlalchemy.url")
  30. context.configure(
  31. url=url,
  32. target_metadata=target_metadata,
  33. literal_binds=True,
  34. dialect_opts={"paramstyle": "named"},
  35. )
  36. with context.begin_transaction():
  37. context.run_migrations()
  38. def do_run_migrations(connection: Connection) -> None:
  39. """Run migrations with the given connection."""
  40. context.configure(connection=connection, target_metadata=target_metadata)
  41. with context.begin_transaction():
  42. context.run_migrations()
  43. async def run_async_migrations() -> None:
  44. """
  45. Run migrations in 'online' mode using async engine.
  46. """
  47. connectable = async_engine_from_config(
  48. config.get_section(config.config_ini_section, {}),
  49. prefix="sqlalchemy.",
  50. poolclass=pool.NullPool,
  51. )
  52. async with connectable.connect() as connection:
  53. await connection.run_sync(do_run_migrations)
  54. await connectable.dispose()
  55. def run_migrations_online() -> None:
  56. """
  57. Run migrations in 'online' mode.
  58. """
  59. asyncio.run(run_async_migrations())
  60. if context.is_offline_mode():
  61. run_migrations_offline()
  62. else:
  63. run_migrations_online()