read.markets/alembic/env.py
Giorgio Gilestro 78ce8c8b0d alembic: make migration chain SQLite-compatible (fresh upgrade)
Five existing migrations used op.alter_column / op.create_unique_constraint /
op.drop_constraint / op.create_foreign_key directly on the users + quotes +
quotes_daily tables. SQLite has no native support for those operations and
requires Alembic's batch_alter_table copy-and-rename workaround.

This wasn't noticed until now because the test suite uses
Base.metadata.create_all to materialise schema, not the migration chain
itself; and prod is MariaDB. But running `alembic upgrade head` against
a fresh SQLite database (developer onboarding, CI smoke tests, the
test container's own bootstrap) would fail at 0005.

Fixes:
- alembic/env.py: set render_as_batch=True when the dialect is SQLite.
  This auto-wraps any future autogenerated migration but doesn't
  retroactively rewrite existing op.* calls.
- 0005 (widen quotes.symbol), 0013 (referrals), 0018 (polar webhook),
  0019 (stripe), 0023 (users.lang index + qd_symbol widen) explicitly
  wrap their problematic ops in `with op.batch_alter_table(...) as bop`.

Now `alembic upgrade head` + `alembic downgrade base` round-trip cleanly
on a fresh SQLite database. MariaDB prod behaviour unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 00:16:09 +02:00

77 lines
2.6 KiB
Python

"""Alembic environment — DB URL is sourced from app/config.Settings at runtime
so we keep secrets out of alembic.ini. Async engine is used in 'online' mode."""
from __future__ import annotations
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from app.config import get_settings
from app.db import Base
# Import models so that Base.metadata is populated.
from app import models # noqa: F401
config = context.config
# Inject the real DB URL from Settings.
config.set_main_option("sqlalchemy.url", get_settings().DATABASE_URL)
if config.config_file_name is not None:
# disable_existing_loggers=False is essential: the app applies
# migrations in-process at startup (see app.main lifespan), so the
# default True would disable uvicorn's already-configured loggers —
# silencing access logs and 500 tracebacks for the whole process.
fileConfig(config.config_file_name, disable_existing_loggers=False)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
# render_as_batch is required for SQLite, which doesn't support
# most ALTER COLUMN / ADD CONSTRAINT operations natively. With
# batch mode enabled, Alembic emits a copy-and-rename dance under
# SQLite while still producing plain ALTER on MariaDB / Postgres,
# so prod migrations are unchanged. Detect via the dialect name.
render_as_batch = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_type=True,
render_as_batch=render_as_batch,
)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())