|
| 1 | +from logging.config import fileConfig |
| 2 | +from sqlalchemy import pool |
| 3 | +from sqlalchemy.engine import Connection |
| 4 | +from sqlalchemy.ext.asyncio import async_engine_from_config |
| 5 | +from alembic import context |
| 6 | +import os |
| 7 | +import sys |
| 8 | + |
| 9 | +sys.path.append(os.path.dirname(os.path.dirname(__file__))) |
| 10 | +from app.core.config import settings |
| 11 | +from app.db.base import Base |
| 12 | + |
| 13 | +# this is the Alembic Config object |
| 14 | +config = context.config |
| 15 | + |
| 16 | +# Interpret the config file for Python logging. |
| 17 | +fileConfig(config.config_file_name) |
| 18 | + |
| 19 | +target_metadata = Base.metadata |
| 20 | + |
| 21 | +def run_migrations_offline(): |
| 22 | + url = settings.POSTGRES_DSN |
| 23 | + context.configure(url=url, target_metadata=target_metadata, literal_binds=True) |
| 24 | + with context.begin_transaction(): |
| 25 | + context.run_migrations() |
| 26 | + |
| 27 | +async def run_migrations_online(): |
| 28 | + connectable = async_engine_from_config( |
| 29 | + config.get_section(config.config_ini_section), |
| 30 | + prefix="sqlalchemy.", |
| 31 | + poolclass=pool.NullPool, |
| 32 | + url=settings.POSTGRES_DSN |
| 33 | + ) |
| 34 | + async with connectable.connect() as connection: |
| 35 | + await connection.run_sync(do_run_migrations) |
| 36 | + |
| 37 | +def do_run_migrations(connection: Connection): |
| 38 | + context.configure(connection=connection, target_metadata=target_metadata) |
| 39 | + with context.begin_transaction(): |
| 40 | + context.run_migrations() |
| 41 | + |
| 42 | +if context.is_offline_mode(): |
| 43 | + run_migrations_offline() |
| 44 | +else: |
| 45 | + import asyncio |
| 46 | + asyncio.run(run_migrations_online()) |
0 commit comments