@niscorp/strata 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/DESIGN.md +16 -7
- package/README.md +37 -7
- package/dist/check/index.cjs +7 -7
- package/dist/check/index.js +2 -2
- package/dist/{chunk-QIXZZZE6.cjs → chunk-564JCO6Q.cjs} +8 -8
- package/dist/{chunk-QIXZZZE6.cjs.map → chunk-564JCO6Q.cjs.map} +1 -1
- package/dist/{chunk-BW4CKKGE.cjs → chunk-7PBIGCLL.cjs} +2 -2
- package/dist/chunk-7PBIGCLL.cjs.map +1 -0
- package/dist/{chunk-PODP3F5N.js → chunk-DGS4XJQQ.js} +4 -4
- package/dist/{chunk-PODP3F5N.js.map → chunk-DGS4XJQQ.js.map} +1 -1
- package/dist/{chunk-D42CQI2X.js → chunk-FNMGVPSA.js} +4 -4
- package/dist/{chunk-D42CQI2X.js.map → chunk-FNMGVPSA.js.map} +1 -1
- package/dist/{chunk-IOS2DL6R.cjs → chunk-FSEUYRLN.cjs} +15 -15
- package/dist/{chunk-IOS2DL6R.cjs.map → chunk-FSEUYRLN.cjs.map} +1 -1
- package/dist/{chunk-HW6ON3LT.cjs → chunk-KYNER7UU.cjs} +18 -7
- package/dist/chunk-KYNER7UU.cjs.map +1 -0
- package/dist/{chunk-CI652R5O.js → chunk-PAMQMFBK.js} +15 -4
- package/dist/chunk-PAMQMFBK.js.map +1 -0
- package/dist/{chunk-LIWVOCKP.js → chunk-SH6BBA2X.js} +3 -3
- package/dist/{chunk-LIWVOCKP.js.map → chunk-SH6BBA2X.js.map} +1 -1
- package/dist/{chunk-VNF4KPVN.js → chunk-STNFHBNR.js} +2 -2
- package/dist/chunk-STNFHBNR.js.map +1 -0
- package/dist/{chunk-3DPZS52U.cjs → chunk-SYU7NKZR.cjs} +4 -4
- package/dist/{chunk-3DPZS52U.cjs.map → chunk-SYU7NKZR.cjs.map} +1 -1
- package/dist/index.cjs +21 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +11 -11
- package/dist/node/index.js +5 -5
- package/dist/{plan-mFmdh0qT.d.ts → plan-BMZJUCZ1.d.ts} +6 -3
- package/dist/{plan-CxuteSH1.d.cts → plan-Bq_Q2x5r.d.cts} +6 -3
- package/dist/postgres/index.cjs +36 -23
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.d.cts +7 -3
- package/dist/postgres/index.d.ts +7 -3
- package/dist/postgres/index.js +25 -12
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +7 -7
- package/dist/upgrade/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-BW4CKKGE.cjs.map +0 -1
- package/dist/chunk-CI652R5O.js.map +0 -1
- package/dist/chunk-HW6ON3LT.cjs.map +0 -1
- package/dist/chunk-VNF4KPVN.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/postgres/index.ts"],"names":["StrataError","planMigrations","prepare","refuseProblems"],"mappings":";;;;;;AAgCA,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACrD,EAAA,IAAI,CAAC,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG,MAAM,IAAIA,6BAAA,CAAY,kBAAA,EAAoB,CAAA,WAAA,EAAc,KAAK,CAAA,EAAA,EAAK,IAAI,CAAA,4BAAA,CAA8B,CAAA;AAC3H,EAAA,OAAO,IAAI,IAAI,CAAA,CAAA,CAAA;AACjB,CAAA;AAEA,IAAM,YAAA,GAAe,CAAC,OAAA,KAA8E;AAClG,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,KAAA,IAAS,iBAAiB,OAAO,CAAA;AAC7D,EAAA,MAAM,MAA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KAAA,EAAO;AACd,QAAA,IAAI,iBAAiBA,6BAAA,EAAa;AAChC,UAAA,MAAM,IAAIA,8BAAY,KAAA,CAAM,IAAA,EAAM,GAAG,KAAA,CAAM,KAAK,CAAA,EAAA,EAAK,KAAK,CAAA,GAAA,EAAM,KAAA,CAAM,QAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAE,IAAI,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAAA,QAChI;AACA,QAAA,MAAM,KAAA;AAAA,MACR;AACA,MAAA,MAAM,EAAA,CAAG,KAAA;AAAA,QACP,CAAA,OAAA,EAAU,KAAK,CAAA,KAAA,EAAQ,MAAM,iBAAiB,KAAK,CAAA,mBAAA,EAAsB,KAAK,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM,CAAA,EAAG,CAAC,CAAA,IAAA,EAAO,CAAA,GAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,OAAO,CAAC,CAAA,CAAA;AAAA,QAC7H,CAAC,KAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA,EAAG,IAAA,CAAK,UAAU,MAAA,CAAO,KAAK,GAAG,GAAG,KAAA,CAAM,IAAI,GAAA,CAAI,CAAC,MAAM,GAAA,CAAI,CAAC,CAAC,CAAC;AAAA,OACjG;AACA,MAAA,QAAA,IAAY,CAAA;AACZ,MAAA,KAAA,MAAW,GAAA,IAAO,OAAO,OAAA,EAAS,OAAA,CAAQ,GAAG,CAAA,GAAA,CAAK,OAAA,CAAQ,GAAG,CAAA,IAAK,CAAA,IAAK,CAAA;AAAA,IACzE;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,IAAA,CAAK,MAAA,EAAQ,UAAU,OAAA,EAAQ;AAAA,EACjD,CAAC,CAAA;AACH","file":"index.cjs","sourcesContent":["import { prepare, planMigrations, refuseProblems, type LedgerRow, type Plan, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// `query` and `transaction` are called on the object that has them, never taken\n// off it first: a driver's own object (a PGlite, a `pg` client) has them as\n// methods that reach for `this`.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n table?: string;\n schema?: string;\n};\n\nexport type MigrateGuard = (tx: { query: StrataQuery }) => Promise<readonly string[]>;\n\nexport type MigrateOptions = LedgerOptions & {\n mode?: 'apply' | 'verify';\n guard?: MigrateGuard;\n dryRun?: boolean;\n};\n\nexport type MigrateReport = {\n applied: readonly PreparedMigration[];\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options));\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n // A dry run leaves by throwing, which is what rolls a transaction back in\n // every pool. This is the throw, told apart by being this object.\n const dryRunEnd = new Error('strata: dry run');\n let dryRunReport: MigrateReport | undefined;\n\n const run = pool.transaction(async (tx) => {\n // The lock first: two processes creating the ledger at once would race in\n // the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified));\n refuseProblems(plan);\n if (options.mode === 'verify' && plan.pending.length > 0) {\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n }\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n\n const reasons = options.guard === undefined ? [] : await options.guard(tx);\n if (reasons.length > 0) {\n throw new StrataError('DOES_NOT_FIT', 'What this run leaves does not fit what has to run on it. Nothing from this run was applied.', reasons);\n }\n if (options.dryRun === true) {\n dryRunReport = { applied, plan };\n throw dryRunEnd;\n }\n return { applied, plan };\n });\n\n return run.catch((error: unknown) => {\n if (error === dryRunEnd && dryRunReport !== undefined) return dryRunReport;\n throw error;\n });\n};\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n column: string;\n stamp: string;\n kind: string;\n key: readonly string[];\n};\n\nexport type StoreReport = {\n total: number;\n upgraded: number;\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/index.ts"],"names":["StrataError","planMigrations","prepare","refuseProblems"],"mappings":";;;;;;AA8BA,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,oBAAA,GAAuB,IAAA;AAO7B,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACr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,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,iBAAiBA,6BAAA,EAAa;AAChC,UAAA,MAAM,IAAIA,8BAAY,KAAA,CAAM,IAAA,EAAM,GAAG,KAAA,CAAM,KAAK,CAAA,EAAA,EAAK,KAAK,CAAA,GAAA,EAAM,KAAA,CAAM,QAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAE,IAAI,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAAA,QAChI;AACA,QAAA,MAAM,KAAA;AAAA,MACR;AACA,MAAA,MAAM,EAAA,CAAG,KAAA;AAAA,QACP,CAAA,OAAA,EAAU,KAAK,CAAA,KAAA,EAAQ,MAAM,iBAAiB,KAAK,CAAA,mBAAA,EAAsB,KAAK,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM,CAAA,EAAG,CAAC,CAAA,IAAA,EAAO,CAAA,GAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,OAAO,CAAC,CAAA,CAAA;AAAA,QAC7H,CAAC,KAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA,EAAG,IAAA,CAAK,UAAU,MAAA,CAAO,KAAK,GAAG,GAAG,KAAA,CAAM,IAAI,GAAA,CAAI,CAAC,MAAM,GAAA,CAAI,CAAC,CAAC,CAAC;AAAA,OACjG;AACA,MAAA,QAAA,IAAY,CAAA;AACZ,MAAA,KAAA,MAAW,GAAA,IAAO,OAAO,OAAA,EAAS,OAAA,CAAQ,GAAG,CAAA,GAAA,CAAK,OAAA,CAAQ,GAAG,CAAA,IAAK,CAAA,IAAK,CAAA;AAAA,IACzE;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,IAAA,CAAK,MAAA,EAAQ,UAAU,OAAA,EAAQ;AAAA,EACjD,CAAC,CAAA;AACH","file":"index.cjs","sourcesContent":["import { prepare, planMigrations, refuseProblems, type LedgerRow, type Plan, type PlanOptions, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// `query` and `transaction` are called on the object that has them, never taken\n// off it first: a driver's own object (a PGlite, a `pg` client) has them as\n// methods that reach for `this`.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n table?: string;\n schema?: string;\n};\n\nexport type MigrateGuard = (tx: { query: StrataQuery }, run: { applied: readonly PreparedMigration[] }) => Promise<readonly string[]>;\n\nexport type MigrateOptions = LedgerOptions &\n PlanOptions & {\n mode?: 'apply' | 'verify';\n guard?: MigrateGuard;\n dryRun?: boolean;\n lockTimeoutMs?: number;\n statementTimeoutMs?: number;\n };\n\nconst LOCK_TIMEOUT_MS = 10_000;\nconst STATEMENT_TIMEOUT_MS = 3_600_000;\n\nexport type MigrateReport = {\n applied: readonly PreparedMigration[];\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions & PlanOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options), options);\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nconst refusePending = (plan: Plan): void => {\n if (plan.pending.length === 0) return;\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n // Read before anything is locked or created: on a database that is up to\n // date a run is a read, which a role without DDL rights can make.\n const read = planMigrations(prepared, await readLedger(pool, options), options);\n refuseProblems(read);\n if (options.mode === 'verify') {\n refusePending(read);\n return { applied: [], plan: read };\n }\n if (read.pending.length === 0 && options.guard === undefined && options.dryRun !== true) return { applied: [], plan: read };\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n // A dry run leaves by throwing, which is what rolls a transaction back in\n // every pool. This is the throw, told apart by being this object.\n const dryRunEnd = new Error('strata: dry run');\n let dryRunReport: MigrateReport | undefined;\n\n const run = pool.transaction(async (tx) => {\n // The wait for another run is bounded by the statement timeout alone: a\n // lock timeout, the pool's or the run's own, would cut it short.\n await tx.query(\"SELECT set_config('statement_timeout', $1, true)\", [`${options.statementTimeoutMs ?? STATEMENT_TIMEOUT_MS}ms`]);\n await tx.query(\"SELECT set_config('lock_timeout', '0', true)\");\n // The lock before the ledger's DDL: two processes creating the ledger at\n // once would race in the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n await tx.query(\"SELECT set_config('lock_timeout', $1, true)\", [`${options.lockTimeoutMs ?? LOCK_TIMEOUT_MS}ms`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified), options);\n refuseProblems(plan);\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n\n const reasons = options.guard === undefined ? [] : await options.guard(tx, { applied });\n if (reasons.length > 0) {\n throw new StrataError('DOES_NOT_FIT', 'What this run leaves does not fit what has to run on it. Nothing from this run was applied.', reasons);\n }\n if (options.dryRun === true) {\n dryRunReport = { applied, plan };\n throw dryRunEnd;\n }\n return { applied, plan };\n });\n\n return run.catch((error: unknown) => {\n if (error === dryRunEnd && dryRunReport !== undefined) return dryRunReport;\n throw error;\n });\n};\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n column: string;\n stamp: string;\n kind: string;\n key: readonly string[];\n};\n\nexport type StoreReport = {\n total: number;\n upgraded: number;\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { b as PreparedMigration, a as PlanOptions, P as Plan, L as LedgerRow } from '../plan-Bq_Q2x5r.cjs';
|
|
2
2
|
import { a as Sequence, n as Upgrader } from '../documents-BjlM94Ea.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
@@ -17,11 +17,15 @@ type LedgerOptions = {
|
|
|
17
17
|
};
|
|
18
18
|
type MigrateGuard = (tx: {
|
|
19
19
|
query: StrataQuery;
|
|
20
|
+
}, run: {
|
|
21
|
+
applied: readonly PreparedMigration[];
|
|
20
22
|
}) => Promise<readonly string[]>;
|
|
21
|
-
type MigrateOptions = LedgerOptions & {
|
|
23
|
+
type MigrateOptions = LedgerOptions & PlanOptions & {
|
|
22
24
|
mode?: 'apply' | 'verify';
|
|
23
25
|
guard?: MigrateGuard;
|
|
24
26
|
dryRun?: boolean;
|
|
27
|
+
lockTimeoutMs?: number;
|
|
28
|
+
statementTimeoutMs?: number;
|
|
25
29
|
};
|
|
26
30
|
type MigrateReport = {
|
|
27
31
|
applied: readonly PreparedMigration[];
|
|
@@ -29,7 +33,7 @@ type MigrateReport = {
|
|
|
29
33
|
};
|
|
30
34
|
declare const ledgerDdl: (options?: LedgerOptions) => string;
|
|
31
35
|
declare const readLedger: (pool: StrataPool, options?: LedgerOptions) => Promise<LedgerRow[]>;
|
|
32
|
-
declare const status: (pool: StrataPool, sequences: readonly Sequence[], options?: LedgerOptions) => Promise<Plan>;
|
|
36
|
+
declare const status: (pool: StrataPool, sequences: readonly Sequence[], options?: LedgerOptions & PlanOptions) => Promise<Plan>;
|
|
33
37
|
declare const migrate: (pool: StrataPool, sequences: readonly Sequence[], options?: MigrateOptions) => Promise<MigrateReport>;
|
|
34
38
|
type DocumentStore = {
|
|
35
39
|
table: string;
|
package/dist/postgres/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { b as PreparedMigration, a as PlanOptions, P as Plan, L as LedgerRow } from '../plan-BMZJUCZ1.js';
|
|
2
2
|
import { a as Sequence, n as Upgrader } from '../documents-BjlM94Ea.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
|
|
@@ -17,11 +17,15 @@ type LedgerOptions = {
|
|
|
17
17
|
};
|
|
18
18
|
type MigrateGuard = (tx: {
|
|
19
19
|
query: StrataQuery;
|
|
20
|
+
}, run: {
|
|
21
|
+
applied: readonly PreparedMigration[];
|
|
20
22
|
}) => Promise<readonly string[]>;
|
|
21
|
-
type MigrateOptions = LedgerOptions & {
|
|
23
|
+
type MigrateOptions = LedgerOptions & PlanOptions & {
|
|
22
24
|
mode?: 'apply' | 'verify';
|
|
23
25
|
guard?: MigrateGuard;
|
|
24
26
|
dryRun?: boolean;
|
|
27
|
+
lockTimeoutMs?: number;
|
|
28
|
+
statementTimeoutMs?: number;
|
|
25
29
|
};
|
|
26
30
|
type MigrateReport = {
|
|
27
31
|
applied: readonly PreparedMigration[];
|
|
@@ -29,7 +33,7 @@ type MigrateReport = {
|
|
|
29
33
|
};
|
|
30
34
|
declare const ledgerDdl: (options?: LedgerOptions) => string;
|
|
31
35
|
declare const readLedger: (pool: StrataPool, options?: LedgerOptions) => Promise<LedgerRow[]>;
|
|
32
|
-
declare const status: (pool: StrataPool, sequences: readonly Sequence[], options?: LedgerOptions) => Promise<Plan>;
|
|
36
|
+
declare const status: (pool: StrataPool, sequences: readonly Sequence[], options?: LedgerOptions & PlanOptions) => Promise<Plan>;
|
|
33
37
|
declare const migrate: (pool: StrataPool, sequences: readonly Sequence[], options?: MigrateOptions) => Promise<MigrateReport>;
|
|
34
38
|
type DocumentStore = {
|
|
35
39
|
table: string;
|
package/dist/postgres/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { planMigrations, prepare, refuseProblems } from '../chunk-
|
|
2
|
-
import { StrataError } from '../chunk-
|
|
1
|
+
import { planMigrations, prepare, refuseProblems } from '../chunk-PAMQMFBK.js';
|
|
2
|
+
import { StrataError } from '../chunk-STNFHBNR.js';
|
|
3
3
|
|
|
4
4
|
// src/postgres/index.ts
|
|
5
|
+
var LOCK_TIMEOUT_MS = 1e4;
|
|
6
|
+
var STATEMENT_TIMEOUT_MS = 36e5;
|
|
5
7
|
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
8
|
var quote = (name, label) => {
|
|
7
9
|
if (!IDENT.test(name)) throw new StrataError("INVALID_SEQUENCE", `The ledger ${label} "${name}" is not a plain identifier.`);
|
|
@@ -40,7 +42,7 @@ var readLedger = async (pool, options = {}) => {
|
|
|
40
42
|
if (rows[0]?.["present"] !== true) return [];
|
|
41
43
|
return readRows(pool, qualified);
|
|
42
44
|
};
|
|
43
|
-
var status = async (pool, sequences, options = {}) => planMigrations(await prepare(sequences), await readLedger(pool, options));
|
|
45
|
+
var status = async (pool, sequences, options = {}) => planMigrations(await prepare(sequences), await readLedger(pool, options), options);
|
|
44
46
|
var refuseGrammars = (prepared) => {
|
|
45
47
|
const grammars = prepared.filter((s) => s.grammar);
|
|
46
48
|
if (grammars.length > 0) {
|
|
@@ -51,9 +53,24 @@ var refuseGrammars = (prepared) => {
|
|
|
51
53
|
);
|
|
52
54
|
}
|
|
53
55
|
};
|
|
56
|
+
var refusePending = (plan) => {
|
|
57
|
+
if (plan.pending.length === 0) return;
|
|
58
|
+
throw new StrataError(
|
|
59
|
+
"PENDING",
|
|
60
|
+
`${plan.pending.length} migration${plan.pending.length === 1 ? " is" : "s are"} not applied, and this boot only verifies. Run the migrations first.`,
|
|
61
|
+
plan.pending.map((m) => `${m.ref} ${m.description}`)
|
|
62
|
+
);
|
|
63
|
+
};
|
|
54
64
|
var migrate = async (pool, sequences, options = {}) => {
|
|
55
65
|
const prepared = await prepare(sequences);
|
|
56
66
|
refuseGrammars(prepared);
|
|
67
|
+
const read = planMigrations(prepared, await readLedger(pool, options), options);
|
|
68
|
+
refuseProblems(read);
|
|
69
|
+
if (options.mode === "verify") {
|
|
70
|
+
refusePending(read);
|
|
71
|
+
return { applied: [], plan: read };
|
|
72
|
+
}
|
|
73
|
+
if (read.pending.length === 0 && options.guard === void 0 && options.dryRun !== true) return { applied: [], plan: read };
|
|
57
74
|
if (pool.transaction === void 0) {
|
|
58
75
|
throw new StrataError(
|
|
59
76
|
"NO_TRANSACTION",
|
|
@@ -64,18 +81,14 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
64
81
|
const dryRunEnd = new Error("strata: dry run");
|
|
65
82
|
let dryRunReport;
|
|
66
83
|
const run = pool.transaction(async (tx) => {
|
|
84
|
+
await tx.query("SELECT set_config('statement_timeout', $1, true)", [`${options.statementTimeoutMs ?? STATEMENT_TIMEOUT_MS}ms`]);
|
|
85
|
+
await tx.query("SELECT set_config('lock_timeout', '0', true)");
|
|
67
86
|
await tx.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`strata:${qualified}`]);
|
|
87
|
+
await tx.query("SELECT set_config('lock_timeout', $1, true)", [`${options.lockTimeoutMs ?? LOCK_TIMEOUT_MS}ms`]);
|
|
68
88
|
if (schema !== void 0) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
|
|
69
89
|
await tx.query(ledgerDdl(options));
|
|
70
|
-
const plan = planMigrations(prepared, await readRows(tx, qualified));
|
|
90
|
+
const plan = planMigrations(prepared, await readRows(tx, qualified), options);
|
|
71
91
|
refuseProblems(plan);
|
|
72
|
-
if (options.mode === "verify" && plan.pending.length > 0) {
|
|
73
|
-
throw new StrataError(
|
|
74
|
-
"PENDING",
|
|
75
|
-
`${plan.pending.length} migration${plan.pending.length === 1 ? " is" : "s are"} not applied, and this boot only verifies. Run the migrations first.`,
|
|
76
|
-
plan.pending.map((m) => `${m.ref} ${m.description}`)
|
|
77
|
-
);
|
|
78
|
-
}
|
|
79
92
|
const applied = [];
|
|
80
93
|
for (const migration of plan.pending) {
|
|
81
94
|
for (const [index, step] of migration.steps.entries()) {
|
|
@@ -99,7 +112,7 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
99
112
|
]);
|
|
100
113
|
applied.push(migration);
|
|
101
114
|
}
|
|
102
|
-
const reasons = options.guard === void 0 ? [] : await options.guard(tx);
|
|
115
|
+
const reasons = options.guard === void 0 ? [] : await options.guard(tx, { applied });
|
|
103
116
|
if (reasons.length > 0) {
|
|
104
117
|
throw new StrataError("DOES_NOT_FIT", "What this run leaves does not fit what has to run on it. Nothing from this run was applied.", reasons);
|
|
105
118
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/postgres/index.ts"],"names":[],"mappings":";;;;AAgCA,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACrD,EAAA,IAAI,CAAC,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG,MAAM,IAAI,WAAA,CAAY,kBAAA,EAAoB,CAAA,WAAA,EAAc,KAAK,CAAA,EAAA,EAAK,IAAI,CAAA,4BAAA,CAA8B,CAAA;AAC3H,EAAA,OAAO,IAAI,IAAI,CAAA,CAAA,CAAA;AACjB,CAAA;AAEA,IAAM,YAAA,GAAe,CAAC,OAAA,KAA8E;AAClG,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,KAAA,IAAS,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AA,MACpF,SAAS,KAAA,EAAO;AACd,QAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,UAAA,MAAM,IAAI,YAAY,KAAA,CAAM,IAAA,EAAM,GAAG,KAAA,CAAM,KAAK,CAAA,EAAA,EAAK,KAAK,CAAA,GAAA,EAAM,KAAA,CAAM,QAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAE,IAAI,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAAA,QAChI;AACA,QAAA,MAAM,KAAA;AAAA,MACR;AACA,MAAA,MAAM,EAAA,CAAG,KAAA;AAAA,QACP,CAAA,OAAA,EAAU,KAAK,CAAA,KAAA,EAAQ,MAAM,iBAAiB,KAAK,CAAA,mBAAA,EAAsB,KAAK,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM,CAAA,EAAG,CAAC,CAAA,IAAA,EAAO,CAAA,GAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,OAAO,CAAC,CAAA,CAAA;AAAA,QAC7H,CAAC,KAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA,EAAG,IAAA,CAAK,UAAU,MAAA,CAAO,KAAK,GAAG,GAAG,KAAA,CAAM,IAAI,GAAA,CAAI,CAAC,MAAM,GAAA,CAAI,CAAC,CAAC,CAAC;AAAA,OACjG;AACA,MAAA,QAAA,IAAY,CAAA;AACZ,MAAA,KAAA,MAAW,GAAA,IAAO,OAAO,OAAA,EAAS,OAAA,CAAQ,GAAG,CAAA,GAAA,CAAK,OAAA,CAAQ,GAAG,CAAA,IAAK,CAAA,IAAK,CAAA;AAAA,IACzE;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,IAAA,CAAK,MAAA,EAAQ,UAAU,OAAA,EAAQ;AAAA,EACjD,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["import { prepare, planMigrations, refuseProblems, type LedgerRow, type Plan, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// `query` and `transaction` are called on the object that has them, never taken\n// off it first: a driver's own object (a PGlite, a `pg` client) has them as\n// methods that reach for `this`.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n table?: string;\n schema?: string;\n};\n\nexport type MigrateGuard = (tx: { query: StrataQuery }) => Promise<readonly string[]>;\n\nexport type MigrateOptions = LedgerOptions & {\n mode?: 'apply' | 'verify';\n guard?: MigrateGuard;\n dryRun?: boolean;\n};\n\nexport type MigrateReport = {\n applied: readonly PreparedMigration[];\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options));\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n // A dry run leaves by throwing, which is what rolls a transaction back in\n // every pool. This is the throw, told apart by being this object.\n const dryRunEnd = new Error('strata: dry run');\n let dryRunReport: MigrateReport | undefined;\n\n const run = pool.transaction(async (tx) => {\n // The lock first: two processes creating the ledger at once would race in\n // the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified));\n refuseProblems(plan);\n if (options.mode === 'verify' && plan.pending.length > 0) {\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n }\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n\n const reasons = options.guard === undefined ? [] : await options.guard(tx);\n if (reasons.length > 0) {\n throw new StrataError('DOES_NOT_FIT', 'What this run leaves does not fit what has to run on it. Nothing from this run was applied.', reasons);\n }\n if (options.dryRun === true) {\n dryRunReport = { applied, plan };\n throw dryRunEnd;\n }\n return { applied, plan };\n });\n\n return run.catch((error: unknown) => {\n if (error === dryRunEnd && dryRunReport !== undefined) return dryRunReport;\n throw error;\n });\n};\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n column: string;\n stamp: string;\n kind: string;\n key: readonly string[];\n};\n\nexport type StoreReport = {\n total: number;\n upgraded: number;\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/index.ts"],"names":[],"mappings":";;;;AA8BA,IAAM,eAAA,GAAkB,GAAA;AACxB,IAAM,oBAAA,GAAuB,IAAA;AAO7B,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACrD,EAAA,IAAI,CAAC,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;AAChC,UAAA,MAAM,IAAI,YAAY,KAAA,CAAM,IAAA,EAAM,GAAG,KAAA,CAAM,KAAK,CAAA,EAAA,EAAK,KAAK,CAAA,GAAA,EAAM,KAAA,CAAM,QAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAE,IAAI,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,CAAA;AAAA,QAChI;AACA,QAAA,MAAM,KAAA;AAAA,MACR;AACA,MAAA,MAAM,EAAA,CAAG,KAAA;AAAA,QACP,CAAA,OAAA,EAAU,KAAK,CAAA,KAAA,EAAQ,MAAM,iBAAiB,KAAK,CAAA,mBAAA,EAAsB,KAAK,GAAA,CAAI,CAAC,GAAG,CAAA,KAAM,CAAA,EAAG,CAAC,CAAA,IAAA,EAAO,CAAA,GAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,OAAO,CAAC,CAAA,CAAA;AAAA,QAC7H,CAAC,KAAK,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA,EAAG,IAAA,CAAK,UAAU,MAAA,CAAO,KAAK,GAAG,GAAG,KAAA,CAAM,IAAI,GAAA,CAAI,CAAC,MAAM,GAAA,CAAI,CAAC,CAAC,CAAC;AAAA,OACjG;AACA,MAAA,QAAA,IAAY,CAAA;AACZ,MAAA,KAAA,MAAW,GAAA,IAAO,OAAO,OAAA,EAAS,OAAA,CAAQ,GAAG,CAAA,GAAA,CAAK,OAAA,CAAQ,GAAG,CAAA,IAAK,CAAA,IAAK,CAAA;AAAA,IACzE;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,IAAA,CAAK,MAAA,EAAQ,UAAU,OAAA,EAAQ;AAAA,EACjD,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["import { prepare, planMigrations, refuseProblems, type LedgerRow, type Plan, type PlanOptions, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// `query` and `transaction` are called on the object that has them, never taken\n// off it first: a driver's own object (a PGlite, a `pg` client) has them as\n// methods that reach for `this`.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n table?: string;\n schema?: string;\n};\n\nexport type MigrateGuard = (tx: { query: StrataQuery }, run: { applied: readonly PreparedMigration[] }) => Promise<readonly string[]>;\n\nexport type MigrateOptions = LedgerOptions &\n PlanOptions & {\n mode?: 'apply' | 'verify';\n guard?: MigrateGuard;\n dryRun?: boolean;\n lockTimeoutMs?: number;\n statementTimeoutMs?: number;\n };\n\nconst LOCK_TIMEOUT_MS = 10_000;\nconst STATEMENT_TIMEOUT_MS = 3_600_000;\n\nexport type MigrateReport = {\n applied: readonly PreparedMigration[];\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions & PlanOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options), options);\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nconst refusePending = (plan: Plan): void => {\n if (plan.pending.length === 0) return;\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n // Read before anything is locked or created: on a database that is up to\n // date a run is a read, which a role without DDL rights can make.\n const read = planMigrations(prepared, await readLedger(pool, options), options);\n refuseProblems(read);\n if (options.mode === 'verify') {\n refusePending(read);\n return { applied: [], plan: read };\n }\n if (read.pending.length === 0 && options.guard === undefined && options.dryRun !== true) return { applied: [], plan: read };\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n // A dry run leaves by throwing, which is what rolls a transaction back in\n // every pool. This is the throw, told apart by being this object.\n const dryRunEnd = new Error('strata: dry run');\n let dryRunReport: MigrateReport | undefined;\n\n const run = pool.transaction(async (tx) => {\n // The wait for another run is bounded by the statement timeout alone: a\n // lock timeout, the pool's or the run's own, would cut it short.\n await tx.query(\"SELECT set_config('statement_timeout', $1, true)\", [`${options.statementTimeoutMs ?? STATEMENT_TIMEOUT_MS}ms`]);\n await tx.query(\"SELECT set_config('lock_timeout', '0', true)\");\n // The lock before the ledger's DDL: two processes creating the ledger at\n // once would race in the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n await tx.query(\"SELECT set_config('lock_timeout', $1, true)\", [`${options.lockTimeoutMs ?? LOCK_TIMEOUT_MS}ms`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified), options);\n refuseProblems(plan);\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n\n const reasons = options.guard === undefined ? [] : await options.guard(tx, { applied });\n if (reasons.length > 0) {\n throw new StrataError('DOES_NOT_FIT', 'What this run leaves does not fit what has to run on it. Nothing from this run was applied.', reasons);\n }\n if (options.dryRun === true) {\n dryRunReport = { applied, plan };\n throw dryRunEnd;\n }\n return { applied, plan };\n });\n\n return run.catch((error: unknown) => {\n if (error === dryRunEnd && dryRunReport !== undefined) return dryRunReport;\n throw error;\n });\n};\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n column: string;\n stamp: string;\n kind: string;\n key: readonly string[];\n};\n\nexport type StoreReport = {\n total: number;\n upgraded: number;\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
package/dist/upgrade/index.cjs
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('../chunk-
|
|
5
|
-
require('../chunk-
|
|
3
|
+
var chunk564JCO6Q_cjs = require('../chunk-564JCO6Q.cjs');
|
|
4
|
+
require('../chunk-SYU7NKZR.cjs');
|
|
5
|
+
require('../chunk-7PBIGCLL.cjs');
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
Object.defineProperty(exports, "changedStrings", {
|
|
10
10
|
enumerable: true,
|
|
11
|
-
get: function () { return
|
|
11
|
+
get: function () { return chunk564JCO6Q_cjs.changedStrings; }
|
|
12
12
|
});
|
|
13
13
|
Object.defineProperty(exports, "planSourceUpgrade", {
|
|
14
14
|
enumerable: true,
|
|
15
|
-
get: function () { return
|
|
15
|
+
get: function () { return chunk564JCO6Q_cjs.planSourceUpgrade; }
|
|
16
16
|
});
|
|
17
17
|
Object.defineProperty(exports, "renderReport", {
|
|
18
18
|
enumerable: true,
|
|
19
|
-
get: function () { return
|
|
19
|
+
get: function () { return chunk564JCO6Q_cjs.renderReport; }
|
|
20
20
|
});
|
|
21
21
|
Object.defineProperty(exports, "verifySourceUpgrade", {
|
|
22
22
|
enumerable: true,
|
|
23
|
-
get: function () { return
|
|
23
|
+
get: function () { return chunk564JCO6Q_cjs.verifySourceUpgrade; }
|
|
24
24
|
});
|
|
25
25
|
//# sourceMappingURL=index.cjs.map
|
|
26
26
|
//# sourceMappingURL=index.cjs.map
|
package/dist/upgrade/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
export { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade } from '../chunk-DGS4XJQQ.js';
|
|
2
|
+
import '../chunk-SH6BBA2X.js';
|
|
3
|
+
import '../chunk-STNFHBNR.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niscorp/strata",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "Migrations for nisc — one ledger for the tables a database holds and the documents stored in them, applied in order, recorded once, refused when edited.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";;;AAaO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF","file":"chunk-BW4CKKGE.cjs","sourcesContent":["export type StrataErrorCode =\n | 'INVALID_SEQUENCE'\n | 'EDITED'\n | 'TOO_NEW'\n | 'UNKNOWN_DEPENDENCY'\n | 'CYCLE'\n | 'PENDING'\n | 'STEP_FAILED'\n | 'DOES_NOT_FIT'\n | 'NO_TRANSACTION'\n | 'UNKNOWN_KIND'\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/plan.ts"],"names":[],"mappings":";;;AAEO,IAAM,WAAA,GAAc;AAEpB,IAAM,aAAA,GAAgB;AAEtB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAKjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgB,EAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAK,CAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqB,EAC/B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,UAAU,CAAA;AAAA,EAC1B,EAAA,EAAI,EACD,MAAA,EAAO,CACP,MAAM,QAAQ,CAAA,CACd,SAAS,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M,KAAA,GAAQ,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,EAAA,IAAI,UAAU,MAAA,EAAW;AACzB,EAAA,MAAM,IAAI,WAAA,CAAY,KAAA,CAAM,IAAA,EAAM,0CAAA,EAA4C,KAAK,QAAA,CAAS,GAAA,CAAI,CAAC,CAAA,KAAM,GAAG,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,MAAM,EAAE,CAAC,CAAA;AAClI","file":"chunk-CI652R5O.js","sourcesContent":["import { z } from 'zod';\n\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// `children[]` crosses the array at `children`, `endpoints.*` the record at\n// `endpoints`. Two wildcards, not one: nova's `children` is a single node or an\n// array, and one for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // Not both: a table sequence's version is recorded per database, a grammar\n // sequence's per document (its stamp), and one number cannot be both.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","import { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n applied: Readonly<Record<string, number>>;\n pending: readonly PreparedMigration[];\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/plan.ts"],"names":["z","StrataError"],"mappings":";;;;;AAEO,IAAM,WAAA,GAAc;AAEpB,IAAM,aAAA,GAAgB;AAEtB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAKjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAKA,KAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,UAAU,CAAA;AAAA,EAC1B,EAAA,EAAIA,MACD,MAAA,EAAO,CACP,MAAM,QAAQ,CAAA,CACd,SAAS,0GAAqG,CAAA;AAAA,EACjH,SAAA,EAAWA,KAAA,CACR,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA;AAIN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,iDAAiD;AAEtD,IAAM,aAAaA,KAAA,CAAE,kBAAA,CAAmB,QAAQ,CAAC,aAAA,EAAe,kBAAkB,CAAC;AAEnF,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,QAAQA,KAAA,CACL,MAAA,CAAOA,MAAE,MAAA,EAAO,CAAE,MAAM,UAAU,CAAA,EAAG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= /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// `children[]` crosses the array at `children`, `endpoints.*` the record at\n// `endpoints`. Two wildcards, not one: nova's `children` is a single node or an\n// array, and one for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // Not both: a table sequence's version is recorded per database, a grammar\n // sequence's per document (its stamp), and one number cannot be both.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","import { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n applied: Readonly<Record<string, number>>;\n pending: readonly PreparedMigration[];\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AAaO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF","file":"chunk-VNF4KPVN.js","sourcesContent":["export type StrataErrorCode =\n | 'INVALID_SEQUENCE'\n | 'EDITED'\n | 'TOO_NEW'\n | 'UNKNOWN_DEPENDENCY'\n | 'CYCLE'\n | 'PENDING'\n | 'STEP_FAILED'\n | 'DOES_NOT_FIT'\n | 'NO_TRANSACTION'\n | 'UNKNOWN_KIND'\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n"]}
|