/ migrations / env.py
env.py
1 """Alembic environment file.""" 2 3 import asyncio 4 from logging.config import fileConfig 5 6 from alembic import context 7 from sqlalchemy.engine import Connection 8 9 from spoolman.database.database import Database, get_connection_url 10 from spoolman.database.models import Base 11 12 config = context.config 13 14 if config.config_file_name is not None: 15 fileConfig(config.config_file_name) 16 17 target_metadata = Base.metadata 18 19 20 def run_migrations_offline() -> None: 21 """Run migrations in 'offline' mode. 22 23 This configures the context with just a URL 24 and not an Engine, though an Engine is acceptable 25 here as well. By skipping the Engine creation 26 we don't even need a DBAPI to be available. 27 28 Calls to context.execute() here emit the given string to the 29 script output. 30 31 """ 32 context.configure( 33 url=get_connection_url(), 34 target_metadata=target_metadata, 35 literal_binds=True, 36 dialect_opts={"paramstyle": "named"}, 37 render_as_batch=True, 38 ) 39 40 with context.begin_transaction(): 41 context.run_migrations() 42 43 44 def do_run_migrations(connection: Connection) -> None: 45 """Run migrations in 'online' mode.""" 46 context.configure(connection=connection, target_metadata=target_metadata) 47 48 with context.begin_transaction(): 49 context.run_migrations() 50 51 52 async def run_async_migrations() -> None: 53 """In this scenario we need to create an Engine and associate a connection with the context.""" 54 db = Database(get_connection_url()) 55 db.connect() 56 57 if db.engine is None: 58 raise RuntimeError("Engine not created.") 59 60 async with db.engine.connect() as connection: 61 await connection.run_sync(do_run_migrations) 62 63 await db.engine.dispose() 64 65 66 if context.is_offline_mode(): 67 run_migrations_offline() 68 else: 69 asyncio.run(run_async_migrations())