{"version":3,"file":"effect-mysql.cjs","names":["Effect","sql","GET_VERSION_FOR","MIGRATIONS_TABLE_VERSIONS"],"sources":["../../src/up-migrations/effect-mysql.ts"],"sourcesContent":["import { Effect } from 'effect';\nimport type { QueryEffectHKTBase } from '~/effect-core/query-effect.ts';\nimport type { MigrationMeta } from '~/migrator.ts';\nimport type { MySqlEffectSession } from '~/mysql-core/effect/session.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<TEffectHKT extends QueryEffectHKTBase>(\n\t\tmigrationsTable: string,\n\t\tsession: MySqlEffectSession<TEffectHKT>,\n\t\tlocalMigrations: MigrationMeta[],\n\t) => Effect.Effect<void, TEffectHKT['error'], TEffectHKT['context']>\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: (migrationsTable, session, localMigrations) => {\n\t\treturn Effect.gen(function*() {\n\t\t\tconst table = sql`${sql.identifier(migrationsTable)}`;\n\n\t\t\t// 1. Read all existing DB migrations\n\t\t\t// Sort them by ids asc (order how they were applied)\n\t\t\tconst dbRows = yield* session.objects<{ id: number; hash: string; created_at: string }>(\n\t\t\t\tsql`SELECT id, hash, created_at FROM ${table} ORDER BY id ASC`,\n\t\t\t);\n\n\t\t\t// 2. Sort ASC by millis and if the same - sort by name\n\t\t\tlocalMigrations.sort((a, b) =>\n\t\t\t\ta.folderMillis !== b.folderMillis ? a.folderMillis - b.folderMillis : (a.name ?? '').localeCompare(b.name ?? '')\n\t\t\t);\n\n\t\t\tconst byMillis = new Map<number, MigrationMeta[]>();\n\t\t\tconst byHash = new Map<string, MigrationMeta>();\n\t\t\tfor (const lm of localMigrations) {\n\t\t\t\tif (!byMillis.has(lm.folderMillis)) {\n\t\t\t\t\tbyMillis.set(lm.folderMillis, []);\n\t\t\t\t}\n\t\t\t\tbyMillis.get(lm.folderMillis)!.push(lm);\n\t\t\t\tbyHash.set(lm.hash, lm);\n\t\t\t}\n\n\t\t\t// \t3. Match each DB row to a local migration\n\t\t\t// \tPriority: millis -> hash\n\t\t\tconst toApply: { id: number; name: string }[] = [];\n\t\t\tlet unmatchedIds: number[] = [];\n\n\t\t\tfor (const dbRow of dbRows) {\n\t\t\t\tconst stringified = String(dbRow.created_at);\n\t\t\t\tconst millis = Number(stringified.substring(0, stringified.length - 3) + '000');\n\t\t\t\tconst candidates = byMillis.get(millis);\n\n\t\t\t\tlet matched: MigrationMeta | undefined;\n\n\t\t\t\tif (candidates && candidates.length === 1) {\n\t\t\t\t\tmatched = candidates[0];\n\t\t\t\t} else if (candidates && candidates.length > 1) {\n\t\t\t\t\tmatched = candidates.find((c) => c.hash === dbRow.hash);\n\t\t\t\t} else {\n\t\t\t\t\tmatched = byHash.get(dbRow.hash);\n\t\t\t\t}\n\n\t\t\t\tif (matched) toApply.push({ id: dbRow.id, name: matched.name });\n\t\t\t\telse unmatchedIds.push(dbRow.id);\n\t\t\t}\n\n\t\t\t// 4. Check for unmatched\n\t\t\t// Our assumption on this migration flow is that all DB entries should be matched to a local migration\n\t\t\t// (if same seconds - fallback to hash, if hash fails - corner case)\n\t\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\t// which can lead to inconsistencies and potential issues when running future migrations\n\t\t\tif (unmatchedIds.length > 0) {\n\t\t\t\tthrow Error(\n\t\t\t\t\t`While upgrading your database migrations table we found ${unmatchedIds.length} migrations (ids: ${\n\t\t\t\t\t\tunmatchedIds.join(', ')\n\t\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\t);\n\t\t\t}\n\n\t\t\t// 5. Create extra column and backfill names for matched migrations\n\t\t\tyield* session.execute(sql`ALTER TABLE ${table} ADD ${sql.identifier('name')} text`);\n\t\t\tyield* session.execute(\n\t\t\t\tsql`ALTER TABLE ${table} ADD ${sql.identifier('applied_at')} TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,\n\t\t\t);\n\n\t\t\tfor (const backfillEntry of toApply) {\n\t\t\t\tyield* session.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 const upgradeIfNeeded: <TEffectHKT extends QueryEffectHKTBase>(\n\tmigrationsTable: string,\n\tsession: MySqlEffectSession<TEffectHKT>,\n\tlocalMigrations: MigrationMeta[],\n) => Effect.Effect<UpgradeResult, TEffectHKT['error'], TEffectHKT['context']> = Effect.fn('upgradeIfNeeded')(\n\tfunction*<TEffectHKT extends QueryEffectHKTBase>(\n\t\tmigrationsTable: string,\n\t\tsession: MySqlEffectSession<TEffectHKT>,\n\t\tlocalMigrations: MigrationMeta[],\n\t) {\n\t\t// Check if the table exists at all\n\t\tconst result = yield* session.objects<{ '1': 1 }>(\n\t\t\tsql`SELECT 1 FROM information_schema.tables\n\t\t\t\tWHERE table_name = ${migrationsTable}\n\t\t\t\tAND table_schema = DATABASE()`,\n\t\t);\n\n\t\tif (result.length === 0) {\n\t\t\treturn { newDb: true };\n\t\t}\n\n\t\t// Table exists, check table shape\n\t\tconst rows = yield* session.objects<{ column_name: string }>(\n\t\t\tsql`SELECT column_name as \\`column_name\\`\n\t\t\tFROM information_schema.columns\n\t\t\tWHERE table_name = ${migrationsTable}\n\t\t\tAND table_schema = DATABASE()\n\t\t\tORDER BY ordinal_position`,\n\t\t);\n\n\t\tconst version = GET_VERSION_FOR.mysql(rows.map((r) => r.column_name));\n\n\t\tfor (let v = version; v < MIGRATIONS_TABLE_VERSIONS.mysql; v++) {\n\t\t\tconst upgradeFn = upgradeFunctions[v];\n\t\t\tif (!upgradeFn) {\n\t\t\t\tthrow new Error(`No upgrade path from migration table version ${v} to ${v + 1}`);\n\t\t\t}\n\t\t\tyield* upgradeFn(migrationsTable, session, localMigrations);\n\t\t}\n\n\t\treturn { newDb: false };\n\t},\n);\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,mBAOF,EAUH,IAAI,iBAAiB,SAAS,oBAAoB;AACjD,QAAOA,cAAO,IAAI,aAAY;EAC7B,MAAM,QAAQ,gBAAG,GAAGC,iBAAI,WAAW,gBAAgB;EAInD,MAAM,SAAS,OAAO,QAAQ,QAC7B,gBAAG,oCAAoC,MAAM,kBAC7C;AAGD,kBAAgB,MAAM,GAAG,MACxB,EAAE,iBAAiB,EAAE,eAAe,EAAE,eAAe,EAAE,gBAAgB,EAAE,QAAQ,IAAI,cAAc,EAAE,QAAQ,GAAG,CAChH;EAED,MAAM,2BAAW,IAAI,KAA8B;EACnD,MAAM,yBAAS,IAAI,KAA4B;AAC/C,OAAK,MAAM,MAAM,iBAAiB;AACjC,OAAI,CAAC,SAAS,IAAI,GAAG,aAAa,CACjC,UAAS,IAAI,GAAG,cAAc,EAAE,CAAC;AAElC,YAAS,IAAI,GAAG,aAAa,CAAE,KAAK,GAAG;AACvC,UAAO,IAAI,GAAG,MAAM,GAAG;;EAKxB,MAAM,UAA0C,EAAE;EAClD,IAAI,eAAyB,EAAE;AAE/B,OAAK,MAAM,SAAS,QAAQ;GAC3B,MAAM,cAAc,OAAO,MAAM,WAAW;GAC5C,MAAM,SAAS,OAAO,YAAY,UAA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