|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from logging.config import fileConfig |
| 5 | + |
| 6 | +# Add the project root directory to the Python path |
| 7 | +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| 8 | + |
| 9 | +from sqlalchemy import pool |
| 10 | +from sqlalchemy.engine import Connection |
| 11 | +from sqlalchemy.ext.asyncio import async_engine_from_config |
| 12 | + |
| 13 | +from alembic import context |
| 14 | +from api.core.config import settings |
| 15 | + |
| 16 | +# Import your models here |
| 17 | +from api.core.database import Base |
| 18 | + |
| 19 | +# this is the Alembic Config object |
| 20 | +config = context.config |
| 21 | + |
| 22 | +# Interpret the config file for Python logging |
| 23 | +if config.config_file_name is not None: |
| 24 | + fileConfig(config.config_file_name) |
| 25 | + |
| 26 | +# Set sqlalchemy.url |
| 27 | +config.set_main_option("sqlalchemy.url", settings.DATABASE_URL) |
| 28 | + |
| 29 | +# Add your model's MetaData object here for 'autogenerate' support |
| 30 | +target_metadata = Base.metadata |
| 31 | + |
| 32 | + |
| 33 | +def run_migrations_offline() -> None: |
| 34 | + """Run migrations in 'offline' mode.""" |
| 35 | + url = config.get_main_option("sqlalchemy.url") |
| 36 | + context.configure( |
| 37 | + url=url, |
| 38 | + target_metadata=target_metadata, |
| 39 | + literal_binds=True, |
| 40 | + dialect_opts={"paramstyle": "named"}, |
| 41 | + ) |
| 42 | + |
| 43 | + with context.begin_transaction(): |
| 44 | + context.run_migrations() |
| 45 | + |
| 46 | + |
| 47 | +def do_run_migrations(connection: Connection) -> None: |
| 48 | + context.configure(connection=connection, target_metadata=target_metadata) |
| 49 | + |
| 50 | + with context.begin_transaction(): |
| 51 | + context.run_migrations() |
| 52 | + |
| 53 | + |
| 54 | +async def run_async_migrations() -> None: |
| 55 | + """In this scenario we need to create an Engine |
| 56 | + and associate a connection with the context.""" |
| 57 | + |
| 58 | + connectable = async_engine_from_config( |
| 59 | + config.get_section(config.config_ini_section, {}), |
| 60 | + prefix="sqlalchemy.", |
| 61 | + poolclass=pool.NullPool, |
| 62 | + ) |
| 63 | + |
| 64 | + async with connectable.connect() as connection: |
| 65 | + await connection.run_sync(do_run_migrations) |
| 66 | + |
| 67 | + await connectable.dispose() |
| 68 | + |
| 69 | + |
| 70 | +def run_migrations_online() -> None: |
| 71 | + """Run migrations in 'online' mode.""" |
| 72 | + |
| 73 | + asyncio.run(run_async_migrations()) |
| 74 | + |
| 75 | + |
| 76 | +if context.is_offline_mode(): |
| 77 | + run_migrations_offline() |
| 78 | +else: |
| 79 | + run_migrations_online() |
0 commit comments