Files
Yigit Colakoglu 4f6098e8c2
All checks were successful
Build And Test / publish (push) Successful in 1m30s
Initial commit
2025-12-30 15:16:45 -08:00

102 lines
2.7 KiB
Python

"""Alembic migration environment configuration."""
import asyncio
import os
import sys
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from sqlmodel import SQLModel
from alembic import context
# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
# Import all models to register them with SQLModel.metadata
from database.models import ( # noqa: F401
CacheMeta,
EmailCache,
EventCache,
ContactCache,
SyncState,
)
# this is the Alembic Config object
config = context.config
# Interpret the config file for Python logging
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# SQLModel metadata for autogenerate
target_metadata = SQLModel.metadata
# Get database URL from environment or config
def get_url() -> str:
"""Get database URL from environment variable or config."""
sqlite_path = os.environ.get("SQLITE_PATH", "data/cache.db")
return f"sqlite+aiosqlite:///{sqlite_path}"
def run_migrations_offline() -> None:
"""
Run migrations in 'offline' mode.
This configures the context with just a URL and not an Engine.
Calls to context.execute() emit the SQL to the script output.
"""
url = get_url()
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
render_as_batch=True, # Required for SQLite ALTER TABLE support
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Run migrations with the given connection."""
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True, # Required for SQLite ALTER TABLE support
)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""Run migrations in 'online' mode with async engine."""
configuration = config.get_section(config.config_ini_section) or {}
configuration["sqlalchemy.url"] = get_url()
connectable = async_engine_from_config(
configuration,
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()