|
| 1 | +import { getErrorMessage } from '@sim/utils/errors' |
| 2 | +import { generateNKeysBetween } from '@sim/utils/fractional-indexing' |
| 3 | +import type { ScriptMigration } from './types' |
| 4 | + |
| 5 | +/** |
| 6 | + * Rows written per `UPDATE … FROM unnest(...)` statement. The two unnest |
| 7 | + * arrays are single bind parameters, so chunking only bounds per-statement |
| 8 | + * work and wire-message size, not parameter count. Chunks share the one |
| 9 | + * per-table transaction, so the table is still keyed atomically. |
| 10 | + */ |
| 11 | +const WRITE_CHUNK_SIZE = 5000 |
| 12 | + |
| 13 | +/** |
| 14 | + * Backfills the `order_key` column on `user_table_rows`. |
| 15 | + * |
| 16 | + * Row ordering moved from the contiguous integer `position` to a fractional |
| 17 | + * string `order_key` (O(1) insert/delete — no reshift/recompact). Each existing |
| 18 | + * row gets a key derived from its current `position` order, so the fractional |
| 19 | + * ordering matches today's once `TABLES_FRACTIONAL_ORDERING` is on. |
| 20 | + * |
| 21 | + * Per-table-atomic: each table is keyed inside one transaction holding the same |
| 22 | + * per-table advisory lock the app uses for inserts, so a concurrent insert |
| 23 | + * can't interleave. Idempotent: tables already fully keyed are skipped; a table |
| 24 | + * with any NULL key is fully re-keyed from `position` order (deterministic, so |
| 25 | + * a re-run after a partial failure is safe). Per-table failures are isolated — |
| 26 | + * remaining tables still run, then the migration throws so it stays pending and |
| 27 | + * retries (only still-unkeyed tables) on the next upgrade. |
| 28 | + */ |
| 29 | +export const backfillTableOrderKeys: ScriptMigration = { |
| 30 | + name: '0001_backfill_table_order_keys', |
| 31 | + async up(sql) { |
| 32 | + const pending = await sql<{ table_id: string }[]>` |
| 33 | + SELECT DISTINCT table_id FROM user_table_rows WHERE order_key IS NULL |
| 34 | + ` |
| 35 | + console.log(`order_key backfill — ${pending.length} table(s) with NULL order_key`) |
| 36 | + |
| 37 | + const stats = { tablesKeyed: 0, rowsKeyed: 0, failed: 0 } |
| 38 | + |
| 39 | + for (const { table_id: tableId } of pending) { |
| 40 | + try { |
| 41 | + const keyed = await sql.begin(async (tx) => { |
| 42 | + await tx` |
| 43 | + SELECT pg_advisory_xact_lock(hashtextextended(${`user_table_rows_pos:${tableId}`}, 0)) |
| 44 | + ` |
| 45 | + const rows = await tx<{ id: string }[]>` |
| 46 | + SELECT id FROM user_table_rows |
| 47 | + WHERE table_id = ${tableId} |
| 48 | + ORDER BY position ASC, id ASC |
| 49 | + ` |
| 50 | + if (rows.length === 0) return 0 |
| 51 | + const keys = generateNKeysBetween(null, null, rows.length) |
| 52 | + |
| 53 | + for (let start = 0; start < rows.length; start += WRITE_CHUNK_SIZE) { |
| 54 | + const chunk = rows.slice(start, start + WRITE_CHUNK_SIZE) |
| 55 | + const ids = chunk.map((r) => r.id) |
| 56 | + const chunkKeys = keys.slice(start, start + chunk.length) |
| 57 | + await tx` |
| 58 | + UPDATE user_table_rows AS t |
| 59 | + SET order_key = v.order_key |
| 60 | + FROM ( |
| 61 | + SELECT unnest(${ids}::text[]) AS id, unnest(${chunkKeys}::text[]) AS order_key |
| 62 | + ) AS v |
| 63 | + WHERE t.id = v.id AND t.table_id = ${tableId} |
| 64 | + ` |
| 65 | + } |
| 66 | + return rows.length |
| 67 | + }) |
| 68 | + stats.tablesKeyed += 1 |
| 69 | + stats.rowsKeyed += keyed |
| 70 | + console.log(` ${tableId}: keyed ${keyed} rows`) |
| 71 | + } catch (error) { |
| 72 | + stats.failed += 1 |
| 73 | + console.error(` ${tableId}: FAILED — ${getErrorMessage(error)}`) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + console.log( |
| 78 | + `order_key backfill done — tables keyed: ${stats.tablesKeyed}, ` + |
| 79 | + `rows keyed: ${stats.rowsKeyed}, failed: ${stats.failed}` |
| 80 | + ) |
| 81 | + if (stats.failed > 0) { |
| 82 | + throw new Error(`order_key backfill failed for ${stats.failed} table(s); will retry next run`) |
| 83 | + } |
| 84 | + }, |
| 85 | +} |
0 commit comments