{"version":3,"file":"cockroach.cjs","names":["sql","GET_VERSION_FOR","MIGRATIONS_TABLE_VERSIONS"],"sources":["../../src/up-migrations/cockroach.ts"],"sourcesContent":["import type { CockroachSession } from '~/cockroach-core/session.ts';\nimport type { MigrationMeta } from '~/migrator.ts';\nimport { sql } from '~/sql/sql.ts';\nimport { GET_VERSION_FOR, MIGRATIONS_TABLE_VERSIONS, type UpgradeResult } from './utils.ts';\n\n/**\n * Map of upgrade functions. Each key is the version being upgraded FROM,\n * and the function upgrades the table to the next version.\n */\nconst upgradeFunctions: Record<\n\tnumber,\n\t(\n\t\tmigrationsSchema: string,\n\t\tmigrationsTable: string,\n\t\tsession: CockroachSession,\n\t\tlocalMigrations: MigrationMeta[],\n\t) => Promise<void>\n> = {\n\t/**\n\t * Upgrade from version 0 to version 1:\n\t * 1. Read all existing DB migrations\n\t * 2. Sort localMigrations ASC by millis and if the same - sort by name\n\t * 3. Match each DB row to a local migration\n\t * If multiple migrations share the same second, use hash matching as a tiebreaker\n\t * Not implemented for now -> If hash matching fails, fall back to serial id ordering\n\t * 5. Create extra column and backfill names for matched migrations\n\t */\n\t0: async (migrationsSchema, migrationsTable, session, localMigrations) => {\n\t\tconst table = sql`${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)}`;\n\n\t\t// 1. Read all existing DB migrations\n\t\t// Sort them by ids asc (order how they were applied)\n\t\tconst dbRows = await session.objects<{ id: number; hash: string; created_at: string }>(\n\t\t\tsql`SELECT id, hash, created_at FROM ${table} ORDER BY id ASC`,\n\t\t);\n\n\t\t// 2. Sort ASC by millis and if the same - sort by name\n\t\tlocalMigrations.sort((a, b) =>\n\t\t\ta.folderMillis !== b.folderMillis ? a.folderMillis - b.folderMillis : (a.name ?? '').localeCompare(b.name ?? '')\n\t\t);\n\n\t\tconst byMillis = new Map<number, MigrationMeta[]>();\n\t\tconst byHash = new Map<string, MigrationMeta>();\n\t\tfor (const lm of localMigrations) {\n\t\t\tif (!byMillis.has(lm.folderMillis)) {\n\t\t\t\tbyMillis.set(lm.folderMillis, []);\n\t\t\t}\n\t\t\tbyMillis.get(lm.folderMillis)!.push(lm);\n\t\t\tbyHash.set(lm.hash, lm);\n\t\t}\n\n\t\t// \t3. Match each DB row to a local migration\n\t\t// \tPriority: millis -> hash\n\t\tconst toApply: { id: number; name: string }[] = [];\n\t\tlet unmatchedIds: number[] = [];\n\n\t\tfor (const dbRow of dbRows) {\n\t\t\tconst stringified = String(dbRow.created_at);\n\t\t\tconst millis = Number(stringified.substring(0, stringified.length - 3) + '000');\n\t\t\tconst candidates = byMillis.get(millis);\n\n\t\t\tlet matched: MigrationMeta | undefined;\n\n\t\t\tif (candidates && candidates.length === 1) {\n\t\t\t\tmatched = candidates[0];\n\t\t\t} else if (candidates && candidates.length > 1) {\n\t\t\t\tmatched = candidates.find((c) => c.hash === dbRow.hash);\n\t\t\t} else {\n\t\t\t\tmatched = byHash.get(dbRow.hash);\n\t\t\t}\n\n\t\t\tif (matched) toApply.push({ id: dbRow.id, name: matched.name });\n\t\t\telse unmatchedIds.push(dbRow.id);\n\t\t}\n\n\t\t// 4. Check for unmatched\n\t\t// Our assumption on this migration flow is that all DB entries should be matched to a local migration\n\t\t// (if same seconds - fallback to hash, if hash fails - corner case)\n\t\t// If there are unmatched entries, it means that the local environment is missing migrations that have been applied to the DB,\n\t\t// which can lead to inconsistencies and potential issues when running future migrations\n\t\tif (unmatchedIds.length > 0) {\n\t\t\tthrow Error(\n\t\t\t\t`While upgrading your database migrations table we found ${unmatchedIds.length} migrations (ids: ${\n\t\t\t\t\tunmatchedIds.join(', ')\n\t\t\t\t}) in the database that do not match any local migration. This means that some migrations were applied to the database but are missing from the local environment`,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Create extra column and backfill names for matched migrations\n\t\tawait session.transaction(async (tx) => {\n\t\t\t// 1. Add new columns\n\t\t\tawait tx.execute(sql`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${sql.identifier('name')} text`);\n\t\t\tawait tx.execute(\n\t\t\t\tsql`ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${\n\t\t\t\t\tsql.identifier('applied_at')\n\t\t\t\t} timestamp with time zone DEFAULT now()`,\n\t\t\t);\n\n\t\t\tfor (const backfillEntry of toApply) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\tsql`UPDATE ${table} SET ${sql.identifier('name')} = ${backfillEntry.name}, ${\n\t\t\t\t\t\tsql.identifier('applied_at')\n\t\t\t\t\t} = NULL WHERE ${sql.identifier('id')} = ${backfillEntry.id}`,\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t},\n};\n\n/**\n * Detects the current version of the migrations table schema and upgrades it if needed.\n *\n * Version 0: Original schema (id, hash, created_at)\n * Version 1: Extended schema (id, hash, created_at, name, applied_at)\n */\nexport async function upgradeIfNeeded(\n\tmigrationsSchema: string,\n\tmigrationsTable: string,\n\tsession: CockroachSession,\n\tlocalMigrations: MigrationMeta[],\n): Promise<UpgradeResult> {\n\t// Check if the table exists at all\n\tconst tableExists = await session.objects<{ 1: '1' }>(\n\t\tsql`SELECT 1 FROM information_schema.tables\n\t\t\tWHERE table_schema = ${migrationsSchema}\n\t\t\tAND table_name = ${migrationsTable}`,\n\t);\n\n\tif (tableExists.length === 0) {\n\t\treturn { newDb: true };\n\t}\n\n\t// Table exists, check table shape\n\tconst rows = await session.objects<{ schema: string; table_name: string; column_name: string; type: string }>(\n\t\tsql`SELECT\n            n.nspname AS \"schema\",\n            c.relname AS \"table_name\",\n            a.attname AS \"column_name\",\n            pg_catalog.format_type(a.atttypid, a.atttypmod) AS \"type\"\n        FROM\n            pg_catalog.pg_attribute a\n            JOIN pg_catalog.pg_class c ON c.oid = a.attrelid\n            JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n        WHERE\n            a.attnum > 0\n            AND NOT a.attisdropped\n            AND n.nspname = ${migrationsSchema}\n            AND c.relname = ${migrationsTable}\n        ORDER BY a.attnum;`,\n\t);\n\n\tlet version = GET_VERSION_FOR.cockroach(rows.map((r) => r.column_name));\n\n\tfor (let v = version; v < MIGRATIONS_TABLE_VERSIONS.cockroach; v++) {\n\t\tconst upgradeFn = upgradeFunctions[v];\n\t\tif (!upgradeFn) {\n\t\t\tthrow new Error(`No upgrade path from migration table version ${v} to ${v + 1}`);\n\t\t}\n\t\tawait upgradeFn(migrationsSchema, migrationsTable, session, localMigrations);\n\t}\n\n\treturn { newDb: false };\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,mBAQF,EAUH,GAAG,OAAO,kBAAkB,iBAAiB,SAAS,oBAAoB;CACzE,MAAM,QAAQ,gBAAG,GAAGA,iBAAI,WAAW,iBAAiB,CAAC,GAAGA,iBAAI,WAAW,gBAAgB;CAIvF,MAAM,SAAS,MAAM,QAAQ,QAC5B,gBAAG,oCAAoC,MAAM,kBAC7C;AAGD,iBAAgB,MAAM,GAAG,MACxB,EAAE,iBAAiB,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,IAAI,cAAc,EAAE,QAAQ,GAAG,CAChH;CAED,MAAM,2BAAW,IAAI,KAA8B;CACnD,MAAM,yBAAS,IAAI,KAA4B;AAC/C,MAAK,MAAM,MAAM,iBAAiB;AACjC,MAAI,CAAC,SAAS,IAAI,GAAG,aAAa,CACjC,UAAS,IAAI,GAAG,cAAc,EAAE,CAAC;AAElC,WAAS,IAAI,GAAG,aAAa,CAAE,KAAK,GAAG;AACvC,SAAO,IAAI,GAAG,MAAM,GAAG;;CAKxB,MAAM,UAA0C,EAAE;CAClD,IAAI,eAAyB,EAAE;AAE/B,MAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,cAAc,OAAO,MAAM,WAAW;EAC5C,MAAM,SAAS,OAAO,YAAY,UAAU,GAAG,YAAY,SAAS,EAAE,GAAG,MAAM;EAC/E,MAAM,aAAa,SAAS,IAAI,OAAO;EAEvC,IAAI;AAEJ,MAAI,cAAc,WAAW,WAAW,EACvC,WAAU,WAAW;WACX,cAAc,WAAW,SAAS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