From 2c1e12a7ad12e11bae97eda2894e1ebbb91d1e33 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 22 Jul 2026 19:51:08 -0400 Subject: [PATCH] perf(backend): backfill roms_facets before installing the triggers Migrations run at startup before the app serves traffic, so no write can race the backfill. Populating the empty table first means no row can conflict, dropping the per-engine upsert guards and collapsing the two backfill statements into one. Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/alembic/versions/0100_roms_facets_table.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/backend/alembic/versions/0100_roms_facets_table.py b/backend/alembic/versions/0100_roms_facets_table.py index 6870aec41..d47425de6 100644 --- a/backend/alembic/versions/0100_roms_facets_table.py +++ b/backend/alembic/versions/0100_roms_facets_table.py @@ -48,16 +48,12 @@ _MIRRORED_COLUMNS = [ _TARGET_COLUMNS = ", ".join(target for target, _ in _MIRRORED_COLUMNS) _SOURCE_COLUMNS = ", ".join(source for _, source in _MIRRORED_COLUMNS) -# Runs after the triggers are installed, so a ROM written concurrently with the -# migration cannot fall between the two steps. Rows a trigger already wrote are -# left alone: they were built from the write itself, so they are never staler -# than this statement's snapshot. -_BACKFILL_SELECT = ( +# Backfilled into the empty table before the triggers exist, so no row can +# conflict and no upsert guard is needed. +_BACKFILL_SQL = ( f"INSERT INTO roms_facets (rom_id, {_TARGET_COLUMNS})\n" # nosec B608 f"SELECT id, {_SOURCE_COLUMNS} FROM roms" ) -_MYSQL_BACKFILL_SQL = f"{_BACKFILL_SELECT}\nON DUPLICATE KEY UPDATE rom_id = rom_id" -_POSTGRES_BACKFILL_SQL = f"{_BACKFILL_SELECT}\nON CONFLICT (rom_id) DO NOTHING" _MYSQL_UPSERT_BODY = ( f"INSERT INTO roms_facets (rom_id, {_TARGET_COLUMNS})\n" # nosec B608 @@ -127,17 +123,17 @@ def upgrade() -> None: ) op.create_index("idx_roms_facets_platform_id", "roms_facets", ["platform_id"]) + op.execute(_BACKFILL_SQL) + if is_postgresql(op.get_bind()): op.execute(_POSTGRES_SYNC_FN) op.execute(_POSTGRES_TRIGGER) - op.execute(_POSTGRES_BACKFILL_SQL) else: for name, timing in _MYSQL_TRIGGERS.items(): op.execute( f"CREATE TRIGGER {name} {timing} ON roms\n" f"FOR EACH ROW\n{_MYSQL_UPSERT_BODY}" ) - op.execute(_MYSQL_BACKFILL_SQL) def downgrade() -> None: