- Build async SQLAlchemy engine with PRAGMA journal_mode=WAL, foreign_keys=ON, and synchronous=NORMAL - Implement DownloadJob ORM model with protobuf mapping and state transition guards - Initialize Alembic async migrations and create initial download_jobs table schema - Add unit test suite in tests/test_db.py covering WAL pragmas, CRUD, and state transitions - Update todo.txt marking Priority (A) tasks complete
85 lines
2.2 KiB
Python
85 lines
2.2 KiB
Python
import asyncio
|
|
import os
|
|
from logging.config import fileConfig
|
|
from pathlib import Path
|
|
|
|
from alembic import context
|
|
from sqlalchemy import pool
|
|
from sqlalchemy.engine import Connection
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
from worker.db.engine import normalize_database_url
|
|
from worker.db.models import Base
|
|
|
|
config = context.config
|
|
|
|
if config.config_file_name is not None:
|
|
fileConfig(config.config_file_name)
|
|
|
|
target_metadata = Base.metadata
|
|
|
|
|
|
def get_url() -> str:
|
|
"""Retrieve normalized async database URL."""
|
|
env_url = os.getenv("DATABASE_URL")
|
|
ini_url = config.get_main_option("sqlalchemy.url")
|
|
chosen = env_url or ini_url or "sqlite+aiosqlite:///data/magnetflix.sqlite3"
|
|
url = normalize_database_url(chosen)
|
|
|
|
prefix = "sqlite+aiosqlite:///"
|
|
if url.startswith(prefix):
|
|
raw_path = url[len(prefix) :]
|
|
if raw_path and raw_path != ":memory:":
|
|
Path(raw_path).resolve().parent.mkdir(parents=True, exist_ok=True)
|
|
return url
|
|
|
|
|
|
def run_migrations_offline() -> None:
|
|
"""Run migrations in 'offline' mode."""
|
|
url = get_url()
|
|
context.configure(
|
|
url=url,
|
|
target_metadata=target_metadata,
|
|
literal_binds=True,
|
|
dialect_opts={"paramstyle": "named"},
|
|
render_as_batch=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
def do_run_migrations(connection: Connection) -> None:
|
|
"""Configure migration context on active connection."""
|
|
context.configure(
|
|
connection=connection,
|
|
target_metadata=target_metadata,
|
|
render_as_batch=True,
|
|
)
|
|
|
|
with context.begin_transaction():
|
|
context.run_migrations()
|
|
|
|
|
|
async def run_async_migrations() -> None:
|
|
"""Run migrations asynchronously using an AsyncEngine."""
|
|
connectable = create_async_engine(
|
|
get_url(),
|
|
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()
|