fix(rag): make migration 030 offline-renderable (plpgsql DO block)

The initial 030 used sa.inspect(op.get_bind()) for its conditional ALTERs, which
raises NoInspectionAvailable under `alembic upgrade --sql` (offline mode) —
breaking test_enum_migration_parity and any offline SQL generation. Reimplement
the same idempotent rename (text->content) + add (created_at) as a self-contained
plpgsql DO block that guards on information_schema at execution time, so it
renders offline and runs online identically. Round-trip verified.
This commit is contained in:
Renn F
2026-06-15 04:54:51 +02:00
parent 996ef56ac3
commit e53eb5b7ee
@@ -16,10 +16,12 @@ The legacy ``chunk_index`` / integer ``id`` columns are left untouched: the
engine never references them and dropping them would be a needless destructive engine never references them and dropping them would be a needless destructive
change. change.
Both directions guard on actual column presence, so the migration is idempotent The work runs inside a single plpgsql ``DO`` block that guards each step on
``information_schema`` at execution time. That keeps the migration idempotent
and safe whether a table is piragi-shaped, already engine-shaped, or absent and safe whether a table is piragi-shaped, already engine-shaped, or absent
(e.g. ``chunks_code``, which has never been populated and will be created fresh (e.g. ``chunks_code``, never populated) — and, unlike Python-side reflection,
in the correct shape by the engine). it renders under ``alembic upgrade --sql`` (offline mode) where no live
connection exists.
Revision ID: 030_rag_chunks_content_schema Revision ID: 030_rag_chunks_content_schema
Revises: 029_project_quality_command Revises: 029_project_quality_command
@@ -28,24 +30,17 @@ Create Date: 2026-06-15
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING
import sqlalchemy as sa
from alembic import op from alembic import op
if TYPE_CHECKING:
from sqlalchemy.engine import Inspector
revision = "030_rag_chunks_content_schema" revision = "030_rag_chunks_content_schema"
down_revision = "029_project_quality_command" down_revision = "029_project_quality_command"
branch_labels = None branch_labels = None
depends_on = None depends_on = None
# Frozen snapshot of the chunk tables — one per ``IndexType`` value at the time # One per ``IndexType`` value at the time of writing. Hardcoded so the migration
# of writing. Hardcoded so the migration stays self-contained and never imports # stays self-contained and never imports evolving application code; a unit test
# evolving application code; a unit test guards this tuple against the live # guards this tuple against the live ``IndexType`` enum so a newly added index
# ``IndexType`` enum so a newly added index type cannot silently escape the # type cannot silently escape the schema alignment.
# schema alignment.
CHUNK_TABLES = ( CHUNK_TABLES = (
"chunks_code", "chunks_code",
"chunks_documentation", "chunks_documentation",
@@ -58,39 +53,64 @@ CHUNK_TABLES = (
"chunks_learnings", "chunks_learnings",
) )
# SQL array literal of the table names (validated identifiers from the tuple).
def _columns(inspector: Inspector, table: str) -> set[str]: _TABLES_SQL = ", ".join(f"'{name}'" for name in CHUNK_TABLES)
"""Return the set of column names currently present on ``table``."""
return {col["name"] for col in inspector.get_columns(table)}
def upgrade() -> None: def upgrade() -> None:
inspector = sa.inspect(op.get_bind()) op.execute(
for table in CHUNK_TABLES: f"""
if not inspector.has_table(table): DO $$
continue DECLARE
cols = _columns(inspector, table) t text;
if "text" in cols and "content" not in cols: BEGIN
op.alter_column(table, "text", new_column_name="content") FOREACH t IN ARRAY ARRAY[{_TABLES_SQL}] LOOP
if "created_at" not in cols: IF EXISTS (
op.add_column( SELECT 1 FROM information_schema.columns
table, WHERE table_schema = 'public'
sa.Column( AND table_name = t AND column_name = 'text'
"created_at", ) AND NOT EXISTS (
sa.TIMESTAMP(timezone=True), SELECT 1 FROM information_schema.columns
nullable=False, WHERE table_schema = 'public'
server_default=sa.text("NOW()"), AND table_name = t AND column_name = 'content'
), ) THEN
) EXECUTE format('ALTER TABLE %I RENAME COLUMN text TO content', t);
END IF;
EXECUTE format(
'ALTER TABLE IF EXISTS %I '
'ADD COLUMN IF NOT EXISTS created_at '
'TIMESTAMPTZ NOT NULL DEFAULT NOW()',
t
);
END LOOP;
END $$;
"""
)
def downgrade() -> None: def downgrade() -> None:
inspector = sa.inspect(op.get_bind()) op.execute(
for table in CHUNK_TABLES: f"""
if not inspector.has_table(table): DO $$
continue DECLARE
cols = _columns(inspector, table) t text;
if "created_at" in cols: BEGIN
op.drop_column(table, "created_at") FOREACH t IN ARRAY ARRAY[{_TABLES_SQL}] LOOP
if "content" in cols and "text" not in cols: EXECUTE format(
op.alter_column(table, "content", new_column_name="text") 'ALTER TABLE IF EXISTS %I DROP COLUMN IF EXISTS created_at', t
);
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = t AND column_name = 'content'
) AND NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = t AND column_name = 'text'
) THEN
EXECUTE format('ALTER TABLE %I RENAME COLUMN content TO text', t);
END IF;
END LOOP;
END $$;
"""
)