symmetria-kit 1.0.0

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.
@@ -0,0 +1,2797 @@
1
+ import { _ as objectName, b as snapshotHash, f as canonicalJSON, g as migrationSnapshot, h as emptySnapshot, m as compareNames, p as checksum, s as indexSQL, v as parseMigrationSnapshot } from "./ddl-BpRIXfCw.js";
2
+ import { n as diffSchemas } from "./diff-ConfLt63.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { INDEX_METHODS, normalizeResult, quoteIdentifier } from "symmetria/internal";
5
+ import { access, mkdir, mkdtemp, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { hostname } from "node:os";
8
+ import { postgres } from "symmetria/driver";
9
+ import { setTimeout } from "node:timers/promises";
10
+ import { snakeCase, sqlState } from "symmetria";
11
+ //#region src/migrations/sql.ts
12
+ /** Split PostgreSQL scripts without splitting quoted strings or function bodies. */
13
+ const parseMigrationSQL = (script) => {
14
+ const statements = [];
15
+ let start = 0;
16
+ let position = 0;
17
+ let hasCode = false;
18
+ let words = [];
19
+ const finish = (end) => {
20
+ if (hasCode) {
21
+ const first = words[0];
22
+ if ([
23
+ "BEGIN",
24
+ "COMMIT",
25
+ "END",
26
+ "ROLLBACK",
27
+ "ABORT",
28
+ "SAVEPOINT",
29
+ "RELEASE"
30
+ ].includes(first ?? "") || first === "START" && words[1] === "TRANSACTION" || first === "PREPARE" && words[1] === "TRANSACTION") throw new Error("symmetria: migration transaction boundaries are managed by the runner");
31
+ if (first === "COPY" && words.includes("STDIN")) throw new Error("symmetria: COPY FROM STDIN is not supported in migration SQL files");
32
+ if (first === "SET" && words.includes("STANDARD_CONFORMING_STRINGS")) throw new Error("symmetria: migration scripts use standard_conforming_strings=on");
33
+ statements.push({
34
+ sql: script.slice(start, end).trim(),
35
+ words
36
+ });
37
+ }
38
+ hasCode = false;
39
+ words = [];
40
+ start = end + 1;
41
+ };
42
+ while (position < script.length) {
43
+ const character = script[position];
44
+ if (/\s/.test(character)) {
45
+ position += 1;
46
+ continue;
47
+ }
48
+ if (script.startsWith("--", position)) {
49
+ const newline = script.indexOf("\n", position + 2);
50
+ position = newline < 0 ? script.length : newline + 1;
51
+ continue;
52
+ }
53
+ if (script.startsWith("/*", position)) {
54
+ let depth = 1;
55
+ position += 2;
56
+ while (position < script.length && depth) if (script.startsWith("/*", position)) {
57
+ depth += 1;
58
+ position += 2;
59
+ } else if (script.startsWith("*/", position)) {
60
+ depth -= 1;
61
+ position += 2;
62
+ } else position += 1;
63
+ if (depth) throw new Error("symmetria: unterminated SQL block comment");
64
+ continue;
65
+ }
66
+ if (character === ";") {
67
+ finish(position);
68
+ position += 1;
69
+ continue;
70
+ }
71
+ hasCode = true;
72
+ if (character === "'" || character === "\"") {
73
+ const escaped = character === "'" && /[eE]/.test(script[position - 1] ?? "") && !/[\w$]/.test(script[position - 2] ?? "");
74
+ position += 1;
75
+ let closed = false;
76
+ while (position < script.length) {
77
+ if (escaped && script[position] === "\\") {
78
+ position += 2;
79
+ continue;
80
+ }
81
+ if (script[position] === character) {
82
+ if (script[position + 1] === character) {
83
+ position += 2;
84
+ continue;
85
+ }
86
+ position += 1;
87
+ closed = true;
88
+ break;
89
+ }
90
+ position += 1;
91
+ }
92
+ if (!closed) throw new Error("symmetria: unterminated SQL quote");
93
+ continue;
94
+ }
95
+ if (character === "$") {
96
+ const tag = script.slice(position).match(/^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z_0-9\u0080-\uFFFF]*)?\$/)?.[0];
97
+ if (tag) {
98
+ const end = script.indexOf(tag, position + tag.length);
99
+ if (end < 0) throw new Error("symmetria: unterminated SQL dollar quote");
100
+ position = end + tag.length;
101
+ continue;
102
+ }
103
+ }
104
+ const word = script.slice(position).match(/^[A-Za-z_][A-Za-z_0-9$]*/)?.[0];
105
+ if (word) {
106
+ words.push(word.toUpperCase());
107
+ position += word.length;
108
+ } else position += 1;
109
+ }
110
+ finish(script.length);
111
+ return statements;
112
+ };
113
+ const splitMigrationSQL = (script) => parseMigrationSQL(script).map((statement) => statement.sql);
114
+ const formatMigrationSQL = (statements) => statements.length ? `${statements.join(";\n\n")};\n` : "-- No schema changes.\n";
115
+ //#endregion
116
+ //#region src/migrations/lint.ts
117
+ const levelOrder = {
118
+ destructive: 0,
119
+ blocking: 1,
120
+ caution: 2
121
+ };
122
+ /** Review a diff for operations that fail or lose data on a populated database. */
123
+ const lintMigration = (plan, renames = {}) => {
124
+ const findings = [];
125
+ const renamedTables = renames.tables ?? {};
126
+ const afterTables = new Map(plan.after.tables.map((table) => [table.name, table]));
127
+ const report = (level, table, message, advice, column) => {
128
+ findings.push({
129
+ level,
130
+ table,
131
+ ...column ? { column } : {},
132
+ message,
133
+ advice
134
+ });
135
+ };
136
+ const compareColumns = (before, after) => {
137
+ const renamedColumns = renames.columns?.[after.name] ?? {};
138
+ const afterColumns = new Map(after.columns.map((column) => [column.name, column]));
139
+ const beforeColumns = new Map(before.columns.map((column) => [column.name, column]));
140
+ for (const column of before.columns) {
141
+ const renamedTo = renamedColumns[column.name];
142
+ const next = afterColumns.get(renamedTo ?? column.name);
143
+ if (!next) {
144
+ report("destructive", after.name, `Column "${column.name}" is dropped; its data is lost.`, "Stop reading and writing the column in a release first, then drop it in a later migration.", column.name);
145
+ continue;
146
+ }
147
+ if (renamedTo) report("caution", after.name, `Column "${column.name}" is renamed to "${renamedTo}".`, "Deploy code that tolerates both names, or add the new column and backfill it before removing the old one.", renamedTo);
148
+ compareColumn(after, column, next);
149
+ }
150
+ for (const column of after.columns) {
151
+ if (beforeColumns.has(column.name) || Object.values(renamedColumns).includes(column.name)) continue;
152
+ if (column.notNull && column.default === void 0 && !column.identity) report("blocking", after.name, `Column "${column.name}" is added as NOT NULL without a default; the statement fails when the table has rows.`, "Add a default, or add the column as nullable, backfill it and set NOT NULL in a later migration.", column.name);
153
+ if (column.unique) report("caution", after.name, `Column "${column.name}" is added with a UNIQUE constraint.`, "Existing rows all receive the same default; make sure the default is unique or add the constraint after backfilling.", column.name);
154
+ }
155
+ for (const definition of after.indexes) {
156
+ if (before.indexes.some((existing) => existing.sqlName === definition.sqlName && JSON.stringify(existing) === JSON.stringify(definition))) continue;
157
+ report(definition.unique ? "blocking" : "caution", after.name, definition.unique ? `Unique index "${definition.sqlName}" fails when existing rows contain duplicates.` : `Index "${definition.sqlName}" is created inside the migration transaction and blocks writes while it builds.`, definition.unique ? "Deduplicate the data first, then add the index." : "For large tables create it separately with $createIndexes({ concurrently: true }).");
158
+ }
159
+ if (JSON.stringify(before.primaryKey) !== JSON.stringify(after.primaryKey)) report("caution", after.name, `Primary key changes from (${before.primaryKey.join(", ")}) to (${after.primaryKey.join(", ")}).`, "The table is rewritten and foreign keys are rebuilt; plan the deploy for low traffic.");
160
+ };
161
+ const compareColumn = (table, before, after) => {
162
+ if (before.sqlType !== after.sqlType || before.enumeration !== after.enumeration) report("caution", table.name, `Column "${after.name}" changes type from ${before.enumeration ?? before.sqlType} to ${after.enumeration ?? after.sqlType}.`, "PostgreSQL rewrites the table and the USING cast can fail on existing values; add a new column, backfill in batches and swap it in a later migration.", after.name);
163
+ if (!before.notNull && after.notNull) report("blocking", table.name, `Column "${after.name}" becomes NOT NULL; the statement fails when existing rows contain NULL.`, "Backfill NULL values first, or add a default and set NOT NULL in a later migration.", after.name);
164
+ if (!before.unique && after.unique) report("blocking", table.name, `Column "${after.name}" becomes UNIQUE; the statement fails when existing rows contain duplicates.`, "Deduplicate the data first, then add the constraint.", after.name);
165
+ };
166
+ for (const table of plan.before.tables) {
167
+ const renamedTo = renamedTables[table.name];
168
+ const next = afterTables.get(renamedTo ?? table.name);
169
+ if (!next) {
170
+ report("destructive", table.name, `Table "${table.name}" is dropped; its rows are lost.`, "Stop using the table in a release first, keep a backup, then drop it in a later migration.");
171
+ continue;
172
+ }
173
+ if (renamedTo) report("caution", next.name, `Table "${table.name}" is renamed to "${renamedTo}".`, "Deploy code that tolerates both names, or create a view with the old name until every deployment is updated.");
174
+ compareColumns(table, next);
175
+ }
176
+ for (const enumeration of plan.before.enumerations) {
177
+ const next = plan.after.enumerations.find((candidate) => candidate.name === enumeration.name);
178
+ if (!next) continue;
179
+ const removed = enumeration.values.filter((value) => !next.values.includes(value));
180
+ if (removed.length) report("destructive", enumeration.name, `Enum "${enumeration.name}" drops ${removed.map((value) => `'${value}'`).join(", ")}; rows using those labels make the rebuild fail.`, "Update or delete the rows that use the removed labels before migrating.");
181
+ else if (JSON.stringify(enumeration.values) !== JSON.stringify(next.values)) report("caution", enumeration.name, `Enum "${enumeration.name}" is rebuilt to change its labels.`, "Dependent columns are rewritten while the type is replaced; plan for the lock.");
182
+ }
183
+ return findings.sort((left, right) => levelOrder[left.level] - levelOrder[right.level] || left.table.localeCompare(right.table));
184
+ };
185
+ const formatLintFindings = (findings) => findings.length ? findings.map((finding) => `${finding.level.toUpperCase().padEnd(11)} ${finding.table}${finding.column ? `.${finding.column}` : ""}: ${finding.message}\n ${finding.advice}`).join("\n") : "No risky operations found.";
186
+ //#endregion
187
+ //#region src/migrations/publication.ts
188
+ /**
189
+ * Atomic publication of generated migration files: lock file, fsync, ownership record, rollback and crash recovery.
190
+ */
191
+ const generationLockName = ".symmetria-generate.lock";
192
+ const fileIdentity = async (path) => {
193
+ try {
194
+ const value = await stat(path, { bigint: true });
195
+ return `${value.dev}:${value.ino}`;
196
+ } catch (error) {
197
+ if (error.code === "ENOENT") return;
198
+ throw error;
199
+ }
200
+ };
201
+ const syncPath = async (path) => {
202
+ const file = await open(path, "r");
203
+ try {
204
+ await file.sync();
205
+ } finally {
206
+ await file.close();
207
+ }
208
+ };
209
+ const savePublication = async (directory, publication) => {
210
+ const path = join(directory, generationLockName, "publication.json");
211
+ await writeFile(`${path}.next`, JSON.stringify(publication));
212
+ await syncPath(`${path}.next`);
213
+ await rename(`${path}.next`, path);
214
+ await syncPath(dirname(path));
215
+ };
216
+ const recordGenerationOwner = async (directory) => {
217
+ const path = join(directory, generationLockName, "owner.json");
218
+ await writeFile(path, JSON.stringify({
219
+ pid: process.pid,
220
+ host: hostname()
221
+ }));
222
+ await syncPath(path);
223
+ await syncPath(dirname(path));
224
+ await syncPath(directory);
225
+ };
226
+ const present = async (path) => {
227
+ try {
228
+ await (await open(path)).close();
229
+ return true;
230
+ } catch (error) {
231
+ if (error.code === "ENOENT") return false;
232
+ throw error;
233
+ }
234
+ };
235
+ const rollbackPublication = async (publication) => {
236
+ for (const { source, destination, identity } of [...publication.moves].reverse()) {
237
+ const sourceIdentity = await fileIdentity(source);
238
+ if (sourceIdentity === identity) continue;
239
+ if (await fileIdentity(destination) === identity && sourceIdentity === void 0) {
240
+ await rename(destination, source);
241
+ await syncPath(dirname(source));
242
+ await syncPath(dirname(destination));
243
+ } else throw new Error(`symmetria: conflicting publication recovery files: ${source} and ${destination}`);
244
+ }
245
+ };
246
+ /** Recover a process crash without discarding a live writer or guessing at incomplete metadata. */
247
+ const recoverMigrationFiles = async (directory) => {
248
+ directory = resolve(directory);
249
+ const lock = join(directory, generationLockName);
250
+ const owner = JSON.parse(await readFile(join(lock, "owner.json"), "utf8"));
251
+ if (owner.host !== hostname() || !Number.isSafeInteger(owner.pid) || owner.pid < 1) throw new Error("symmetria: generation lock belongs to another host or has invalid ownership; inspect it manually");
252
+ try {
253
+ process.kill(owner.pid, 0);
254
+ throw new Error("symmetria: migration generation owner is still running");
255
+ } catch (error) {
256
+ if (error.code !== "ESRCH") throw error;
257
+ }
258
+ const recovery = join(lock, "recovering");
259
+ await mkdir(recovery);
260
+ try {
261
+ const path = join(lock, "publication.json");
262
+ if (await present(path)) {
263
+ const publication = JSON.parse(await readFile(path, "utf8"));
264
+ const inside = (path) => resolve(path).startsWith(`${directory}/`);
265
+ if (!inside(publication.temporary) || !publication.temporary.startsWith(join(directory, ".symmetria-")) || typeof publication.hadMetadata !== "boolean" || typeof publication.committed !== "boolean" || !Array.isArray(publication.moves) || publication.moves.some((move) => !inside(move.source) || !inside(move.destination) || typeof move.identity !== "string")) throw new Error("symmetria: invalid publication recovery journal");
266
+ if (!publication.committed) {
267
+ await rollbackPublication(publication);
268
+ if (!publication.hadMetadata) await rm(join(directory, "meta"), {
269
+ recursive: true,
270
+ force: true
271
+ });
272
+ publication.moves = [];
273
+ await savePublication(directory, publication);
274
+ }
275
+ await rm(publication.temporary, {
276
+ recursive: true,
277
+ force: true
278
+ });
279
+ }
280
+ await rm(lock, {
281
+ recursive: true,
282
+ force: true
283
+ });
284
+ await syncPath(directory);
285
+ } catch (error) {
286
+ await rm(recovery, {
287
+ recursive: true,
288
+ force: true
289
+ });
290
+ throw error;
291
+ }
292
+ };
293
+ //#endregion
294
+ //#region src/migrations/files.ts
295
+ /**
296
+ * Migration files on disk: manifest and state loading, SQL generation, squashing and file naming.
297
+ */
298
+ const migrationIdPattern = /^\d{6}_[a-z0-9][a-z0-9_]*$/;
299
+ const hashPattern = /^[a-f0-9]{64}$/;
300
+ const metadataFiles = ["migration.json", "snapshot.json"];
301
+ const lockName = generationLockName;
302
+ const missing = (error) => !!error && typeof error === "object" && "code" in error && error.code === "ENOENT";
303
+ const exists = (path) => access(path).then(() => true, (error) => {
304
+ if (missing(error)) return false;
305
+ throw error;
306
+ });
307
+ const readDirectory = (directory) => readdir(directory, { withFileTypes: true }).catch((error) => {
308
+ if (missing(error)) return [];
309
+ throw error;
310
+ });
311
+ const readMigrationState = async (directory) => {
312
+ const directories = (await readDirectory(directory)).filter((entry) => entry.name !== "meta" && !entry.name.startsWith(".") && entry.isDirectory()).map((entry) => entry.name).sort(compareNames);
313
+ const metadata = await readDirectory(join(directory, "meta"));
314
+ if (!directories.length && !metadata.length) return {
315
+ migrations: [],
316
+ snapshot: emptySnapshot()
317
+ };
318
+ if (metadata.length !== metadataFiles.length || metadata.some((entry) => !entry.isFile() || !metadataFiles.includes(entry.name))) throw new Error("symmetria: migration metadata must contain only meta/snapshot.json and meta/migration.json");
319
+ const [journalText, snapshotText] = await Promise.all(metadataFiles.map((name) => readFile(join(directory, "meta", name), "utf8")));
320
+ const journal = JSON.parse(journalText);
321
+ const snapshot = parseMigrationSnapshot(JSON.parse(snapshotText));
322
+ if (!journal || journal.version !== 1 || !Array.isArray(journal.migrations) || journal.migrations.length !== directories.length) throw new Error("symmetria: migration journal does not match SQL directories");
323
+ const migrations = [];
324
+ let previousHash = snapshotHash(emptySnapshot());
325
+ let previousOrdinal = 0;
326
+ for (const [position, id] of directories.entries()) {
327
+ const manifest = journal.migrations[position];
328
+ if (!migrationIdPattern.test(id) || Number(id.slice(0, 6)) <= previousOrdinal || !manifest || manifest.version !== 1 || manifest.id !== id || manifest.parent !== (migrations.at(-1)?.id ?? null) || manifest.before !== previousHash || typeof manifest.after !== "string" || !hashPattern.test(manifest.after) || manifest.transaction !== void 0 && ![
329
+ "batch",
330
+ "each",
331
+ "none"
332
+ ].includes(manifest.transaction)) throw new Error(`symmetria: migration chain mismatch at "${id}"`);
333
+ const location = join(directory, id);
334
+ if ((await readDirectory(location)).some((entry) => metadataFiles.includes(entry.name))) throw new Error(`symmetria: unexpected per-migration metadata in "${id}"`);
335
+ const [up, down] = await Promise.all([readFile(join(location, "up.sql"), "utf8"), readFile(join(location, "down.sql"), "utf8")]);
336
+ splitMigrationSQL(up);
337
+ splitMigrationSQL(down);
338
+ migrations.push({
339
+ id,
340
+ manifest,
341
+ up,
342
+ down,
343
+ checksum: checksum(canonicalJSON({
344
+ manifest,
345
+ up,
346
+ down
347
+ }))
348
+ });
349
+ previousHash = manifest.after;
350
+ previousOrdinal = Number(id.slice(0, 6));
351
+ }
352
+ if (snapshotHash(snapshot) !== previousHash) throw new Error("symmetria: latest snapshot checksum does not match the migration journal");
353
+ return {
354
+ migrations,
355
+ snapshot
356
+ };
357
+ };
358
+ /** One current schema snapshot and a compact journal for the entire SQL chain. */
359
+ const loadMigrationState = async (directory) => {
360
+ const assertUnlocked = async () => {
361
+ if (await exists(join(directory, lockName))) throw new Error("symmetria: migration generation is already locked");
362
+ };
363
+ await assertUnlocked();
364
+ const state = await readMigrationState(directory);
365
+ await assertUnlocked();
366
+ return state;
367
+ };
368
+ const loadMigrations = async (directory) => (await loadMigrationState(directory)).migrations;
369
+ const normalizeName = (name) => {
370
+ const normalized = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
371
+ if (!normalized || normalized.length > 100) throw new Error("symmetria: migration names must contain 1–100 letters/digits after normalization");
372
+ return normalized;
373
+ };
374
+ const withGenerationLock = async (directory, callback) => {
375
+ await mkdir(directory, { recursive: true });
376
+ const lock = join(directory, lockName);
377
+ await mkdir(lock).catch((error) => {
378
+ if (error && typeof error === "object" && "code" in error && error.code === "EEXIST") throw new Error("symmetria: migration generation is already locked");
379
+ throw error;
380
+ });
381
+ try {
382
+ await recordGenerationOwner(directory);
383
+ return await callback();
384
+ } finally {
385
+ if (!await exists(join(lock, "publication.json"))) await rm(lock, {
386
+ recursive: true,
387
+ force: true
388
+ });
389
+ }
390
+ };
391
+ const writeMigrationFiles = async (directory, migration, manifests, replaced = []) => {
392
+ if (!replaced.includes(migration.id) && await exists(join(directory, migration.id))) throw new Error(`symmetria: migration "${migration.id}" already exists`);
393
+ const temporary = await mkdtemp(join(directory, ".symmetria-"));
394
+ const staged = join(temporary, "staged");
395
+ const backup = join(temporary, "backup");
396
+ const moved = [];
397
+ let preserveBackup = false;
398
+ const hadMetadata = await exists(join(directory, "meta"));
399
+ const publication = {
400
+ temporary,
401
+ hadMetadata,
402
+ moves: moved,
403
+ committed: false
404
+ };
405
+ const move = async (source, destination) => {
406
+ moved.push({
407
+ source,
408
+ destination,
409
+ identity: await fileIdentity(source)
410
+ });
411
+ await savePublication(directory, publication);
412
+ await rename(source, destination);
413
+ await syncPath(resolve(source, ".."));
414
+ await syncPath(resolve(destination, ".."));
415
+ };
416
+ try {
417
+ await Promise.all([
418
+ mkdir(join(staged, migration.id), { recursive: true }),
419
+ mkdir(join(staged, "meta"), { recursive: true }),
420
+ mkdir(join(backup, "meta"), { recursive: true })
421
+ ]);
422
+ const journal = {
423
+ version: 1,
424
+ migrations: manifests
425
+ };
426
+ await Promise.all([
427
+ writeFile(join(staged, migration.id, "up.sql"), migration.up),
428
+ writeFile(join(staged, migration.id, "down.sql"), migration.down),
429
+ writeFile(join(staged, "meta", "migration.json"), `${JSON.stringify(journal, null, 2)}\n`),
430
+ writeFile(join(staged, "meta", "snapshot.json"), `${JSON.stringify(migration.snapshot, null, 2)}\n`)
431
+ ]);
432
+ for (const path of [
433
+ join(staged, migration.id, "up.sql"),
434
+ join(staged, migration.id, "down.sql"),
435
+ ...metadataFiles.map((name) => join(staged, "meta", name)),
436
+ join(staged, migration.id),
437
+ join(staged, "meta"),
438
+ staged,
439
+ backup,
440
+ temporary
441
+ ]) await syncPath(path);
442
+ await savePublication(directory, publication);
443
+ await mkdir(join(directory, "meta"), { recursive: true });
444
+ for (const id of replaced) await move(join(directory, id), join(backup, id));
445
+ for (const name of metadataFiles) {
446
+ const path = join(directory, "meta", name);
447
+ if (await exists(path)) await move(path, join(backup, "meta", name));
448
+ await move(join(staged, "meta", name), path);
449
+ }
450
+ await move(join(staged, migration.id), join(directory, migration.id));
451
+ publication.committed = true;
452
+ await savePublication(directory, publication);
453
+ } catch (error) {
454
+ if (publication.committed) {
455
+ preserveBackup = true;
456
+ throw new Error("symmetria: publication commit could not be confirmed; use recover after this process exits", { cause: error });
457
+ }
458
+ const failures = [error];
459
+ try {
460
+ await rollbackPublication(publication);
461
+ } catch (rollbackError) {
462
+ failures.push(rollbackError);
463
+ }
464
+ if (failures.length > 1) {
465
+ preserveBackup = true;
466
+ throw new AggregateError(failures, `symmetria: migration publication rollback failed; original files retained in ${backup}`);
467
+ }
468
+ if (!hadMetadata) await rm(join(directory, "meta"), {
469
+ recursive: true,
470
+ force: true
471
+ });
472
+ preserveBackup = true;
473
+ publication.moves = [];
474
+ await savePublication(directory, publication);
475
+ preserveBackup = false;
476
+ throw error;
477
+ } finally {
478
+ if (!preserveBackup) {
479
+ await rm(temporary, {
480
+ recursive: true,
481
+ force: true
482
+ });
483
+ await rm(join(directory, lockName, "publication.json"), { force: true });
484
+ }
485
+ }
486
+ };
487
+ /** Replace the SQL chain and journal with a baseline for the current snapshot. */
488
+ const squashMigrations = async (options) => {
489
+ const directory = resolve(options.directory);
490
+ const name = normalizeName(options.name);
491
+ return withGenerationLock(directory, async () => {
492
+ const { migrations, snapshot } = await readMigrationState(directory);
493
+ if (migrations.length < 2) return null;
494
+ const plan = diffSchemas(emptySnapshot(), snapshot);
495
+ const id = `000001_${name}`;
496
+ const manifest = {
497
+ version: 1,
498
+ id,
499
+ parent: null,
500
+ before: snapshotHash(emptySnapshot()),
501
+ after: snapshotHash(snapshot)
502
+ };
503
+ const up = formatMigrationSQL(plan.up);
504
+ const down = formatMigrationSQL(plan.down);
505
+ const squashed = {
506
+ id,
507
+ manifest,
508
+ snapshot,
509
+ up,
510
+ down,
511
+ checksum: checksum(canonicalJSON({
512
+ manifest,
513
+ up,
514
+ down
515
+ }))
516
+ };
517
+ await writeMigrationFiles(directory, squashed, [manifest], migrations.map((migration) => migration.id));
518
+ return squashed;
519
+ });
520
+ };
521
+ /** SQL files are editable before application; applied checksums include both directions. */
522
+ const generateMigration = async (options) => {
523
+ const directory = resolve(options.directory);
524
+ const name = normalizeName(options.name);
525
+ if (options.transaction !== void 0 && ![
526
+ "batch",
527
+ "each",
528
+ "none"
529
+ ].includes(options.transaction)) throw new Error("symmetria: transaction must be batch, each, or none");
530
+ if (options.online && options.transaction && options.transaction !== "none") throw new Error("symmetria: online generation requires transaction: \"none\"");
531
+ return withGenerationLock(directory, async () => {
532
+ const { migrations, snapshot: before } = await readMigrationState(directory);
533
+ const previous = migrations.at(-1);
534
+ if (!options.empty && !options.snapshot) throw new Error("symmetria: generation requires a schema snapshot");
535
+ const next = options.empty ? before : options.snapshot;
536
+ const after = "version" in next ? parseMigrationSnapshot(next) : migrationSnapshot(next);
537
+ const plan = diffSchemas(before, after, options);
538
+ const destructive = options.allowDestructive ? [] : lintMigration(plan, options.renames).filter((finding) => finding.level === "destructive");
539
+ if (destructive.length) throw new Error(`symmetria: destructive migration requires explicit rename hints or allowDestructive (--allow-destructive):\n${destructive.map((finding) => ` - ${finding.table}${finding.column ? `.${finding.column}` : ""}: ${finding.message}`).join("\n")}`);
540
+ if (!options.empty && !plan.up.length && !plan.down.length) return null;
541
+ const ordinal = Number(previous?.id.slice(0, 6) ?? 0) + 1;
542
+ if (ordinal > 999999) throw new Error("symmetria: migration sequence exhausted");
543
+ const id = `${String(ordinal).padStart(6, "0")}_${name}`;
544
+ const manifest = {
545
+ version: 1,
546
+ id,
547
+ parent: previous?.id ?? null,
548
+ before: snapshotHash(before),
549
+ after: snapshotHash(after),
550
+ ...options.online ? { transaction: "none" } : options.transaction && options.transaction !== "batch" ? { transaction: options.transaction } : {}
551
+ };
552
+ const up = formatMigrationSQL(plan.up);
553
+ const down = formatMigrationSQL(plan.down);
554
+ const migration = {
555
+ id,
556
+ manifest,
557
+ snapshot: after,
558
+ up,
559
+ down,
560
+ checksum: checksum(canonicalJSON({
561
+ manifest,
562
+ up,
563
+ down
564
+ }))
565
+ };
566
+ await writeMigrationFiles(directory, migration, [...migrations.map((entry) => entry.manifest), manifest]);
567
+ return migration;
568
+ });
569
+ };
570
+ //#endregion
571
+ //#region src/migrations/sql-lint.ts
572
+ /**
573
+ * Lints migration SQL for statements that lock or rewrite large tables, anonymous constraints and
574
+ * volatile defaults, with safer rewrites.
575
+ */
576
+ const LEADING_COMMENTS = String.raw`^\s*(?:(?:--[^\n]*(?:\n|$)|/\*[\s\S]*?\*/)\s*)*`;
577
+ const IDENTIFIER = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`;
578
+ const TABLE_NAME = String.raw`(${IDENTIFIER}(?:\s*\.\s*${IDENTIFIER})?)`;
579
+ const CREATED_TABLE = new RegExp(String.raw`${LEADING_COMMENTS}CREATE\s+(?:(?:GLOBAL\s+|LOCAL\s+)?(?:TEMP|TEMPORARY|UNLOGGED)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${TABLE_NAME}`, "i");
580
+ const TARGET_TABLE = new RegExp(String.raw`${LEADING_COMMENTS}(?:CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:(?:IF\s+NOT\s+EXISTS\s+)?${IDENTIFIER}\s+)?ON\s+(?:ONLY\s+)?|ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?)${TABLE_NAME}`, "i");
581
+ const RECREATED_OBJECT = new RegExp(String.raw`(?:\bADD\s+CONSTRAINT\s+(${IDENTIFIER})|\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(${IDENTIFIER})\s+ON\b)`, "gi");
582
+ const DROPPED_OBJECT = new RegExp(String.raw`${LEADING_COMMENTS}(?:ALTER\s+TABLE\b[^;]*?\bDROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?(${IDENTIFIER})|DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?(${IDENTIFIER}))\s*$`, "i");
583
+ /** Normalizes a possibly qualified, possibly quoted table name the way PostgreSQL folds it. */
584
+ const tableKey = (name) => (name.match(new RegExp(IDENTIFIER, "g")) ?? []).map((part) => part.startsWith("\"") ? part.slice(1, -1).replaceAll("\"\"", "\"") : part.toLowerCase()).join(".");
585
+ /** Inspect the SQL that will execute, ignoring comments, strings and function bodies. */
586
+ const lintMigrationSQL = (sql, name = "SQL") => {
587
+ const created = /* @__PURE__ */ new Set();
588
+ const statements = parseMigrationSQL(sql);
589
+ const recreated = new Set(statements.flatMap(({ sql: statement }) => [...statement.matchAll(RECREATED_OBJECT)].map((match) => match[1] ?? match[2])));
590
+ return statements.flatMap(({ words, sql: statement }, position) => {
591
+ const text = words.join(" ");
592
+ const createdTable = statement.match(CREATED_TABLE)?.[1];
593
+ if (createdTable) created.add(tableKey(createdTable));
594
+ const target = statement.match(TARGET_TABLE)?.[1];
595
+ const newTable = target !== void 0 && created.has(tableKey(target));
596
+ const finding = (level, message, advice) => [{
597
+ level,
598
+ table: name,
599
+ statement: position + 1,
600
+ message: `Statement ${position + 1}: ${message}`,
601
+ advice
602
+ }];
603
+ if (/^ALTER (?:TABLE|INDEX|TYPE)\b(?! .*\bDROP\b).*\bRENAME\b/.test(text)) return [];
604
+ const dropped = statement.match(DROPPED_OBJECT);
605
+ const droppedName = dropped?.[1] ?? dropped?.[2];
606
+ if (droppedName !== void 0 && recreated.has(droppedName)) return finding("caution", "Rebuilds a constraint or index that this migration creates again.", "The rebuild scans the table under a lock; on large tables prefer a rename or a concurrent build.");
607
+ if (/^(DROP|TRUNCATE|DELETE)\b/.test(text) || /^ALTER TABLE\b.*\bDROP(?:$| (?!DEFAULT\b|NOT\b|IDENTITY\b))/.test(text) || /^WITH\b.*\bDELETE\b/.test(text)) return finding("destructive", "Removes data or a database object.", "Review the exact SQL and deploy dependent application changes first.");
608
+ if (newTable) return [];
609
+ const addedClauses = /^ALTER TABLE\b/.test(text) ? text.split(/\bADD\b/).slice(1) : [];
610
+ const isConstraint = (clause) => /^\s*(?:CONSTRAINT|PRIMARY KEY|UNIQUE|CHECK|FOREIGN KEY|EXCLUDE)\b/.test(clause);
611
+ const addedConstraints = addedClauses.filter(isConstraint);
612
+ const addedColumns = addedClauses.filter((clause) => !isConstraint(clause));
613
+ if (/^ALTER TABLE\b.*\bSET NOT NULL\b/.test(text) || addedColumns.some((clause) => /\bNOT NULL\b/.test(clause) && !/\bDEFAULT\b/.test(clause))) return finding("blocking", "Requires non-null values in existing rows.", "Backfill first, then validate the constraint.");
614
+ if (/^CREATE UNIQUE INDEX\b/.test(text) || addedConstraints.some((clause) => /\b(?:UNIQUE|PRIMARY KEY)\b/.test(clause) && !/\bUSING INDEX\b/.test(clause))) return finding("blocking", "Requires unique existing values.", "Check and resolve duplicates before applying.");
615
+ if (addedColumns.some((clause) => /\b(?:GENERATED\b.*\b(?:IDENTITY|STORED)|(?:SMALL|BIG)?SERIAL)\b/.test(clause))) return finding("caution", "An identity, serial or stored generated column rewrites every existing row.", "Add a plain column, backfill in batches, then attach the identity or expression.");
616
+ if (addedColumns.length) return addedColumns.some((clause) => /\bDEFAULT\b.*\b(?:CLOCK_TIMESTAMP|TIMEOFDAY|RANDOM|GEN_RANDOM_UUID|UUID_GENERATE_V\d|NEXTVAL)\b/.test(clause)) ? finding("caution", "A volatile default rewrites every existing row.", "Add the column without the default, backfill in batches, then set the default.") : addedConstraints.length ? finding("caution", "Adds a constraint that is validated against existing rows under a lock.", "Add it NOT VALID, then VALIDATE CONSTRAINT separately on large tables.") : [];
617
+ if (/^ALTER TABLE\b.*\bALTER COLUMN\b.*\bTYPE\b/.test(text)) return finding("caution", "Changing a column type rewrites the table under an ACCESS EXCLUSIVE lock unless the cast is binary-coercible.", "Expect downtime proportional to table size; for large tables add a new column, backfill and switch.");
618
+ if (/^CREATE INDEX\b/.test(text) && !words.includes("CONCURRENTLY")) return finding("caution", "Index construction blocks writes.", "Use a dedicated nontransactional migration with CREATE INDEX CONCURRENTLY on large tables.");
619
+ if (/^(ALTER|UPDATE|INSERT|DO|CALL|WITH|SELECT)\b/.test(text) || /^CREATE (?:OR REPLACE )?(?:FUNCTION|PROCEDURE|TRIGGER)\b/.test(text)) return finding("caution", "Contains a schema change, data operation or executable SQL requiring review.", "Verify locks, data preconditions and the upgrade against representative data. SQL lint does not analyze function bodies.");
620
+ if (!/^(CREATE|COMMENT|GRANT|REVOKE)\b/.test(text)) return finding("caution", "SQL is outside the static migration checks.", "Review this statement and exercise it with verify.");
621
+ return [];
622
+ });
623
+ };
624
+ //#endregion
625
+ //#region src/migrations/catalog.ts
626
+ /**
627
+ * Installed extensions other than plpgsql. Kept out of readCatalog, whose rows are
628
+ * compared between databases by verification.
629
+ */
630
+ const readExtensions = async (options) => normalizeResult(await options.execute({
631
+ sql: `SELECT extension.extname AS name, namespace.nspname AS schema
632
+ FROM pg_extension extension JOIN pg_namespace namespace ON namespace.oid = extension.extnamespace
633
+ WHERE extension.extname <> 'plpgsql' ORDER BY extension.extname COLLATE "C"`,
634
+ parameters: []
635
+ })).rows;
636
+ /** Stable catalog representation for drift, replay verification and rollback checks. */
637
+ const readCatalog = async (options) => {
638
+ const query = async (sql) => normalizeResult(await options.execute({
639
+ sql,
640
+ parameters: [
641
+ options.schemaName ?? null,
642
+ options.metadataSchema ?? "public",
643
+ options.metadataTable ?? "_symmetria_migrations"
644
+ ]
645
+ })).rows;
646
+ const filter = "namespace.nspname = COALESCE($1, current_schema()) AND NOT (namespace.nspname = $2 AND relation.relname = $3)";
647
+ return {
648
+ tables: await query(`SELECT relation.relname AS name FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace WHERE ${filter} AND relation.relkind IN ('r', 'p') ORDER BY relation.relname COLLATE "C"`),
649
+ columns: await query(`
650
+ SELECT relation.relname AS table_name, attribute.attname AS column_name,
651
+ format_type(attribute.atttypid, attribute.atttypmod) AS data_type,
652
+ CASE WHEN typ.typtype = 'e' THEN typ.typname ELSE NULL END AS enum_name,
653
+ CASE WHEN typ.typtype = 'e' AND typ.typnamespace <> relation.relnamespace THEN typ_namespace.nspname ELSE NULL END AS enum_schema,
654
+ attribute.attnotnull AS not_null, attribute.attidentity AS identity,
655
+ pg_get_expr(definition.adbin, definition.adrelid) AS default
656
+ FROM pg_attribute attribute JOIN pg_class relation ON relation.oid = attribute.attrelid
657
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
658
+ JOIN pg_type typ ON typ.oid = attribute.atttypid
659
+ JOIN pg_namespace typ_namespace ON typ_namespace.oid = typ.typnamespace
660
+ LEFT JOIN pg_attrdef definition ON definition.adrelid = relation.oid AND definition.adnum = attribute.attnum
661
+ WHERE ${filter} AND relation.relkind IN ('r', 'p') AND attribute.attnum > 0 AND NOT attribute.attisdropped
662
+ ORDER BY relation.relname COLLATE "C", attribute.attname COLLATE "C"`),
663
+ constraints: await query(`
664
+ SELECT relation.relname AS table_name, con.conname AS name, con.contype AS kind,
665
+ ARRAY(SELECT att.attname FROM unnest(con.conkey) WITH ORDINALITY k(num, pos) JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = k.num ORDER BY pos) AS columns,
666
+ target.relname AS reference_table,
667
+ CASE WHEN target.relnamespace = relation.relnamespace THEN NULL ELSE target_namespace.nspname END AS reference_schema,
668
+ ARRAY(SELECT att.attname FROM unnest(con.confkey) WITH ORDINALITY k(num, pos) JOIN pg_attribute att ON att.attrelid = con.confrelid AND att.attnum = k.num ORDER BY pos) AS reference_columns,
669
+ con.confdeltype AS on_delete, con.confupdtype AS on_update, con.confmatchtype AS match,
670
+ con.condeferrable AS deferrable, con.condeferred AS initially_deferred, con.convalidated AS validated,
671
+ con.connoinherit AS no_inherit, COALESCE((SELECT (to_jsonb(i)->>'indnullsnotdistinct')::boolean FROM pg_index i WHERE i.indexrelid = con.conindid), false) AS nulls_not_distinct,
672
+ pg_get_expr(con.conbin, con.conrelid) AS expression, pg_get_constraintdef(con.oid) AS definition
673
+ FROM pg_constraint con JOIN pg_class relation ON relation.oid = con.conrelid
674
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
675
+ LEFT JOIN pg_class target ON target.oid = con.confrelid
676
+ LEFT JOIN pg_namespace target_namespace ON target_namespace.oid = target.relnamespace
677
+ WHERE ${filter} AND con.contype IN ('p', 'u', 'f', 'c', 'x')
678
+ ORDER BY relation.relname COLLATE "C", con.conname COLLATE "C"`),
679
+ indexes: await query(`
680
+ SELECT relation.relname AS table_name, idx.relname AS name, i.indisvalid AS valid, i.indisready AS ready,
681
+ pg_get_indexdef(i.indexrelid) AS definition,
682
+ EXISTS(SELECT 1 FROM pg_constraint con WHERE con.conindid = i.indexrelid AND con.contype IN ('p', 'u', 'x')) AS constraint
683
+ FROM pg_index i JOIN pg_class relation ON relation.oid = i.indrelid JOIN pg_class idx ON idx.oid = i.indexrelid
684
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace WHERE ${filter}
685
+ ORDER BY relation.relname COLLATE "C", idx.relname COLLATE "C"`),
686
+ enumerations: await query(`
687
+ SELECT typ.typname AS name, array_agg(enum.enumlabel ORDER BY enum.enumsortorder) AS values
688
+ FROM pg_type typ JOIN pg_namespace namespace ON namespace.oid = typ.typnamespace
689
+ JOIN pg_enum enum ON enum.enumtypid = typ.oid
690
+ WHERE namespace.nspname = COALESCE($1, current_schema()) AND $2::text IS NOT NULL AND $3::text IS NOT NULL
691
+ GROUP BY typ.typname ORDER BY typ.typname COLLATE "C"`)
692
+ };
693
+ };
694
+ //#endregion
695
+ //#region src/introspection/catalog.ts
696
+ /**
697
+ * Catalog queries that only introspection needs on top of readCatalog: column
698
+ * declaration order, generated columns, partitioning and structured index details.
699
+ */
700
+ const query = async (options, sql) => normalizeResult(await options.execute({
701
+ sql,
702
+ parameters: [
703
+ options.schemaName ?? null,
704
+ options.metadataSchema ?? "public",
705
+ options.metadataTable ?? "_symmetria_migrations"
706
+ ]
707
+ })).rows;
708
+ const filter = "namespace.nspname = COALESCE($1, current_schema()) AND NOT (namespace.nspname = $2 AND relation.relname = $3)";
709
+ /** Physical column order and generated-column markers; kept apart from readCatalog, whose rows are compared across databases. */
710
+ const readColumnLayout = (options) => query(options, `SELECT relation.relname AS table_name, attribute.attname AS column_name,
711
+ attribute.attnum::integer AS position, attribute.attgenerated::text AS generated
712
+ FROM pg_attribute attribute JOIN pg_class relation ON relation.oid = attribute.attrelid
713
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
714
+ WHERE ${filter} AND relation.relkind IN ('r', 'p') AND attribute.attnum > 0 AND NOT attribute.attisdropped
715
+ ORDER BY relation.relname COLLATE "C", attribute.attnum`);
716
+ const readTableDetails = (options) => query(options, `SELECT relation.relname AS name, relation.relkind::text AS kind, relation.relispartition AS partition
717
+ FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
718
+ WHERE ${filter} AND relation.relkind IN ('r', 'p')
719
+ ORDER BY relation.relname COLLATE "C"`);
720
+ /** Every non-primary-key index with its keys, ordering flags, INCLUDE columns and predicate. */
721
+ const readIndexDetails = (options) => query(options, `SELECT relation.relname AS table_name, indexrelation.relname AS index_name,
722
+ index.indisunique AS is_unique, COALESCE((to_jsonb(index)->>'indnullsnotdistinct')::boolean, false) AS nulls_not_distinct, accessmethod.amname AS method,
723
+ ARRAY(SELECT pg_get_indexdef(index.indexrelid, position, true)
724
+ FROM generate_series(1, index.indnkeyatts) position) AS keys,
725
+ ARRAY(SELECT index.indoption[position - 1]::integer
726
+ FROM generate_series(1, index.indnkeyatts) position) AS options,
727
+ ARRAY(SELECT pg_get_indexdef(index.indexrelid, position, true)
728
+ FROM generate_series(index.indnkeyatts + 1, index.indnatts) position) AS included,
729
+ ARRAY(SELECT CASE WHEN opclass.opcdefault THEN NULL ELSE opclass.opcname::text END
730
+ FROM unnest(index.indclass::oid[]) WITH ORDINALITY classes(oid, position)
731
+ JOIN pg_opclass opclass ON opclass.oid = classes.oid ORDER BY position) AS opclasses,
732
+ indexrelation.reloptions::text[] AS reloptions,
733
+ pg_get_expr(index.indpred, index.indrelid, true) AS predicate,
734
+ pg_get_indexdef(index.indexrelid) AS definition
735
+ FROM pg_index index
736
+ JOIN pg_class relation ON relation.oid = index.indrelid
737
+ JOIN pg_class indexrelation ON indexrelation.oid = index.indexrelid
738
+ JOIN pg_am accessmethod ON accessmethod.oid = indexrelation.relam
739
+ JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace
740
+ WHERE ${filter} AND NOT index.indisprimary
741
+ ORDER BY relation.relname COLLATE "C", indexrelation.relname COLLATE "C"`);
742
+ /** Everything `pull` needs in one round of queries. */
743
+ const readPullCatalog = async (options) => {
744
+ const [schemaRow] = await query(options, "SELECT COALESCE($1, current_schema()) AS name WHERE $2::text IS NOT NULL AND $3::text IS NOT NULL");
745
+ const catalog = await readCatalog(options);
746
+ const layout = await readColumnLayout(options);
747
+ const details = await readTableDetails(options);
748
+ const indexDetails = await readIndexDetails(options);
749
+ const extensions = await readExtensions(options);
750
+ return {
751
+ ...catalog,
752
+ schemaName: schemaRow?.name ?? options.schemaName ?? "public",
753
+ layout,
754
+ details,
755
+ indexDetails,
756
+ extensions
757
+ };
758
+ };
759
+ //#endregion
760
+ //#region src/migrations/drift-expressions.ts
761
+ /** Let PostgreSQL normalize casts, parentheses and expression rewrites without scanning data. */
762
+ const expressionsMatch = async (expected, actual, tableName, options) => {
763
+ const table = `${options.schemaName ? `${quoteIdentifier(options.schemaName)}.` : ""}${quoteIdentifier(tableName)}`;
764
+ try {
765
+ const output = (normalizeResult(await options.execute({
766
+ sql: `EXPLAIN (VERBOSE, FORMAT JSON, COSTS OFF) SELECT ${[...expected, ...actual].map((expression) => `(${expression})`).join(", ")} FROM ${table}`,
767
+ parameters: []
768
+ })).rows[0]?.["QUERY PLAN"])[0].Plan.Output;
769
+ return output.length === expected.length * 2 && output.slice(0, expected.length).every((expression, position) => expression === output[position + expected.length]);
770
+ } catch (error) {
771
+ if (error && typeof error === "object" && ["code", "errno"].some((field) => [
772
+ "42703",
773
+ "42704",
774
+ "42804",
775
+ "42846",
776
+ "42883",
777
+ "22P02",
778
+ "42601"
779
+ ].includes(String(error[field])))) return false;
780
+ throw error;
781
+ }
782
+ };
783
+ //#endregion
784
+ //#region src/migrations/drift-constraints.ts
785
+ const constraintDrift = async (table, catalog, options) => {
786
+ const findings = [];
787
+ const constraints = [
788
+ ...table.primaryKey.length ? [{
789
+ name: objectName(table.name, "pkey"),
790
+ kind: "p",
791
+ columns: table.primaryKey
792
+ }] : [],
793
+ ...table.columns.flatMap((column) => [...column.unique ? [{
794
+ name: objectName(table.name, column.name, "key"),
795
+ kind: "u",
796
+ columns: [column.name]
797
+ }] : [], ...column.references ? [{
798
+ name: objectName(table.name, column.name, "fkey"),
799
+ kind: "f",
800
+ columns: [column.name],
801
+ reference: column.references
802
+ }] : []]),
803
+ ...(table.checks ?? []).map((check) => ({
804
+ name: check.sqlName,
805
+ kind: "c",
806
+ expression: check.expression
807
+ }))
808
+ ];
809
+ const liveConstraints = catalog.filter((constraint) => constraint.table_name === table.name);
810
+ const actions = {
811
+ "no action": "a",
812
+ restrict: "r",
813
+ cascade: "c",
814
+ "set null": "n",
815
+ "set default": "d"
816
+ };
817
+ for (const constraint of constraints) {
818
+ const live = liveConstraints.find((entry) => entry.name === constraint.name);
819
+ if (!live) {
820
+ findings.push({
821
+ kind: "missing-constraint",
822
+ table: table.name,
823
+ expected: constraint.name
824
+ });
825
+ continue;
826
+ }
827
+ if (!live.validated) findings.push({
828
+ kind: "invalid-constraint",
829
+ table: table.name,
830
+ actual: constraint.name
831
+ });
832
+ if (live.kind !== constraint.kind || live.deferrable || live.initially_deferred || constraint.kind === "c" && live.no_inherit || live.nulls_not_distinct || constraint.columns && JSON.stringify(constraint.columns) !== JSON.stringify(live.columns) || constraint.reference && (live.reference_table !== constraint.reference.table || live.reference_schema !== null || JSON.stringify(live.reference_columns) !== JSON.stringify([constraint.reference.column]) || live.on_delete !== actions[constraint.reference.onDelete] || live.on_update !== "a" || live.match !== "s") || constraint.expression && (!live.expression || !await expressionsMatch([constraint.expression], [live.expression], table.name, options))) findings.push({
833
+ kind: "constraint-mismatch",
834
+ table: table.name,
835
+ expected: constraint.name,
836
+ actual: live.definition
837
+ });
838
+ }
839
+ for (const constraint of liveConstraints) if (!constraints.some((entry) => entry.name === constraint.name)) findings.push({
840
+ kind: "extra-constraint",
841
+ table: table.name,
842
+ actual: constraint.name
843
+ });
844
+ return findings;
845
+ };
846
+ //#endregion
847
+ //#region src/migrations/drift.ts
848
+ /**
849
+ * Drift detection: compares the live catalog with the expected snapshot and reports findings by kind.
850
+ */
851
+ const indexKey = (expression) => {
852
+ const ordering = /(?:\s+(ASC|DESC))?(?:\s+NULLS\s+(FIRST|LAST))?$/i.exec(expression);
853
+ const descending = ordering[1]?.toUpperCase() === "DESC";
854
+ return {
855
+ expression: expression.slice(0, ordering.index),
856
+ descending,
857
+ nullsFirst: ordering[2] ? ordering[2].toUpperCase() === "FIRST" : descending
858
+ };
859
+ };
860
+ const typeAliases = {
861
+ int: "integer",
862
+ int4: "integer",
863
+ serial: "integer",
864
+ int8: "bigint",
865
+ bigserial: "bigint",
866
+ int2: "smallint",
867
+ bool: "boolean",
868
+ timestamptz: "timestamp with time zone",
869
+ timestamp: "timestamp without time zone",
870
+ varchar: "character varying",
871
+ float8: "double precision",
872
+ float4: "real",
873
+ time: "time without time zone",
874
+ timetz: "time with time zone"
875
+ };
876
+ /** Compare declared and catalog types after resolving aliases such as timestamptz. */
877
+ const normalizeSqlType = (sqlType) => {
878
+ const text = sqlType.trim().toLowerCase().replace(/\s+/g, " ");
879
+ if (text.endsWith("[]")) return `${normalizeSqlType(text.slice(0, -2))}[]`;
880
+ const match = /^([a-z_][a-z0-9_. ]*?)(\(.*?\))?( with(?:out)? time zone)?$/.exec(text);
881
+ if (!match) return text;
882
+ const base = `${match[1].trim()}${match[3] ?? ""}`;
883
+ const qualified = base.includes(".") ? base.slice(base.indexOf(".") + 1) : base;
884
+ return `${typeAliases[qualified] ?? qualified}${match[2]?.replace(/\s+/g, "") ?? ""}`;
885
+ };
886
+ /**
887
+ * Detect manual changes: tables, columns, types, nullability and declared indexes
888
+ * are compared between the live catalog and the expected snapshot.
889
+ */
890
+ const detectDrift = async (options) => {
891
+ const expected = "version" in options.snapshot ? parseMigrationSnapshot(options.snapshot) : migrationSnapshot(options.snapshot);
892
+ const catalog = await readCatalog(options);
893
+ const columns = catalog.columns;
894
+ const indexes = await readIndexDetails(options);
895
+ const findings = [];
896
+ const actualTables = /* @__PURE__ */ new Map();
897
+ for (const table of catalog.tables) actualTables.set(table.name, /* @__PURE__ */ new Map());
898
+ for (const row of columns) {
899
+ const table = actualTables.get(row.table_name) ?? /* @__PURE__ */ new Map();
900
+ table.set(row.column_name, {
901
+ type: row.data_type,
902
+ notNull: row.not_null
903
+ });
904
+ actualTables.set(row.table_name, table);
905
+ }
906
+ for (const table of expected.tables) {
907
+ const actual = actualTables.get(table.name);
908
+ if (!actual) {
909
+ findings.push({
910
+ kind: "missing-table",
911
+ table: table.name
912
+ });
913
+ continue;
914
+ }
915
+ for (const column of table.columns) {
916
+ const live = actual.get(column.name);
917
+ if (!live) {
918
+ findings.push({
919
+ kind: "missing-column",
920
+ table: table.name,
921
+ column: column.name
922
+ });
923
+ continue;
924
+ }
925
+ const details = catalog.columns.find((entry) => entry.table_name === table.name && entry.column_name === column.name);
926
+ const expectedType = normalizeSqlType(column.enumeration ?? column.sqlType);
927
+ const actualType = normalizeSqlType(live.type);
928
+ if (column.enumeration ? details.enum_name !== column.enumeration || details.enum_schema !== null : expectedType !== actualType) findings.push({
929
+ kind: "type-mismatch",
930
+ table: table.name,
931
+ column: column.name,
932
+ expected: expectedType,
933
+ actual: actualType
934
+ });
935
+ if (column.notNull !== live.notNull) findings.push({
936
+ kind: "nullability-mismatch",
937
+ table: table.name,
938
+ column: column.name,
939
+ expected: column.notNull ? "NOT NULL" : "NULL",
940
+ actual: live.notNull ? "NOT NULL" : "NULL"
941
+ });
942
+ if (details.identity !== (column.identity ? "a" : "")) findings.push({
943
+ kind: "identity-mismatch",
944
+ table: table.name,
945
+ column: column.name,
946
+ expected: column.identity ? "GENERATED ALWAYS" : "none",
947
+ actual: details.identity === "a" ? "GENERATED ALWAYS" : details.identity === "d" ? "GENERATED BY DEFAULT" : "none"
948
+ });
949
+ if (column.default === void 0 !== (details.default === null) || column.default !== void 0 && details.default !== null && !await expressionsMatch([`(${column.default})::${column.enumeration ? quoteIdentifier(column.enumeration) : column.sqlType}`], [`(${details.default})::${column.enumeration ? quoteIdentifier(column.enumeration) : column.sqlType}`], table.name, options)) findings.push({
950
+ kind: "default-mismatch",
951
+ table: table.name,
952
+ column: column.name,
953
+ ...column.default === void 0 ? {} : { expected: column.default },
954
+ ...details.default === null ? {} : { actual: details.default }
955
+ });
956
+ }
957
+ for (const columnName of actual.keys()) if (!table.columns.some((column) => column.name === columnName)) findings.push({
958
+ kind: "extra-column",
959
+ table: table.name,
960
+ column: columnName
961
+ });
962
+ const liveIndexes = indexes.filter((row) => row.table_name === table.name);
963
+ for (const index of catalog.indexes.filter((index) => index.table_name === table.name && (!index.valid || !index.ready))) findings.push({
964
+ kind: "invalid-index",
965
+ table: table.name,
966
+ actual: index.name
967
+ });
968
+ findings.push(...await constraintDrift(table, catalog.constraints, options));
969
+ for (const definition of table.indexes) {
970
+ const live = liveIndexes.find((row) => row.index_name === definition.sqlName);
971
+ if (!live) {
972
+ findings.push({
973
+ kind: "missing-index",
974
+ table: table.name,
975
+ expected: definition.sqlName
976
+ });
977
+ continue;
978
+ }
979
+ const declaredKeys = definition.keys.map(indexKey);
980
+ if (definition.unique !== live.is_unique || live.nulls_not_distinct || definition.method !== live.method || declaredKeys.length !== live.keys.length || definition.include.length !== live.included.length || declaredKeys.some((_key, position) => (definition.opclasses?.[position] ?? null) !== (live.opclasses[position] ?? null)) || !sameStorage(definition.with, live.reloptions) || declaredKeys.some((key, position) => key.descending !== !!(live.options[position] & 1) || key.nullsFirst !== !!(live.options[position] & 2)) || !await expressionsMatch([
981
+ ...declaredKeys.map((key) => key.expression),
982
+ ...definition.include,
983
+ definition.where ?? "TRUE"
984
+ ], [
985
+ ...live.keys,
986
+ ...live.included,
987
+ live.predicate ?? "TRUE"
988
+ ], table.name, options)) findings.push({
989
+ kind: "index-mismatch",
990
+ table: table.name,
991
+ expected: indexSQL(table, definition),
992
+ actual: live.definition
993
+ });
994
+ }
995
+ for (const { index_name: name } of liveIndexes) if (!(table.indexes.some((definition) => definition.sqlName === name) || catalog.indexes.some((index) => index.table_name === table.name && index.name === name && index.constraint))) findings.push({
996
+ kind: "extra-index",
997
+ table: table.name,
998
+ actual: name
999
+ });
1000
+ }
1001
+ for (const name of actualTables.keys()) if (!expected.tables.some((table) => table.name === name)) findings.push({
1002
+ kind: "extra-table",
1003
+ table: name
1004
+ });
1005
+ for (const enumeration of expected.enumerations) {
1006
+ const live = catalog.enumerations.find((entry) => entry.name === enumeration.name);
1007
+ if (!live) findings.push({
1008
+ kind: "missing-enum",
1009
+ table: enumeration.name
1010
+ });
1011
+ else if (JSON.stringify(live.values) !== JSON.stringify(enumeration.values)) findings.push({
1012
+ kind: "enum-mismatch",
1013
+ table: enumeration.name,
1014
+ expected: JSON.stringify(enumeration.values),
1015
+ actual: JSON.stringify(live.values)
1016
+ });
1017
+ }
1018
+ for (const enumeration of catalog.enumerations) if (!expected.enumerations.some((entry) => entry.name === enumeration.name)) findings.push({
1019
+ kind: "extra-enum",
1020
+ table: enumeration.name
1021
+ });
1022
+ if (expected.extensions?.length) {
1023
+ const installed = new Set((await readExtensions(options)).map((extension) => extension.name));
1024
+ for (const name of expected.extensions) if (!installed.has(name)) findings.push({
1025
+ kind: "missing-extension",
1026
+ table: name
1027
+ });
1028
+ }
1029
+ return findings;
1030
+ };
1031
+ /** `WITH (m = 16)` versus pg_class.reloptions `["m=16"]`, compared as normalized name=value sets. */
1032
+ const sameStorage = (declared, live) => {
1033
+ const normalize = (entries) => entries.map((entry) => {
1034
+ const separator = entry.indexOf("=");
1035
+ return `${entry.slice(0, separator).trim().toLowerCase()}=${entry.slice(separator + 1).trim().replace(/^'(.*)'$/, "$1")}`;
1036
+ }).sort();
1037
+ const expected = normalize(Object.entries(declared ?? {}).map(([name, value]) => `${name}=${value}`));
1038
+ const actual = normalize(live ?? []);
1039
+ return JSON.stringify(expected) === JSON.stringify(actual);
1040
+ };
1041
+ const formatDriftFindings = (findings) => findings.length ? findings.map((finding) => {
1042
+ const target = `${quoteIdentifier(finding.table)}${finding.column ? `.${quoteIdentifier(finding.column)}` : ""}`;
1043
+ const details = finding.expected !== void 0 || finding.actual !== void 0 ? ` (expected ${finding.expected ?? "nothing"}, found ${finding.actual ?? "nothing"})` : "";
1044
+ return `${finding.kind.padEnd(21)} ${target}${details}`;
1045
+ }).join("\n") : "No schema drift detected.";
1046
+ //#endregion
1047
+ //#region src/migrations/execution.ts
1048
+ /**
1049
+ * Executes migration SQL: splits statements into steps, runs them in a transaction with advisory locking,
1050
+ * and wraps failures with SQLSTATE details.
1051
+ */
1052
+ const executionPlan = (migrations, direction) => {
1053
+ let group = 0;
1054
+ let previous = "";
1055
+ return migrations.map((migration) => {
1056
+ const transaction = migration.manifest.transaction ?? "batch";
1057
+ if (transaction !== "batch" || previous !== "batch") group++;
1058
+ previous = transaction;
1059
+ const statements = splitMigrationSQL(migration[direction]);
1060
+ if (transaction !== "none" && parseMigrationSQL(migration[direction]).some(({ words }) => words.includes("CONCURRENTLY") || words[0] === "VACUUM")) throw new Error(`symmetria: migration "${migration.id}" requires transaction: "none"`);
1061
+ return {
1062
+ id: migration.id,
1063
+ transaction,
1064
+ group,
1065
+ statements
1066
+ };
1067
+ });
1068
+ };
1069
+ var MigrationExecutionError = class extends Error {
1070
+ migration;
1071
+ direction;
1072
+ statement;
1073
+ sql;
1074
+ sqlState;
1075
+ constructor(migration, direction, statement, sql, cause) {
1076
+ const state = sqlState(cause);
1077
+ super(`symmetria: migration "${migration}" failed (${direction}, statement ${statement}${state ? `, SQLSTATE ${state}` : ""}): ${cause instanceof Error ? cause.message : String(cause)}\n\nSQL:\n${sql}`, { cause });
1078
+ this.name = "MigrationExecutionError";
1079
+ this.migration = migration;
1080
+ this.direction = direction;
1081
+ this.statement = statement;
1082
+ this.sql = sql;
1083
+ this.sqlState = state;
1084
+ }
1085
+ };
1086
+ const executeSQL = async (executor, sql, parameters = [], signal) => {
1087
+ signal?.throwIfAborted();
1088
+ const result = normalizeResult(await executor({
1089
+ sql,
1090
+ parameters
1091
+ }));
1092
+ signal?.throwIfAborted();
1093
+ return result;
1094
+ };
1095
+ const applyStatements = async (executor, migration, direction, options, completed) => {
1096
+ for (const [position, sql] of splitMigrationSQL(migration[direction]).entries()) {
1097
+ const event = {
1098
+ migration: migration.id,
1099
+ direction,
1100
+ statement: position + 1,
1101
+ sql
1102
+ };
1103
+ const started = performance.now();
1104
+ options.onEvent?.({
1105
+ ...event,
1106
+ type: "statement-start"
1107
+ });
1108
+ try {
1109
+ await executeSQL(executor, sql, [], options.signal);
1110
+ await completed?.(position + 1);
1111
+ } catch (cause) {
1112
+ const error = new MigrationExecutionError(migration.id, direction, position + 1, sql, cause);
1113
+ options.onEvent?.({
1114
+ ...event,
1115
+ type: "statement-error",
1116
+ durationMs: performance.now() - started,
1117
+ ...error.sqlState ? { sqlState: error.sqlState } : {}
1118
+ });
1119
+ throw error;
1120
+ }
1121
+ options.onEvent?.({
1122
+ ...event,
1123
+ type: "statement-end",
1124
+ durationMs: performance.now() - started
1125
+ });
1126
+ }
1127
+ options.signal?.throwIfAborted();
1128
+ };
1129
+ /** Session locks survive commits; transaction-only drivers retain atomic-batch support. */
1130
+ const withMigrationConnection = async (driver, lock, options, callback) => {
1131
+ const advisory = options.advisoryLockTimeoutMs ?? 1e4;
1132
+ const ddl = options.lockTimeoutMs ?? 5e3;
1133
+ const statement = options.statementTimeoutMs ?? 6e5;
1134
+ for (const value of [
1135
+ advisory,
1136
+ ddl,
1137
+ statement
1138
+ ]) if (!Number.isSafeInteger(value) || value < 0 || value > 2147483647) throw new Error("symmetria: migration timeouts must be integers between 0 and 2147483647 milliseconds");
1139
+ const run = async (session, atomic) => {
1140
+ options.signal?.throwIfAborted();
1141
+ let cancellation;
1142
+ const abort = () => {
1143
+ cancellation = session.cancel?.();
1144
+ cancellation?.catch(() => {});
1145
+ };
1146
+ options.signal?.addEventListener("abort", abort, { once: true });
1147
+ let original;
1148
+ let lockAttempted = false;
1149
+ try {
1150
+ original = (await executeSQL(session.execute, "SELECT current_setting('lock_timeout') AS lock_timeout, current_setting('statement_timeout') AS statement_timeout, current_setting('standard_conforming_strings') AS strings")).rows[0];
1151
+ const started = performance.now();
1152
+ while (true) {
1153
+ options.signal?.throwIfAborted();
1154
+ lockAttempted = true;
1155
+ if ((await executeSQL(session.execute, `SELECT pg_try_advisory_${atomic ? "xact_" : ""}lock(1937339476, hashtext($1)) AS locked`, [lock], options.signal)).rows[0]?.locked) break;
1156
+ if (performance.now() - started >= advisory) throw new Error(`symmetria: migration advisory lock timeout after ${advisory}ms`);
1157
+ await setTimeout(Math.min(50, advisory), void 0, options.signal ? { signal: options.signal } : {});
1158
+ }
1159
+ await executeSQL(session.execute, "SELECT set_config('lock_timeout', $1, $4), set_config('statement_timeout', $2, $4), set_config('standard_conforming_strings', $3, $4)", [
1160
+ `${ddl}ms`,
1161
+ `${statement}ms`,
1162
+ "on",
1163
+ atomic
1164
+ ]);
1165
+ return await callback(session, atomic);
1166
+ } finally {
1167
+ options.signal?.removeEventListener("abort", abort);
1168
+ await cancellation?.catch(() => {});
1169
+ if (!atomic) try {
1170
+ if (original) await executeSQL(session.execute, "SELECT set_config('lock_timeout', $1, false), set_config('statement_timeout', $2, false), set_config('standard_conforming_strings', $3, false)", [
1171
+ original.lock_timeout,
1172
+ original.statement_timeout,
1173
+ original.strings
1174
+ ]);
1175
+ } finally {
1176
+ if (lockAttempted) await executeSQL(session.execute, "SELECT pg_advisory_unlock(1937339476, hashtext($1))", [lock]);
1177
+ }
1178
+ }
1179
+ };
1180
+ if (driver.session) return driver.session((session) => run(session, false));
1181
+ if (!driver.transaction) throw new Error("symmetria: migrations require a transaction-capable driver");
1182
+ return driver.transaction((tx) => run({
1183
+ execute: tx.execute,
1184
+ transaction: (callback) => callback(tx)
1185
+ }, true), { isolationLevel: "read committed" });
1186
+ };
1187
+ //#endregion
1188
+ //#region src/migrations/runner.ts
1189
+ /**
1190
+ * The migrator: applies and rolls back migrations against a database, tracking status in the migrations table.
1191
+ */
1192
+ const migrator = (options) => {
1193
+ const metadataSchema = options.metadataSchema ?? "public";
1194
+ const metadataTable = options.metadataTable ?? "_symmetria_migrations";
1195
+ const qualifiedName = `${quoteIdentifier(metadataSchema)}.${quoteIdentifier(metadataTable)}`;
1196
+ const lockName = `symmetria:migrations:${qualifiedName}`;
1197
+ const connection = (callback) => withMigrationConnection(options.driver, lockName, options, callback);
1198
+ const readHistory = async (execute, create) => {
1199
+ if (create) {
1200
+ if (!(await executeSQL(execute, "SELECT 1 FROM pg_namespace WHERE nspname = $1", [metadataSchema])).rows.length) await executeSQL(execute, `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)}`);
1201
+ await executeSQL(execute, `CREATE TABLE IF NOT EXISTS ${qualifiedName} (id text PRIMARY KEY, checksum text NOT NULL, snapshot_hash text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`);
1202
+ await executeSQL(execute, `ALTER TABLE ${qualifiedName} ADD COLUMN IF NOT EXISTS state text NOT NULL DEFAULT 'applied', ADD COLUMN IF NOT EXISTS direction text NOT NULL DEFAULT 'up', ADD COLUMN IF NOT EXISTS statement integer NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS error text`);
1203
+ } else if (!(await executeSQL(execute, "SELECT to_regclass($1)::text AS name", [qualifiedName])).rows[0]?.name) return [];
1204
+ return (await executeSQL(execute, `SELECT id, checksum, snapshot_hash, applied_at, to_jsonb(history)->>'state' AS state, to_jsonb(history)->>'direction' AS direction, to_jsonb(history)->>'statement' AS statement, to_jsonb(history)->>'error' AS error FROM ${qualifiedName} history ORDER BY id COLLATE "C"`)).rows.map((row) => {
1205
+ const statement = Number(row.statement ?? 0);
1206
+ if (row.state !== null && !["applied", "incomplete"].includes(String(row.state)) || row.direction !== null && !["up", "down"].includes(String(row.direction)) || !Number.isSafeInteger(statement) || statement < 0) throw new Error(`symmetria: invalid migration journal state at "${row.id}"`);
1207
+ return {
1208
+ id: String(row.id),
1209
+ checksum: String(row.checksum),
1210
+ snapshotHash: String(row.snapshot_hash),
1211
+ appliedAt: new Date(row.applied_at),
1212
+ state: row.state === "incomplete" ? "incomplete" : "applied",
1213
+ direction: row.direction === "down" ? "down" : "up",
1214
+ statement,
1215
+ ...row.error ? { error: String(row.error) } : {}
1216
+ };
1217
+ });
1218
+ };
1219
+ const inspect = async (execute, migrations, create = false, incomplete = false) => {
1220
+ const history = await readHistory(execute, create);
1221
+ for (const [position, entry] of history.entries()) {
1222
+ const migration = migrations[position];
1223
+ if (!migration || migration.id !== entry.id) throw new Error(`symmetria: applied migration "${entry.id}" is missing or out of order in the local chain`);
1224
+ if (migration.checksum !== entry.checksum || migration.manifest.after !== entry.snapshotHash) throw new Error(`symmetria: checksum mismatch for applied migration "${entry.id}"`);
1225
+ if (!incomplete && entry.state === "incomplete") throw new Error(`symmetria: migration "${entry.id}" is incomplete (${entry.direction}, ${entry.statement} confirmed statements); inspect the database and use repair`);
1226
+ if (entry.state === "incomplete" && position !== history.length - 1) throw new Error("symmetria: incomplete migration is not the last journal entry");
1227
+ }
1228
+ return history;
1229
+ };
1230
+ const targetIndex = (migrations, to) => {
1231
+ const target = to === void 0 ? migrations.length - 1 : migrations.findIndex((migration) => migration.id === to);
1232
+ if (to !== void 0 && target < 0) throw new Error(`symmetria: unknown migration target "${to}"`);
1233
+ return target;
1234
+ };
1235
+ const record = async (execute, migration, direction) => {
1236
+ if (direction === "up") await executeSQL(execute, `INSERT INTO ${qualifiedName} (id, checksum, snapshot_hash) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET state = 'applied', direction = 'up', statement = 0, error = NULL, applied_at = clock_timestamp()`, [
1237
+ migration.id,
1238
+ migration.checksum,
1239
+ migration.manifest.after
1240
+ ]);
1241
+ else await executeSQL(execute, `DELETE FROM ${qualifiedName} WHERE id = $1`, [migration.id]);
1242
+ };
1243
+ const checkBoundary = async (execute, state, target, snapshot) => {
1244
+ const hash = target < 0 ? snapshotHash(emptySnapshot()) : state.migrations[target].manifest.after;
1245
+ const expected = snapshot ?? (target < 0 ? emptySnapshot() : hash === snapshotHash(state.snapshot) ? state.snapshot : void 0);
1246
+ if (expected) {
1247
+ if (snapshotHash(expected) !== hash) throw new Error("symmetria: verification snapshot does not match the target migration hash");
1248
+ const findings = await detectDrift({
1249
+ execute,
1250
+ snapshot: expected,
1251
+ metadataSchema,
1252
+ metadataTable
1253
+ });
1254
+ if (findings.length) throw new Error(`symmetria: schema does not match the adoption/recovery target\n${formatDriftFindings(findings)}`);
1255
+ } else {
1256
+ if (!options.verificationDatabaseUrl) throw new Error("symmetria: historical verification requires verificationDatabaseUrl or a matching snapshot");
1257
+ await verifyBoundary({
1258
+ ...options,
1259
+ execute,
1260
+ state,
1261
+ target,
1262
+ url: options.verificationDatabaseUrl,
1263
+ metadataSchema,
1264
+ metadataTable
1265
+ });
1266
+ }
1267
+ };
1268
+ const run = async (session, atomic, migrations, direction) => {
1269
+ const plan = executionPlan(migrations, direction);
1270
+ if (atomic && plan.some((step) => step.transaction !== "batch")) throw new Error("symmetria: each/none migrations require a session-capable driver");
1271
+ for (let position = 0; position < migrations.length;) {
1272
+ const step = plan[position];
1273
+ if (step.transaction === "none") {
1274
+ const migration = migrations[position++];
1275
+ await session.transaction(async (tx) => {
1276
+ await readHistory(tx.execute, true);
1277
+ if (direction === "up") await executeSQL(tx.execute, `INSERT INTO ${qualifiedName} (id, checksum, snapshot_hash, state, direction) VALUES ($1, $2, $3, 'incomplete', 'up')`, [
1278
+ migration.id,
1279
+ migration.checksum,
1280
+ migration.manifest.after
1281
+ ]);
1282
+ else await executeSQL(tx.execute, `UPDATE ${qualifiedName} SET state = 'incomplete', direction = 'down', statement = 0, error = NULL WHERE id = $1`, [migration.id]);
1283
+ });
1284
+ try {
1285
+ await applyStatements(session.execute, migration, direction, options, async (statement) => {
1286
+ await executeSQL(session.execute, `UPDATE ${qualifiedName} SET statement = $2 WHERE id = $1`, [migration.id, statement]);
1287
+ });
1288
+ await record(session.execute, migration, direction);
1289
+ } catch (error) {
1290
+ await executeSQL(session.execute, `UPDATE ${qualifiedName} SET error = $2 WHERE id = $1`, [migration.id, error instanceof Error ? error.message : String(error)]);
1291
+ throw error;
1292
+ }
1293
+ } else {
1294
+ const group = [];
1295
+ while (position < plan.length && plan[position].group === step.group) group.push(migrations[position++]);
1296
+ await session.transaction(async (tx) => {
1297
+ await readHistory(tx.execute, true);
1298
+ for (const migration of group) {
1299
+ await applyStatements(tx.execute, migration, direction, options);
1300
+ await record(tx.execute, migration, direction);
1301
+ }
1302
+ options.signal?.throwIfAborted();
1303
+ }, { isolationLevel: "read committed" });
1304
+ }
1305
+ }
1306
+ return migrations.map((migration) => migration.id);
1307
+ };
1308
+ return Object.freeze({
1309
+ status: async () => {
1310
+ const { migrations } = await loadMigrationState(options.directory);
1311
+ const history = await inspect(options.driver.execute, migrations, false, true);
1312
+ return migrations.map((migration, position) => {
1313
+ const entry = history[position];
1314
+ return entry ? {
1315
+ id: migration.id,
1316
+ status: entry.state,
1317
+ appliedAt: entry.appliedAt,
1318
+ ...entry.state === "incomplete" ? {
1319
+ direction: entry.direction,
1320
+ statement: entry.statement,
1321
+ ...entry.error ? { error: entry.error } : {}
1322
+ } : {}
1323
+ } : {
1324
+ id: migration.id,
1325
+ status: "pending"
1326
+ };
1327
+ });
1328
+ },
1329
+ plan: async (settings = {}) => {
1330
+ const { migrations } = await loadMigrationState(options.directory);
1331
+ return connection(async (session) => {
1332
+ const history = await inspect(session.execute, migrations);
1333
+ const direction = settings.direction ?? "up";
1334
+ const steps = settings.steps ?? 1;
1335
+ if (direction === "down" && (!Number.isSafeInteger(steps) || steps < 1 || steps > history.length)) throw new Error("symmetria: invalid rollback steps");
1336
+ return executionPlan(direction === "up" ? migrations.slice(history.length, targetIndex(migrations, settings.to) + 1) : migrations.slice(history.length - steps, history.length).reverse(), direction);
1337
+ });
1338
+ },
1339
+ migrate: async (settings = {}) => {
1340
+ const { migrations } = await loadMigrationState(options.directory);
1341
+ const target = targetIndex(migrations, settings.to);
1342
+ return connection(async (session, atomic) => {
1343
+ const history = await inspect(session.execute, migrations);
1344
+ return run(session, atomic, migrations.slice(history.length, target + 1), "up");
1345
+ });
1346
+ },
1347
+ rollback: async (settings = {}) => {
1348
+ const steps = settings.steps ?? 1;
1349
+ if (!Number.isSafeInteger(steps) || steps < 1) throw new Error("symmetria: rollback steps must be a positive safe integer");
1350
+ const { migrations } = await loadMigrationState(options.directory);
1351
+ return connection(async (session, atomic) => {
1352
+ const history = await inspect(session.execute, migrations);
1353
+ if (!history.length) return [];
1354
+ if (steps > history.length) throw new Error("symmetria: rollback steps exceed the applied migration count");
1355
+ return run(session, atomic, migrations.slice(history.length - steps, history.length).reverse(), "down");
1356
+ });
1357
+ },
1358
+ adopt: async (settings = {}) => {
1359
+ const state = await loadMigrationState(options.directory);
1360
+ const { migrations } = state;
1361
+ return connection((session) => session.transaction(async (tx) => {
1362
+ const history = await readHistory(tx.execute, true);
1363
+ if (history.some((entry) => entry.state === "incomplete")) throw new Error("symmetria: repair incomplete migrations before adopting history");
1364
+ const latest = history.at(-1);
1365
+ let target = targetIndex(migrations, settings.to);
1366
+ if (settings.to === void 0 && latest) {
1367
+ const matching = migrations.flatMap((migration, position) => migration.manifest.after === latest.snapshotHash ? [position] : []);
1368
+ const existing = matching.find((position) => migrations[position].id === latest.id && migrations[position].checksum === latest.checksum);
1369
+ if (existing === void 0 && matching.length > 1) throw new Error("symmetria: the database snapshot matches multiple local migrations; pass { to } to choose the baseline explicitly");
1370
+ target = existing ?? matching[0] ?? -1;
1371
+ }
1372
+ if (target < 0) throw new Error("symmetria: the database snapshot matches no local migration; pass { to } to baseline it explicitly");
1373
+ await checkBoundary(tx.execute, state, target, settings.snapshot);
1374
+ await executeSQL(tx.execute, `DELETE FROM ${qualifiedName}`);
1375
+ const adopted = migrations.slice(0, target + 1);
1376
+ for (const migration of adopted) await record(tx.execute, migration, "up");
1377
+ return adopted.map((migration) => migration.id);
1378
+ }));
1379
+ },
1380
+ repair: async (settings) => {
1381
+ if (!["retry", "complete"].includes(settings.action)) throw new Error("symmetria: repair action must be retry or complete");
1382
+ const state = await loadMigrationState(options.directory);
1383
+ await connection((session) => session.transaction(async (tx) => {
1384
+ const history = await inspect(tx.execute, state.migrations, true, true);
1385
+ const entry = history.find((entry) => entry.id === settings.id);
1386
+ if (!entry || entry.state !== "incomplete" || history.at(-1) !== entry) throw new Error("symmetria: repair requires the last, incomplete migration");
1387
+ const index = state.migrations.findIndex((migration) => migration.id === entry.id);
1388
+ const applied = settings.action === "complete" === (entry.direction === "up");
1389
+ await checkBoundary(tx.execute, state, applied ? index : index - 1, settings.snapshot);
1390
+ await record(tx.execute, state.migrations[index], applied ? "up" : "down");
1391
+ }));
1392
+ }
1393
+ });
1394
+ };
1395
+ //#endregion
1396
+ //#region src/migrations/verify.ts
1397
+ /**
1398
+ * Replays migrations against a scratch database and compares the resulting catalog with the expected snapshot.
1399
+ */
1400
+ const disposableDatabase = async (url, schemaName, callback) => {
1401
+ const admin = postgres({
1402
+ url,
1403
+ max: 1
1404
+ });
1405
+ const name = `symmetria_verify_${randomUUID().replaceAll("-", "")}`;
1406
+ let created = false;
1407
+ let driver;
1408
+ try {
1409
+ await executeSQL(admin.execute, `CREATE DATABASE ${quoteIdentifier(name)} TEMPLATE template0`);
1410
+ created = true;
1411
+ const address = new URL(url);
1412
+ address.pathname = `/${name}`;
1413
+ address.searchParams.delete("options");
1414
+ driver = postgres({
1415
+ url: address.toString(),
1416
+ max: 1
1417
+ });
1418
+ if (schemaName !== "public") await executeSQL(driver.execute, `CREATE SCHEMA ${quoteIdentifier(schemaName)}`);
1419
+ await executeSQL(driver.execute, "SELECT set_config('search_path', $1, false)", [quoteIdentifier(schemaName)]);
1420
+ return await callback(driver);
1421
+ } finally {
1422
+ try {
1423
+ await driver?.close();
1424
+ } finally {
1425
+ try {
1426
+ if (created) await executeSQL(admin.execute, `DROP DATABASE ${quoteIdentifier(name)} WITH (FORCE)`);
1427
+ } finally {
1428
+ await admin.close();
1429
+ }
1430
+ }
1431
+ }
1432
+ };
1433
+ /** Catalog rows present on one side only, so a refused repair or adoption says what to reconcile. */
1434
+ const catalogDifferences = (expected, actual) => Object.keys({
1435
+ ...expected,
1436
+ ...actual
1437
+ }).sort().flatMap((section) => {
1438
+ const wanted = new Set((expected[section] ?? []).map(canonicalJSON));
1439
+ const found = new Set((actual[section] ?? []).map(canonicalJSON));
1440
+ return [...[...found].filter((row) => !wanted.has(row)).map((row) => {
1441
+ const index = JSON.parse(row);
1442
+ return section === "indexes" && index.valid === false ? ` unexpected invalid index ${index.name} (left by a failed CONCURRENTLY build; DROP INDEX CONCURRENTLY it before retrying): ${row}` : ` unexpected ${section}: ${row}`;
1443
+ }), ...[...wanted].filter((row) => !found.has(row)).map((row) => ` missing ${section}: ${row}`)];
1444
+ });
1445
+ const catalogMatches = (expected, actual, label) => {
1446
+ if (canonicalJSON(expected) !== canonicalJSON(actual)) {
1447
+ const differences = catalogDifferences(expected, actual);
1448
+ const shown = differences.slice(0, 20);
1449
+ throw new Error([
1450
+ `symmetria: ${label}: database catalog does not match the verified migration boundary`,
1451
+ ...shown,
1452
+ ...differences.length > shown.length ? [` … ${differences.length - shown.length} more`] : []
1453
+ ].join("\n"));
1454
+ }
1455
+ };
1456
+ /** Reconstruct an older boundary by replaying SQL; no historical snapshots are persisted. */
1457
+ const verifyBoundary = async (options) => {
1458
+ const schemaName = String((await executeSQL(options.execute, "SELECT current_schema() AS name")).rows[0].name);
1459
+ const actual = await readCatalog({
1460
+ ...options,
1461
+ schemaName
1462
+ });
1463
+ await disposableDatabase(options.url, schemaName, async (driver) => {
1464
+ if (options.target >= 0) await migrator({
1465
+ ...options,
1466
+ driver
1467
+ }).migrate({ to: options.state.migrations[options.target].id });
1468
+ const expected = await readCatalog({
1469
+ ...options,
1470
+ execute: driver.execute,
1471
+ schemaName
1472
+ });
1473
+ catalogMatches(expected, actual, "schema does not match the adoption/recovery target");
1474
+ });
1475
+ };
1476
+ /** Exercise fresh installation, populated upgrades, rollback and reapplication on real PostgreSQL. */
1477
+ const verifyMigrations = async (options) => {
1478
+ const state = await loadMigrationState(options.directory);
1479
+ const schemaName = options.schemaName ?? "public";
1480
+ const assertLatest = async (driver) => {
1481
+ const findings = await detectDrift({
1482
+ ...options,
1483
+ execute: driver.execute,
1484
+ snapshot: state.snapshot,
1485
+ schemaName
1486
+ });
1487
+ if (findings.length) throw new Error(`symmetria: verified SQL differs from the latest snapshot\n${formatDriftFindings(findings)}`);
1488
+ };
1489
+ await disposableDatabase(options.url, schemaName, async (driver) => {
1490
+ await migrator({
1491
+ ...options,
1492
+ driver
1493
+ }).migrate();
1494
+ await assertLatest(driver);
1495
+ });
1496
+ await disposableDatabase(options.url, schemaName, async (driver) => {
1497
+ const runner = migrator({
1498
+ ...options,
1499
+ driver
1500
+ });
1501
+ const catalog = () => readCatalog({
1502
+ ...options,
1503
+ execute: driver.execute,
1504
+ schemaName
1505
+ });
1506
+ for (const migration of state.migrations) {
1507
+ const before = await catalog();
1508
+ const up = {
1509
+ driver,
1510
+ migration: migration.id,
1511
+ phase: "up"
1512
+ };
1513
+ await options.beforeMigration?.(up);
1514
+ await runner.migrate({ to: migration.id });
1515
+ const after = await catalog();
1516
+ await options.afterMigration?.(up);
1517
+ const down = {
1518
+ ...up,
1519
+ phase: "down"
1520
+ };
1521
+ await options.beforeMigration?.(down);
1522
+ await runner.rollback();
1523
+ catalogMatches(before, await catalog(), `rollback of ${migration.id}`);
1524
+ await options.afterMigration?.(down);
1525
+ const reapply = {
1526
+ ...up,
1527
+ phase: "reapply"
1528
+ };
1529
+ await options.beforeMigration?.(reapply);
1530
+ await runner.migrate({ to: migration.id });
1531
+ catalogMatches(after, await catalog(), `reapplication of ${migration.id}`);
1532
+ await options.afterMigration?.(reapply);
1533
+ }
1534
+ await assertLatest(driver);
1535
+ });
1536
+ return {
1537
+ migrations: state.migrations.map((migration) => migration.id),
1538
+ verified: true
1539
+ };
1540
+ };
1541
+ //#endregion
1542
+ //#region src/migrations/config.ts
1543
+ const defineMigrationConfig = (config) => config;
1544
+ //#endregion
1545
+ //#region src/introspection/names.ts
1546
+ /**
1547
+ * Name conversions for introspection: SQL identifiers to schema keys that round-trip
1548
+ * through the assembler's snakeCase, conventional object names and source-text escaping.
1549
+ */
1550
+ /** Names the table handle resolves to its own methods before columns. */
1551
+ const RESERVED_COLUMN_KEYS = /* @__PURE__ */ new Set([
1552
+ "indexes",
1553
+ "checks",
1554
+ "primaryKey",
1555
+ "computed",
1556
+ "nullable",
1557
+ "unique",
1558
+ "index",
1559
+ "onDelete",
1560
+ "inverse"
1561
+ ]);
1562
+ const RESERVED_TABLE_KEYS = /* @__PURE__ */ new Set([
1563
+ "constructor",
1564
+ "prototype",
1565
+ "__proto__"
1566
+ ]);
1567
+ /**
1568
+ * The camelCase key whose snake_case form is exactly `sqlName`, or undefined when
1569
+ * no key can produce that SQL name (uppercase letters, leading/trailing or doubled
1570
+ * underscores, digits after an underscore, a leading digit).
1571
+ */
1572
+ const camelKey = (sqlName) => {
1573
+ if (!/^[a-z][a-z0-9]*(_[a-z][a-z0-9]*)*$/.test(sqlName)) return;
1574
+ const key = sqlName.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
1575
+ return snakeCase(key) === sqlName ? key : void 0;
1576
+ };
1577
+ const isReservedColumnKey = (key) => RESERVED_COLUMN_KEYS.has(key);
1578
+ const isReservedTableKey = (key) => RESERVED_TABLE_KEYS.has(key);
1579
+ const pascal = (key) => key.charAt(0).toUpperCase() + key.slice(1);
1580
+ /** The constraint and index names the DSL derives for a table. */
1581
+ const conventionalNames = {
1582
+ primaryKey: (table) => objectName(table, "pkey"),
1583
+ unique: (table, column) => objectName(table, column, "key"),
1584
+ foreignKey: (table, column) => objectName(table, column, "fkey"),
1585
+ check: (table, key) => objectName(table, snakeCase(key), "check"),
1586
+ index: (table, key) => objectName(table, snakeCase(key), "idx"),
1587
+ enumeration: (table, column) => objectName(table, column, "enum")
1588
+ };
1589
+ /** Escapes text for a JavaScript template literal. */
1590
+ const escapeTemplate = (text) => text.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
1591
+ /** A double-quoted JavaScript string literal. */
1592
+ const quoteString = (text) => JSON.stringify(text);
1593
+ /** `"identifier"` in SQL, for suggested fixes. */
1594
+ const quoteSql = (identifier) => `"${identifier.replaceAll("\"", "\"\"")}"`;
1595
+ //#endregion
1596
+ //#region src/introspection/model.ts
1597
+ /**
1598
+ * Turns the live catalog into a declaration model: which builder, modifiers and
1599
+ * default each column gets, which foreign keys become relations, which tables are
1600
+ * junctions, plus a warning for everything the DSL cannot express faithfully.
1601
+ */
1602
+ const ON_DELETE = {
1603
+ c: "cascade",
1604
+ n: "setNull",
1605
+ a: "noAction"
1606
+ };
1607
+ const columnIdentifier = (name) => /^[a-z_][a-z0-9_]*$/.test(name) ? name : quoteSql(name);
1608
+ /** JavaScript value type for a PostgreSQL type without a builder, as both drivers deliver it. */
1609
+ const customValueType = (sqlType) => {
1610
+ if (/^(oid|money)$/.test(sqlType) || /^float\d$/.test(sqlType)) return "number";
1611
+ if (sqlType === "timestamp without time zone") return "Date";
1612
+ if (sqlType === "json") return "unknown";
1613
+ return "string";
1614
+ };
1615
+ const renameFix = (table, from, to) => `ALTER TABLE ${quoteSql(table)} RENAME CONSTRAINT ${quoteSql(from)} TO ${quoteSql(to)};`;
1616
+ const buildPulledSchema = (catalog) => {
1617
+ const warnings = [];
1618
+ const skippedTables = [];
1619
+ const schemaIndexes = [];
1620
+ const warn = (warning) => {
1621
+ warnings.push(warning);
1622
+ };
1623
+ const enumUsers = /* @__PURE__ */ new Map();
1624
+ for (const column of catalog.columns) if (column.enum_name) {
1625
+ const users = enumUsers.get(column.enum_name) ?? [];
1626
+ users.push(column);
1627
+ enumUsers.set(column.enum_name, users);
1628
+ }
1629
+ const enumLabels = new Map(catalog.enumerations.map((entry) => [entry.name, entry.values]));
1630
+ const ownsEnum = (column) => !!column.enum_name && column.enum_schema === null && enumUsers.get(column.enum_name)?.length === 1 && column.enum_name === conventionalNames.enumeration(column.table_name, column.column_name);
1631
+ const facts = /* @__PURE__ */ new Map();
1632
+ for (const table of catalog.tables) {
1633
+ const details = catalog.details.find((entry) => entry.name === table.name);
1634
+ if (details?.partition) {
1635
+ skippedTables.push({
1636
+ sqlName: table.name,
1637
+ reason: "partitions are declared through their parent table"
1638
+ });
1639
+ warn({
1640
+ code: "partition",
1641
+ table: table.name,
1642
+ message: `"${table.name}" is a partition; only the parent table is declared`
1643
+ });
1644
+ continue;
1645
+ }
1646
+ const key = camelKey(table.name);
1647
+ if (!key || isReservedTableKey(key)) {
1648
+ skippedTables.push({
1649
+ sqlName: table.name,
1650
+ reason: "the name cannot be produced by a schema key"
1651
+ });
1652
+ warn({
1653
+ code: "name",
1654
+ table: table.name,
1655
+ message: `"${table.name}" cannot be declared: table keys are camelCase and map to lowercase snake_case names`
1656
+ });
1657
+ continue;
1658
+ }
1659
+ const layout = catalog.layout.filter((entry) => entry.table_name === table.name);
1660
+ const columns = catalog.columns.filter((entry) => entry.table_name === table.name).sort((left, right) => {
1661
+ const position = (column) => layout.find((entry) => entry.column_name === column.column_name)?.position ?? Number.MAX_SAFE_INTEGER;
1662
+ return position(left) - position(right);
1663
+ });
1664
+ const constraints = catalog.constraints.filter((entry) => entry.table_name === table.name);
1665
+ if (details?.kind === "p") warn({
1666
+ code: "partition",
1667
+ table: table.name,
1668
+ message: `"${table.name}" is partitioned; the declaration describes a plain table`
1669
+ });
1670
+ facts.set(table.name, {
1671
+ key,
1672
+ sqlName: table.name,
1673
+ columns,
1674
+ generated: new Set(layout.filter((entry) => entry.generated !== "").map((entry) => entry.column_name)),
1675
+ constraints,
1676
+ indexes: catalog.indexDetails.filter((entry) => entry.table_name === table.name),
1677
+ primaryKey: constraints.find((entry) => entry.kind === "p"),
1678
+ references: /* @__PURE__ */ new Map(),
1679
+ junction: false
1680
+ });
1681
+ }
1682
+ for (const table of facts.values()) {
1683
+ const columnKeys = new Set(table.columns.map((column) => camelKey(column.column_name)));
1684
+ for (const constraint of table.constraints.filter((entry) => entry.kind === "f")) {
1685
+ const reason = (() => {
1686
+ const [columnName] = constraint.columns;
1687
+ const column = table.columns.find((entry) => entry.column_name === columnName);
1688
+ if (constraint.columns.length !== 1 || !column) return "composite foreign keys are not supported";
1689
+ if (constraint.reference_schema !== null) return "references a table in another schema";
1690
+ if (constraint.on_update !== "a") return "ON UPDATE actions are not supported";
1691
+ if (constraint.match !== "s") return "MATCH FULL / PARTIAL are not supported";
1692
+ if (constraint.deferrable) return "deferrable constraints are not supported";
1693
+ if (!constraint.validated) return "the constraint is NOT VALID";
1694
+ if (constraint.on_delete === "d") return "ON DELETE SET DEFAULT is not supported";
1695
+ const conventional = columnName.endsWith("_id") && columnName.length > 3;
1696
+ const key = camelKey(conventional ? columnName.slice(0, -3) : columnName);
1697
+ if (!key || isReservedColumnKey(key)) return `"${columnName}" does not map to a relation key`;
1698
+ if (columnKeys.has(key) && key !== camelKey(columnName)) return `a column already uses the key "${key}"`;
1699
+ if (!conventional && columnKeys.has(`${key}Id`)) return `a column already uses the key "${key}Id"`;
1700
+ const target = facts.get(constraint.reference_table ?? "");
1701
+ if (!target) return `the referenced table "${constraint.reference_table}" is not declared`;
1702
+ const [referencedName] = constraint.reference_columns;
1703
+ const targetKey = target.primaryKey?.columns;
1704
+ const isPrimary = targetKey?.length === 1 && targetKey[0] === referencedName;
1705
+ const isUnique = target.constraints.some((entry) => entry.kind === "u" && entry.columns.length === 1 && entry.columns[0] === referencedName);
1706
+ if (!isPrimary && !isUnique) return "relations must reference a single-column primary key or UNIQUE constraint";
1707
+ const targetColumn = target.columns.find((entry) => entry.column_name === referencedName);
1708
+ if (normalizeSqlType(column.data_type) !== normalizeSqlType(targetColumn.data_type)) return `its type ${column.data_type} differs from the referenced key ${targetColumn.data_type}`;
1709
+ if (column.default !== null || column.identity !== "") return "relation columns cannot carry a default";
1710
+ if (table.generated.has(columnName)) return "generated columns cannot be relations";
1711
+ table.references.set(columnName, {
1712
+ constraint,
1713
+ key,
1714
+ targetSql: target.sqlName,
1715
+ ...isPrimary ? {} : { by: camelKey(referencedName) },
1716
+ ...conventional ? {} : { column: columnName }
1717
+ });
1718
+ })();
1719
+ if (reason) warn({
1720
+ code: "foreign-key",
1721
+ table: table.sqlName,
1722
+ column: constraint.columns.join(", "),
1723
+ object: constraint.name,
1724
+ message: `foreign key "${constraint.name}" is kept as a plain column: ${reason}`
1725
+ });
1726
+ }
1727
+ }
1728
+ for (const table of facts.values()) {
1729
+ const keyColumns = table.primaryKey?.columns ?? [];
1730
+ table.junction = keyColumns.length === 2 && keyColumns.every((column) => table.references.has(column)) && !table.columns.some((column) => column.column_name === "id");
1731
+ }
1732
+ const relationNames = new Map([...facts.values()].map((table) => [table.sqlName, /* @__PURE__ */ new Set()]));
1733
+ const claim = (tableSql, name) => {
1734
+ const names = relationNames.get(tableSql);
1735
+ if (names.has(name)) return false;
1736
+ names.add(name);
1737
+ return true;
1738
+ };
1739
+ for (const table of facts.values()) for (const reference of table.references.values()) claim(table.sqlName, reference.key);
1740
+ for (const table of facts.values()) {
1741
+ if (!table.junction) continue;
1742
+ const [first, second] = table.primaryKey.columns.map((column) => table.references.get(column));
1743
+ const firstTarget = facts.get(first.targetSql);
1744
+ const secondTarget = facts.get(second.targetSql);
1745
+ if (first.targetSql === second.targetSql || relationNames.get(first.targetSql).has(secondTarget.key) || relationNames.get(second.targetSql).has(firstTarget.key)) {
1746
+ table.junction = false;
1747
+ warn({
1748
+ code: "foreign-key",
1749
+ table: table.sqlName,
1750
+ message: `"${table.sqlName}" links ${first.targetSql} and ${second.targetSql} but is declared as a plain table: its many-to-many relation names would clash with existing relations`
1751
+ });
1752
+ continue;
1753
+ }
1754
+ claim(first.targetSql, secondTarget.key);
1755
+ claim(second.targetSql, firstTarget.key);
1756
+ }
1757
+ const inverses = /* @__PURE__ */ new Map();
1758
+ for (const table of facts.values()) {
1759
+ const ordered = table.columns.map((column) => table.references.get(column.column_name)).filter((reference) => !!reference);
1760
+ for (const reference of ordered) {
1761
+ if (!(reference.targetSql === table.sqlName) && claim(reference.targetSql, table.key)) continue;
1762
+ let name = `${table.key}By${pascal(reference.key)}`;
1763
+ let attempt = 2;
1764
+ while (!claim(reference.targetSql, name)) {
1765
+ name = `${table.key}By${pascal(reference.key)}${attempt}`;
1766
+ attempt += 1;
1767
+ }
1768
+ inverses.set(reference, name);
1769
+ }
1770
+ }
1771
+ const tables = [];
1772
+ for (const table of facts.values()) {
1773
+ const declared = {
1774
+ key: table.key,
1775
+ sqlName: table.sqlName,
1776
+ junction: table.junction,
1777
+ members: [],
1778
+ indexes: [],
1779
+ checks: [],
1780
+ comments: [],
1781
+ skipped: []
1782
+ };
1783
+ const uniqueConstraints = table.constraints.filter((entry) => entry.kind === "u");
1784
+ const primaryKeyColumns = table.primaryKey?.columns ?? [];
1785
+ const consumedIndexes = /* @__PURE__ */ new Set();
1786
+ const uniqueFor = (columnName) => {
1787
+ const constraint = uniqueConstraints.find((entry) => entry.columns.length === 1 && entry.columns[0] === columnName);
1788
+ if (!constraint) return {
1789
+ unique: false,
1790
+ comments: []
1791
+ };
1792
+ const comments = [];
1793
+ const expected = conventionalNames.unique(table.sqlName, columnName);
1794
+ if (constraint.name !== expected) {
1795
+ comments.push(`constraint "${constraint.name}" is named "${expected}"`);
1796
+ warn({
1797
+ code: "constraint-name",
1798
+ table: table.sqlName,
1799
+ column: columnName,
1800
+ object: constraint.name,
1801
+ message: `unique constraint "${constraint.name}" will be expected as "${expected}"`,
1802
+ fix: renameFix(table.sqlName, constraint.name, expected)
1803
+ });
1804
+ }
1805
+ if (constraint.deferrable || constraint.nulls_not_distinct || !constraint.validated) {
1806
+ comments.push("declared as a plain UNIQUE constraint");
1807
+ warn({
1808
+ code: "unique-constraint",
1809
+ table: table.sqlName,
1810
+ column: columnName,
1811
+ object: constraint.name,
1812
+ message: `unique constraint "${constraint.name}" uses options the schema cannot declare (deferrable, NULLS NOT DISTINCT or NOT VALID)`
1813
+ });
1814
+ }
1815
+ return {
1816
+ unique: true,
1817
+ comments
1818
+ };
1819
+ };
1820
+ const plainIndexOn = (columnName) => table.indexes.find((entry) => entry.keys.length === 1 && entry.keys[0] === columnIdentifier(columnName) && !entry.is_unique && entry.method === "btree" && entry.predicate === null && entry.included.length === 0 && !entry.nulls_not_distinct);
1821
+ const indexFor = (columnName, unique) => {
1822
+ if (unique || primaryKeyColumns.includes(columnName)) return false;
1823
+ const candidate = plainIndexOn(columnName);
1824
+ if (candidate && candidate.index_name === conventionalNames.index(table.sqlName, columnName)) {
1825
+ consumedIndexes.add(candidate.index_name);
1826
+ return true;
1827
+ }
1828
+ return false;
1829
+ };
1830
+ for (const column of table.columns) {
1831
+ const reference = table.references.get(column.column_name);
1832
+ if (reference) {
1833
+ const { unique, comments } = uniqueFor(column.column_name);
1834
+ const member = {
1835
+ kind: "reference",
1836
+ key: reference.key,
1837
+ sqlName: column.column_name,
1838
+ target: facts.get(reference.targetSql).key,
1839
+ ...reference.by === void 0 ? {} : { by: reference.by },
1840
+ ...reference.column === void 0 ? {} : { column: reference.column },
1841
+ nullable: !column.not_null,
1842
+ unique,
1843
+ index: indexFor(column.column_name, unique),
1844
+ comments
1845
+ };
1846
+ const onDelete = ON_DELETE[reference.constraint.on_delete];
1847
+ if (onDelete) member.onDelete = onDelete;
1848
+ const inverse = inverses.get(reference);
1849
+ if (inverse) member.inverse = inverse;
1850
+ const expected = conventionalNames.foreignKey(table.sqlName, column.column_name);
1851
+ if (reference.constraint.name !== expected) {
1852
+ member.comments.push(`constraint "${reference.constraint.name}" is named "${expected}"`);
1853
+ warn({
1854
+ code: "constraint-name",
1855
+ table: table.sqlName,
1856
+ column: column.column_name,
1857
+ object: reference.constraint.name,
1858
+ message: `foreign key "${reference.constraint.name}" will be expected as "${expected}"`,
1859
+ fix: renameFix(table.sqlName, reference.constraint.name, expected)
1860
+ });
1861
+ }
1862
+ declared.members.push(member);
1863
+ continue;
1864
+ }
1865
+ const key = camelKey(column.column_name);
1866
+ if (!key) {
1867
+ declared.skipped.push({
1868
+ sqlName: column.column_name,
1869
+ dataType: column.data_type,
1870
+ reason: "the name cannot be produced by a column key"
1871
+ });
1872
+ warn({
1873
+ code: "name",
1874
+ table: table.sqlName,
1875
+ column: column.column_name,
1876
+ message: `"${table.sqlName}.${column.column_name}" cannot be declared: column keys are camelCase and map to lowercase snake_case names`
1877
+ });
1878
+ continue;
1879
+ }
1880
+ const member = columnMember(column, key, table, {
1881
+ ownsEnum,
1882
+ enumValues: (name) => enumLabels.get(name),
1883
+ warn,
1884
+ uniqueFor,
1885
+ indexFor
1886
+ });
1887
+ declared.members.push(member);
1888
+ }
1889
+ if (table.junction) {
1890
+ const keyOrder = primaryKeyColumns;
1891
+ declared.members.sort((left, right) => {
1892
+ const rank = (member) => {
1893
+ const position = keyOrder.indexOf(member.sqlName);
1894
+ return position === -1 ? keyOrder.length : position;
1895
+ };
1896
+ return rank(left) - rank(right);
1897
+ });
1898
+ const second = declared.members[1];
1899
+ second.index = false;
1900
+ const leading = table.indexes.find((entry) => entry.keys[0] === columnIdentifier(second.sqlName) || entry.keys[0]?.startsWith(`${columnIdentifier(second.sqlName)} `));
1901
+ const expected = conventionalNames.index(table.sqlName, second.sqlName);
1902
+ if (leading && plainIndexOn(second.sqlName)?.index_name === expected) consumedIndexes.add(expected);
1903
+ else if (!leading) warn({
1904
+ code: "junction-index",
1905
+ table: table.sqlName,
1906
+ column: second.sqlName,
1907
+ object: expected,
1908
+ message: `junction "${table.sqlName}" gets an automatic index "${expected}" on its second key, which the database does not have`,
1909
+ fix: `CREATE INDEX ${quoteSql(expected)} ON ${quoteSql(table.sqlName)} (${quoteSql(second.sqlName)});`
1910
+ });
1911
+ } else primaryKey(table, declared, warn);
1912
+ const indexTools = {
1913
+ table,
1914
+ declared,
1915
+ tableNames: /* @__PURE__ */ new Set([...facts.keys()]),
1916
+ warn,
1917
+ declare: (index) => {
1918
+ if (index.exact) schemaIndexes.push({
1919
+ table: declared.key,
1920
+ index: index.index
1921
+ });
1922
+ else declared.indexes.push(index.index);
1923
+ }
1924
+ };
1925
+ for (const constraint of uniqueConstraints.filter((entry) => entry.columns.length !== 1)) {
1926
+ const row = table.indexes.find((entry) => entry.index_name === constraint.name);
1927
+ const columns = constraint.columns.map(quoteSql).join(", ");
1928
+ warn({
1929
+ code: "unique-constraint",
1930
+ table: table.sqlName,
1931
+ object: constraint.name,
1932
+ message: `multi-column unique constraint "${constraint.name}" (${constraint.columns.join(", ")}) is declared as a unique index of the same name; the constraint itself stays undeclared`,
1933
+ fix: `ALTER TABLE ${quoteSql(table.sqlName)} DROP CONSTRAINT ${quoteSql(constraint.name)}; CREATE UNIQUE INDEX ${quoteSql(constraint.name)} ON ${quoteSql(table.sqlName)} (${columns});`
1934
+ });
1935
+ if (row) declareIndex(row, indexTools, { exact: true });
1936
+ }
1937
+ for (const constraint of table.constraints.filter((entry) => entry.kind === "c")) {
1938
+ const check = checkMember(table, constraint, warn);
1939
+ check.expression = interpolate(check.expression, scopeMembers(declared), declared.key).template;
1940
+ declared.checks.push(check);
1941
+ }
1942
+ for (const constraint of table.constraints.filter((entry) => entry.kind === "x")) warn({
1943
+ code: "exclusion",
1944
+ table: table.sqlName,
1945
+ object: constraint.name,
1946
+ message: `exclusion constraint "${constraint.name}" cannot be declared`
1947
+ });
1948
+ for (const index of table.indexes) {
1949
+ if (catalog.indexes.some((entry) => entry.table_name === table.sqlName && entry.name === index.index_name && entry.constraint) || consumedIndexes.has(index.index_name)) continue;
1950
+ declareIndex(index, indexTools, {});
1951
+ }
1952
+ tables.push(declared);
1953
+ }
1954
+ for (const enumeration of catalog.enumerations) {
1955
+ const users = enumUsers.get(enumeration.name) ?? [];
1956
+ if (users.length === 1 && ownsEnum(users[0])) continue;
1957
+ const [user] = users;
1958
+ const expected = users.length === 1 ? conventionalNames.enumeration(user.table_name, user.column_name) : void 0;
1959
+ warn({
1960
+ code: "enum",
1961
+ object: enumeration.name,
1962
+ ...user ? {
1963
+ table: user.table_name,
1964
+ column: user.column_name
1965
+ } : {},
1966
+ message: users.length ? users.length === 1 ? `enum "${enumeration.name}" is used through customType(); oneOf() expects it to be named "${expected}"` : `enum "${enumeration.name}" is shared by ${users.length} columns; each is declared through customType()` : `enum "${enumeration.name}" is unused and not declared`,
1967
+ ...expected ? { fix: `ALTER TYPE ${quoteSql(enumeration.name)} RENAME TO ${quoteSql(expected)};` } : {}
1968
+ });
1969
+ }
1970
+ for (const extension of catalog.extensions) if (extension.schema !== catalog.schemaName && extension.schema !== "public") warn({
1971
+ code: "extension",
1972
+ object: extension.name,
1973
+ message: `extension "${extension.name}" is installed in schema "${extension.schema}"; a migration generated from this schema would create it on the search_path instead`
1974
+ });
1975
+ return {
1976
+ schemaName: catalog.schemaName,
1977
+ tables,
1978
+ schemaIndexes,
1979
+ extensions: catalog.extensions.map((extension) => extension.name),
1980
+ skippedTables,
1981
+ warnings
1982
+ };
1983
+ };
1984
+ const columnMember = (column, key, table, tools) => {
1985
+ const comments = [];
1986
+ const { unique, comments: uniqueComments } = tools.uniqueFor(column.column_name);
1987
+ comments.push(...uniqueComments);
1988
+ const { type, array } = columnType(column, table, tools, comments);
1989
+ const member = {
1990
+ kind: "column",
1991
+ key,
1992
+ sqlName: column.column_name,
1993
+ type,
1994
+ array,
1995
+ nullable: !column.not_null,
1996
+ unique,
1997
+ index: tools.indexFor(column.column_name, unique),
1998
+ primaryKey: false,
1999
+ comments
2000
+ };
2001
+ if (isReservedColumnKey(key)) {
2002
+ comments.push(`"${key}" is also a table method; use it inside shape callbacks`);
2003
+ tools.warn({
2004
+ code: "name",
2005
+ table: table.sqlName,
2006
+ column: column.column_name,
2007
+ message: `"${table.sqlName}.${column.column_name}" shares its key with a table method; reach it inside shape callbacks`
2008
+ });
2009
+ }
2010
+ if (table.generated.has(column.column_name)) {
2011
+ comments.push("generated column; the expression is not declared");
2012
+ tools.warn({
2013
+ code: "generated-column",
2014
+ table: table.sqlName,
2015
+ column: column.column_name,
2016
+ message: `"${table.sqlName}.${column.column_name}" is a generated column; the schema declares a plain column`
2017
+ });
2018
+ return member;
2019
+ }
2020
+ const value = columnDefault(column, type, array, table, tools, comments);
2021
+ if (value) member.default = value;
2022
+ return member;
2023
+ };
2024
+ const columnType = (column, table, tools, comments) => {
2025
+ const normalized = normalizeSqlType(column.data_type);
2026
+ const array = normalized.endsWith("[]") && !normalized.endsWith("[][]");
2027
+ const base = array ? normalized.slice(0, -2) : normalized;
2028
+ if (column.enum_name && !array) {
2029
+ const values = tools.ownsEnum(column) ? tools.enumValues(column.enum_name) : void 0;
2030
+ if (values) return {
2031
+ type: {
2032
+ kind: "enum",
2033
+ values
2034
+ },
2035
+ array: false
2036
+ };
2037
+ }
2038
+ const builder = {
2039
+ integer: "int",
2040
+ bigint: "bigint",
2041
+ smallint: "smallint",
2042
+ real: "real",
2043
+ "double precision": "doublePrecision",
2044
+ text: "text",
2045
+ boolean: "bool",
2046
+ uuid: "uuid",
2047
+ "timestamp with time zone": "timestamptz",
2048
+ date: "date",
2049
+ "time without time zone": "time",
2050
+ interval: "interval",
2051
+ bytea: "bytea",
2052
+ inet: "inet",
2053
+ jsonb: "jsonb",
2054
+ tsvector: "tsvector"
2055
+ }[base];
2056
+ if (builder) return {
2057
+ type: {
2058
+ kind: "builder",
2059
+ name: builder
2060
+ },
2061
+ array
2062
+ };
2063
+ const vectorType = /^vector(?:\((\d+)\))?$/.exec(base);
2064
+ if (vectorType && !array) return {
2065
+ type: {
2066
+ kind: "vector",
2067
+ ...vectorType[1] ? { dimensions: Number(vectorType[1]) } : {}
2068
+ },
2069
+ array: false
2070
+ };
2071
+ const varchar = /^character varying(?:\((\d+)\))?$/.exec(base);
2072
+ if (varchar) return {
2073
+ type: {
2074
+ kind: "varchar",
2075
+ ...varchar[1] ? { length: Number(varchar[1]) } : {}
2076
+ },
2077
+ array
2078
+ };
2079
+ const numeric = /^numeric(?:\((\d+)(?:,(\d+))?\))?$/.exec(base);
2080
+ if (numeric) return {
2081
+ type: {
2082
+ kind: "numeric",
2083
+ ...numeric[1] ? { precision: Number(numeric[1]) } : {},
2084
+ ...numeric[2] ? { scale: Number(numeric[2]) } : {}
2085
+ },
2086
+ array
2087
+ };
2088
+ const sqlType = column.data_type;
2089
+ const enumeration = column.enum_name && !array ? tools.enumValues(column.enum_name) : void 0;
2090
+ const valueType = enumeration ? enumeration.map((value) => JSON.stringify(value)).join(" | ") : customValueType(base) + (normalized.endsWith("[]") ? "[]" : "");
2091
+ if (enumeration) comments.push(`enum "${column.enum_name}" is declared through customType()`);
2092
+ else {
2093
+ comments.push(`no builder for ${sqlType}`);
2094
+ tools.warn({
2095
+ code: "custom-type",
2096
+ table: table.sqlName,
2097
+ column: column.column_name,
2098
+ object: sqlType,
2099
+ message: `"${table.sqlName}.${column.column_name}" uses ${sqlType}, declared through customType() with driver-native values`
2100
+ });
2101
+ }
2102
+ return {
2103
+ type: {
2104
+ kind: "custom",
2105
+ sqlType,
2106
+ valueType
2107
+ },
2108
+ array: false
2109
+ };
2110
+ };
2111
+ const columnDefault = (column, type, array, table, tools, comments) => {
2112
+ const name = `${table.sqlName}.${column.column_name}`;
2113
+ if (column.identity !== "") {
2114
+ if (column.identity === "d") {
2115
+ comments.push("identity BY DEFAULT is declared as GENERATED ALWAYS");
2116
+ tools.warn({
2117
+ code: "identity-by-default",
2118
+ table: table.sqlName,
2119
+ column: column.column_name,
2120
+ message: `"${name}" is GENERATED BY DEFAULT AS IDENTITY; the schema declares GENERATED ALWAYS`,
2121
+ fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN ${quoteSql(column.column_name)} SET GENERATED ALWAYS;`
2122
+ });
2123
+ }
2124
+ if (type.kind === "builder" && (type.name === "int" || type.name === "bigint" || type.name === "smallint") && !array) return { kind: "auto" };
2125
+ comments.push("identity column");
2126
+ tools.warn({
2127
+ code: "identity-type",
2128
+ table: table.sqlName,
2129
+ column: column.column_name,
2130
+ message: `"${name}" is an identity column of type ${column.data_type}; it is declared through a raw identity default`
2131
+ });
2132
+ return { kind: "identity" };
2133
+ }
2134
+ const text = column.default;
2135
+ if (text === null) return;
2136
+ if (!array && type.kind === "builder") {
2137
+ if (type.name === "timestamptz" && text === "now()") return { kind: "now" };
2138
+ if (type.name === "uuid" && text === "gen_random_uuid()") return { kind: "v4" };
2139
+ if (type.name === "uuid" && text === "uuidv7()") return { kind: "v7" };
2140
+ }
2141
+ if (/^nextval\('[^']*'::regclass\)$/.test(text)) {
2142
+ comments.push("serial column; migrations will not create the sequence");
2143
+ tools.warn({
2144
+ code: "serial",
2145
+ table: table.sqlName,
2146
+ column: column.column_name,
2147
+ message: `"${name}" is a serial column; the schema keeps its nextval() default but migrations from this schema will not create the sequence`,
2148
+ fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN ${quoteSql(column.column_name)} DROP DEFAULT, ALTER COLUMN ${quoteSql(column.column_name)} ADD GENERATED ALWAYS AS IDENTITY;`
2149
+ });
2150
+ return {
2151
+ kind: "sql",
2152
+ sql: text
2153
+ };
2154
+ }
2155
+ const literal = !array ? literalDefault(text, type) : void 0;
2156
+ return literal ? {
2157
+ kind: "value",
2158
+ source: literal
2159
+ } : {
2160
+ kind: "sql",
2161
+ sql: text
2162
+ };
2163
+ };
2164
+ const unescapeLiteral = (text) => text.replaceAll("''", "'");
2165
+ /** JavaScript source for defaults PostgreSQL prints as simple literals. */
2166
+ const literalDefault = (text, type) => {
2167
+ const quoted = /^'((?:[^']|'')*)'::(.+)$/.exec(text);
2168
+ const integer = /^(-?\d+)$/.exec(text) ?? /^'(-?\d+)'::(integer|bigint|smallint)$/.exec(text);
2169
+ const decimal = /^(-?\d+(?:\.\d+)?)$/.exec(text) ?? /^'(-?\d+(?:\.\d+)?)'::(real|double precision|integer|numeric)$/.exec(text);
2170
+ switch (type.kind) {
2171
+ case "builder": switch (type.name) {
2172
+ case "int":
2173
+ case "smallint": return integer ? integer[1] : void 0;
2174
+ case "bigint": return integer ? `${integer[1]}n` : void 0;
2175
+ case "real":
2176
+ case "doublePrecision": return decimal ? decimal[1] : void 0;
2177
+ case "date": return quoted && quoted[2] === "date" ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2178
+ case "time": return quoted && quoted[2] === "time without time zone" ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2179
+ case "interval": return quoted && quoted[2] === "interval" ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2180
+ case "inet": return quoted && quoted[2] === "inet" ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2181
+ case "bool": return text === "true" || text === "false" ? text : void 0;
2182
+ case "text":
2183
+ case "uuid": return quoted && /^(text|character varying(\(\d+\))?|uuid|bpchar)$/.test(quoted[2]) ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2184
+ case "jsonb": return quoted && quoted[2] === "jsonb" && /^(\{\}|\[\])$/.test(quoted[1]) ? quoted[1] : void 0;
2185
+ default: return;
2186
+ }
2187
+ case "varchar": return quoted && /^(text|character varying(\(\d+\))?|bpchar)$/.test(quoted[2]) ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2188
+ case "numeric": {
2189
+ const decimal = /^(-?\d+(?:\.\d+)?)$/.exec(text) ?? /^'(-?\d+(?:\.\d+)?)'::numeric(\(\d+(,\d+)?\))?$/.exec(text);
2190
+ return decimal ? JSON.stringify(decimal[1]) : void 0;
2191
+ }
2192
+ case "enum": return quoted && type.values.includes(unescapeLiteral(quoted[1])) ? JSON.stringify(unescapeLiteral(quoted[1])) : void 0;
2193
+ case "custom":
2194
+ if (type.valueType === "number") {
2195
+ const number = /^(-?\d+(?:\.\d+)?)$/.exec(text) ?? /^'(-?\d+(?:\.\d+)?)'::\w+( \w+)?$/.exec(text);
2196
+ return number ? number[1] : void 0;
2197
+ }
2198
+ if (type.valueType.startsWith("\"") && quoted) {
2199
+ const value = JSON.stringify(unescapeLiteral(quoted[1]));
2200
+ return type.valueType.split(" | ").includes(value) ? value : void 0;
2201
+ }
2202
+ return;
2203
+ }
2204
+ };
2205
+ const primaryKey = (table, declared, warn) => {
2206
+ const constraint = table.primaryKey;
2207
+ if (!constraint) {
2208
+ const id = declared.members.find((member) => member.key === "id");
2209
+ if (id?.kind === "column" && id.nullable) {
2210
+ declared.members.splice(declared.members.indexOf(id), 1);
2211
+ declared.skipped.push({
2212
+ sqlName: id.sqlName,
2213
+ dataType: table.columns.find((column) => column.column_name === id.sqlName)?.data_type ?? "",
2214
+ reason: "a nullable \"id\" without a primary key cannot be declared"
2215
+ });
2216
+ warn({
2217
+ code: "primary-key",
2218
+ table: table.sqlName,
2219
+ column: id.sqlName,
2220
+ message: `"${table.sqlName}" has no primary key and its "id" column is nullable; the column is left out because the schema would make it the key`,
2221
+ fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN "id" SET NOT NULL, ADD PRIMARY KEY ("id");`
2222
+ });
2223
+ } else if (id) warn({
2224
+ code: "primary-key",
2225
+ table: table.sqlName,
2226
+ message: `"${table.sqlName}" has no primary key, but the schema treats its "id" column as one`,
2227
+ fix: `ALTER TABLE ${quoteSql(table.sqlName)} ADD PRIMARY KEY ("id");`
2228
+ });
2229
+ else warn({
2230
+ code: "primary-key",
2231
+ table: table.sqlName,
2232
+ message: `"${table.sqlName}" has no primary key; other tables cannot reference it`
2233
+ });
2234
+ return;
2235
+ }
2236
+ const expected = conventionalNames.primaryKey(table.sqlName);
2237
+ if (constraint.name !== expected) {
2238
+ declared.comments.push(`primary key "${constraint.name}" is named "${expected}"`);
2239
+ warn({
2240
+ code: "constraint-name",
2241
+ table: table.sqlName,
2242
+ object: constraint.name,
2243
+ message: `primary key "${constraint.name}" will be expected as "${expected}"`,
2244
+ fix: renameFix(table.sqlName, constraint.name, expected)
2245
+ });
2246
+ }
2247
+ const members = constraint.columns.map((column) => declared.members.find((member) => member.sqlName === column));
2248
+ if (members.some((member) => !member)) {
2249
+ warn({
2250
+ code: "primary-key",
2251
+ table: table.sqlName,
2252
+ object: constraint.name,
2253
+ message: `primary key "${constraint.name}" includes a column the schema could not declare`
2254
+ });
2255
+ return;
2256
+ }
2257
+ const [single] = members;
2258
+ if (members.length === 1 && single.kind === "column") {
2259
+ if (single.key !== "id") single.primaryKey = true;
2260
+ return;
2261
+ }
2262
+ declared.primaryKey = members.map((member) => member.kind === "reference" ? `${member.key}Id` : member.key);
2263
+ };
2264
+ const checkMember = (table, constraint, warn) => {
2265
+ const comments = [];
2266
+ const suffix = `_check`;
2267
+ const prefix = `${table.sqlName}_`;
2268
+ let key = constraint.name.startsWith(prefix) && constraint.name.endsWith(suffix) ? camelKey(constraint.name.slice(prefix.length, -suffix.length)) : void 0;
2269
+ if (!key) {
2270
+ key = camelKey(constraint.name) ?? camelKey(constraint.name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/_(\d)/g, "$1")) ?? `check${pascal(String(table.constraints.indexOf(constraint) + 1))}`;
2271
+ const expected = conventionalNames.check(table.sqlName, key);
2272
+ comments.push(`constraint "${constraint.name}" is named "${expected}"`);
2273
+ warn({
2274
+ code: "constraint-name",
2275
+ table: table.sqlName,
2276
+ object: constraint.name,
2277
+ message: `check constraint "${constraint.name}" will be expected as "${expected}"`,
2278
+ fix: renameFix(table.sqlName, constraint.name, expected)
2279
+ });
2280
+ }
2281
+ if (constraint.no_inherit || !constraint.validated) {
2282
+ comments.push("declared as a plain CHECK constraint");
2283
+ warn({
2284
+ code: "check",
2285
+ table: table.sqlName,
2286
+ object: constraint.name,
2287
+ message: `check constraint "${constraint.name}" is NO INHERIT or NOT VALID, which the schema cannot declare`
2288
+ });
2289
+ }
2290
+ return {
2291
+ key,
2292
+ expression: constraint.expression ?? "TRUE",
2293
+ comments
2294
+ };
2295
+ };
2296
+ const INDEX_METHODS$1 = new Set(INDEX_METHODS);
2297
+ const SQL_KEYWORDS = /* @__PURE__ */ new Set([
2298
+ "and",
2299
+ "or",
2300
+ "not",
2301
+ "is",
2302
+ "null",
2303
+ "true",
2304
+ "false",
2305
+ "in",
2306
+ "like",
2307
+ "ilike",
2308
+ "between",
2309
+ "case",
2310
+ "when",
2311
+ "then",
2312
+ "else",
2313
+ "end",
2314
+ "distinct",
2315
+ "from",
2316
+ "similar",
2317
+ "to",
2318
+ "escape",
2319
+ "collate",
2320
+ "asc",
2321
+ "desc",
2322
+ "nulls",
2323
+ "first",
2324
+ "last",
2325
+ "array",
2326
+ "any",
2327
+ "all",
2328
+ "some",
2329
+ "exists",
2330
+ "cast",
2331
+ "interval",
2332
+ "current_date",
2333
+ "current_timestamp",
2334
+ "current_time",
2335
+ "localtime",
2336
+ "localtimestamp"
2337
+ ]);
2338
+ /**
2339
+ * Replaces column references in SQL text with `${table.member}` interpolations
2340
+ * and escapes the rest for a template literal. Strings, quoted identifiers,
2341
+ * function names and type names are left alone.
2342
+ */
2343
+ const interpolate = (text, members, tableKey) => {
2344
+ let template = "";
2345
+ let columns = 0;
2346
+ let position = 0;
2347
+ while (position < text.length) {
2348
+ const character = text[position];
2349
+ if (character === "'") {
2350
+ let end = position + 1;
2351
+ while (end < text.length) {
2352
+ if (text[end] === "'") {
2353
+ if (text[end + 1] === "'") {
2354
+ end += 2;
2355
+ continue;
2356
+ }
2357
+ break;
2358
+ }
2359
+ end += 1;
2360
+ }
2361
+ template += escapeTemplate(text.slice(position, end + 1));
2362
+ position = end + 1;
2363
+ continue;
2364
+ }
2365
+ const identifier = character === "\"" ? /^"((?:[^"]|"")+)"/.exec(text.slice(position)) : /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(position));
2366
+ if (!identifier) {
2367
+ template += escapeTemplate(character);
2368
+ position += 1;
2369
+ continue;
2370
+ }
2371
+ const token = identifier[0];
2372
+ const name = character === "\"" ? identifier[1].replaceAll("\"\"", "\"") : token;
2373
+ const before = text.slice(0, position);
2374
+ const after = text.slice(position + token.length);
2375
+ const member = members.get(name);
2376
+ const isFunction = /^\s*\(/.test(after);
2377
+ const isTypeName = /::\s*$/.test(before) || /\.\s*$/.test(before);
2378
+ const isKeyword = character !== "\"" && SQL_KEYWORDS.has(token.toLowerCase());
2379
+ if (member && !isFunction && !isTypeName && !isKeyword) {
2380
+ template += `\${${tableKey}.${member}}`;
2381
+ columns += 1;
2382
+ } else template += escapeTemplate(token);
2383
+ position += token.length;
2384
+ }
2385
+ return {
2386
+ template,
2387
+ columns
2388
+ };
2389
+ };
2390
+ const scopeMembers = (declared) => new Map(declared.members.map((member) => [member.sqlName, member.kind === "reference" ? `${member.key}Id` : member.key]));
2391
+ /** Declares one live index through `.indexes()` or, when its name is not derived, the schema-level `indexes` option. */
2392
+ const declareIndex = (row, tools, options) => {
2393
+ const { table, declared, warn } = tools;
2394
+ const skip = (reason) => warn({
2395
+ code: "index",
2396
+ table: table.sqlName,
2397
+ object: row.index_name,
2398
+ message: `index "${row.index_name}" is not declared: ${reason} (${row.definition})`
2399
+ });
2400
+ if (row.nulls_not_distinct) return skip("NULLS NOT DISTINCT is not supported");
2401
+ if (!INDEX_METHODS$1.has(row.method)) return skip(`unsupported access method ${row.method}`);
2402
+ const members = scopeMembers(declared);
2403
+ const comments = [];
2404
+ const keys = [];
2405
+ for (const [position, rawKey] of row.keys.entries()) {
2406
+ const bits = row.options[position] ?? 0;
2407
+ const descending = !!(bits & 1);
2408
+ const nullsFirst = !!(bits & 2);
2409
+ const text = rawKey.trim();
2410
+ const operatorClass = row.opclasses[position] ?? void 0;
2411
+ if (/\bcollate\b/i.test(text)) return skip("per-key COLLATE is not supported");
2412
+ const column = /^"((?:[^"]|"")+)"$/.exec(text)?.[1]?.replaceAll("\"\"", "\"") ?? (/^[a-z_][a-z0-9_]*$/.test(text) ? text : void 0);
2413
+ const nulls = descending && !nullsFirst ? "last" : !descending && nullsFirst ? "first" : void 0;
2414
+ if (column !== void 0) {
2415
+ const member = members.get(column);
2416
+ if (!member) return skip(`column "${column}" is not declared`);
2417
+ keys.push({
2418
+ kind: "column",
2419
+ source: member,
2420
+ descending,
2421
+ ...nulls ? { nulls } : {},
2422
+ ...operatorClass ? { opclass: operatorClass } : {}
2423
+ });
2424
+ continue;
2425
+ }
2426
+ const expression = interpolate(text, members, declared.key);
2427
+ if (!expression.columns) return skip("expression keys must reference a declared column");
2428
+ keys.push({
2429
+ kind: "expression",
2430
+ source: expression.template,
2431
+ descending,
2432
+ ...nulls ? { nulls } : {},
2433
+ ...operatorClass ? { opclass: operatorClass } : {}
2434
+ });
2435
+ }
2436
+ const include = [];
2437
+ for (const rawColumn of row.included) {
2438
+ const text = rawColumn.trim();
2439
+ const column = /^"((?:[^"]|"")+)"$/.exec(text)?.[1]?.replaceAll("\"\"", "\"") ?? text;
2440
+ const member = members.get(column);
2441
+ if (!member) return skip(`INCLUDE column "${column}" is not declared`);
2442
+ include.push(member);
2443
+ }
2444
+ const ordered = keys.some((key) => key.descending || key.nulls);
2445
+ if (row.is_unique && row.method !== "btree") return skip("unique indexes require btree");
2446
+ if ([
2447
+ "hash",
2448
+ "spgist",
2449
+ "hnsw",
2450
+ "ivfflat"
2451
+ ].includes(row.method) && keys.length !== 1) return skip(`${row.method} indexes take one key`);
2452
+ if (include.length && ![
2453
+ "btree",
2454
+ "gist",
2455
+ "spgist"
2456
+ ].includes(row.method)) return skip(`${row.method} does not support INCLUDE`);
2457
+ if (ordered && row.method !== "btree") return skip("ordered keys require btree");
2458
+ const where = row.predicate ? interpolate(row.predicate, members, declared.key).template : void 0;
2459
+ const storage = Object.fromEntries((row.reloptions ?? []).flatMap((entry) => {
2460
+ const separator = entry.indexOf("=");
2461
+ if (separator === -1) return [];
2462
+ const name = entry.slice(0, separator).trim();
2463
+ const raw = entry.slice(separator + 1).trim();
2464
+ return [[name, /^-?\d+(?:\.\d+)?$/.test(raw) ? Number(raw) : raw]];
2465
+ }));
2466
+ const index = {
2467
+ key: "",
2468
+ keys,
2469
+ unique: row.is_unique,
2470
+ method: row.method,
2471
+ include,
2472
+ ...where ? { where } : {},
2473
+ ...Object.keys(storage).length ? { with: storage } : {},
2474
+ comments
2475
+ };
2476
+ const prefix = `${table.sqlName}_`;
2477
+ const derivedKey = !options.exact && row.index_name.startsWith(prefix) && row.index_name.endsWith("_idx") ? camelKey(row.index_name.slice(prefix.length, -4)) : void 0;
2478
+ if (derivedKey && conventionalNames.index(table.sqlName, derivedKey) === row.index_name && !declared.indexes.some((entry) => entry.key === derivedKey)) {
2479
+ tools.declare({
2480
+ exact: false,
2481
+ index: {
2482
+ ...index,
2483
+ key: derivedKey
2484
+ }
2485
+ });
2486
+ return;
2487
+ }
2488
+ if (!/^[a-z_][a-z0-9_]*$/.test(row.index_name)) return skip("its name contains characters the schema cannot produce; indexes are named <table>_<key>_idx or by a lowercase schema-level key");
2489
+ if (tools.tableNames.has(row.index_name)) return skip("its name is also a table name");
2490
+ comments.push("name kept exactly");
2491
+ tools.declare({
2492
+ exact: true,
2493
+ index: {
2494
+ ...index,
2495
+ key: row.index_name
2496
+ }
2497
+ });
2498
+ };
2499
+ //#endregion
2500
+ //#region src/introspection/render.ts
2501
+ /**
2502
+ * Renders a pulled schema as TypeScript source in the keyed-callback schema() form,
2503
+ * importing only the builders it uses and marking approximations with `// pull:`.
2504
+ */
2505
+ const PASSTHROUGH = `/** Driver-native values for types without a builder; replace with real codecs when convenient. */
2506
+ const passthrough = <Value>() => ({
2507
+ encode: (value: Value): unknown => value,
2508
+ decode: (value: unknown): Value => value as Value,
2509
+ });`;
2510
+ const IMPORT_ORDER = [
2511
+ "bigint",
2512
+ "bool",
2513
+ "bytea",
2514
+ "customType",
2515
+ "date",
2516
+ "doublePrecision",
2517
+ "index",
2518
+ "inet",
2519
+ "int",
2520
+ "interval",
2521
+ "jsonb",
2522
+ "junction",
2523
+ "numeric",
2524
+ "oneOf",
2525
+ "operatorClass",
2526
+ "real",
2527
+ "schema",
2528
+ "smallint",
2529
+ "sql",
2530
+ "table",
2531
+ "text",
2532
+ "time",
2533
+ "timestamptz",
2534
+ "tsvector",
2535
+ "uuid",
2536
+ "varchar"
2537
+ ];
2538
+ const typeSource = (type, imports) => {
2539
+ switch (type.kind) {
2540
+ case "builder":
2541
+ imports.add(type.name);
2542
+ return type.name === "jsonb" ? "jsonb<unknown>()" : type.name;
2543
+ case "varchar":
2544
+ imports.add("varchar");
2545
+ return type.length === void 0 ? "varchar" : `varchar(${type.length})`;
2546
+ case "numeric": {
2547
+ imports.add("numeric");
2548
+ const arguments_ = [type.precision, type.scale].filter((part) => part !== void 0);
2549
+ return arguments_.length ? `numeric(${arguments_.join(", ")})` : "numeric";
2550
+ }
2551
+ case "enum":
2552
+ imports.add("oneOf");
2553
+ return `oneOf(${type.values.map(quoteString).join(", ")})`;
2554
+ case "vector":
2555
+ imports.add("vector");
2556
+ return `vector(${type.dimensions ?? ""})`;
2557
+ case "custom":
2558
+ imports.add("customType");
2559
+ return `customType<${type.valueType}>(${quoteString(type.sqlType)}, passthrough<${type.valueType}>())`;
2560
+ }
2561
+ };
2562
+ const columnSource = (column, imports) => {
2563
+ let source = typeSource(column.type, imports);
2564
+ if (column.array) source += ".array";
2565
+ switch (column.default?.kind) {
2566
+ case "auto":
2567
+ source += ".auto";
2568
+ break;
2569
+ case "now":
2570
+ source += ".now";
2571
+ break;
2572
+ case "v4":
2573
+ source += ".v4";
2574
+ break;
2575
+ case "v7":
2576
+ source += ".v7";
2577
+ break;
2578
+ case "identity":
2579
+ imports.add("sql");
2580
+ source += ".default(sql`identity`)";
2581
+ break;
2582
+ case "value":
2583
+ source += `.default(${column.default.source})`;
2584
+ break;
2585
+ case "sql":
2586
+ imports.add("sql");
2587
+ source += `.default(sql\`${escapeTemplate(column.default.sql)}\`)`;
2588
+ }
2589
+ if (column.nullable) source += ".nullable";
2590
+ if (column.unique) source += ".unique";
2591
+ if (column.index) source += ".index";
2592
+ if (column.primaryKey) source += ".primaryKey";
2593
+ return source;
2594
+ };
2595
+ const referenceSource = (reference) => {
2596
+ let source = reference.target;
2597
+ if (reference.by) source += `.by(${quoteString(reference.by)})`;
2598
+ if (reference.column) source += `.column(${quoteString(reference.column)})`;
2599
+ if (reference.nullable) source += ".nullable";
2600
+ if (reference.unique) source += ".unique";
2601
+ if (reference.index) source += ".index";
2602
+ if (reference.onDelete) source += `.onDelete.${reference.onDelete}`;
2603
+ if (reference.inverse) source += `.inverse(${quoteString(reference.inverse)})`;
2604
+ return source;
2605
+ };
2606
+ const comment = (notes) => notes.length ? ` // pull: ${notes.join("; ")}` : "";
2607
+ const memberLine = (member, imports) => `${member.key}: ${member.kind === "column" ? columnSource(member, imports) : referenceSource(member)},${comment(member.comments)}`;
2608
+ const keySource = (key, tableKey, imports) => {
2609
+ let source = key.kind === "column" ? `${tableKey}.${key.source}` : `sql<string>\`${key.source}\``;
2610
+ if (key.descending) source += ".descending";
2611
+ else if (key.nulls) source += ".ascending";
2612
+ if (key.nulls) source += key.nulls === "first" ? ".nullsFirst" : ".nullsLast";
2613
+ if (key.opclass) {
2614
+ imports.add("operatorClass");
2615
+ return `operatorClass(${source}, ${quoteString(key.opclass)})`;
2616
+ }
2617
+ return source;
2618
+ };
2619
+ const storageSource = (options) => `{ ${Object.entries(options).map(([name, value]) => `${/^[a-z_][a-z0-9_]*$/i.test(name) ? name : quoteString(name)}: ${typeof value === "number" ? value : quoteString(value)}`).join(", ")} }`;
2620
+ const indexSource = (index, tableKey, imports) => {
2621
+ imports.add("index");
2622
+ if (index.keys.some((key) => key.kind === "expression") || index.where) imports.add("sql");
2623
+ let source = `index(${index.keys.map((key) => keySource(key, tableKey, imports)).join(", ")})`;
2624
+ if (index.unique) source += ".unique";
2625
+ if (index.method !== "btree") source += `.using(${quoteString(index.method)})`;
2626
+ if (index.include.length) source += `.include(${index.include.map((member) => `${tableKey}.${member}`).join(", ")})`;
2627
+ if (index.with) source += `.with(${storageSource(index.with)})`;
2628
+ if (index.where) source += `.where(sql<boolean>\`${index.where}\`.is(true))`;
2629
+ return source;
2630
+ };
2631
+ const tableSource = (table, imports) => {
2632
+ const targets = [...new Set(table.members.filter((member) => member.kind === "reference").map((member) => member.target))].sort();
2633
+ const callback = targets.length > 0;
2634
+ const indent = callback ? " " : " ";
2635
+ const constructor = table.junction ? "junction" : "table";
2636
+ imports.add(constructor);
2637
+ const body = [
2638
+ ...table.comments.map((note) => `${indent}// pull: ${note}`),
2639
+ ...table.members.map((member) => `${indent}${memberLine(member, imports)}`),
2640
+ ...table.skipped.map((column) => `${indent}// ${column.sqlName} ${column.dataType}: pull: ${column.reason}`)
2641
+ ];
2642
+ const chain = [];
2643
+ if (table.primaryKey) chain.push([`.primaryKey((${table.key}) => [${table.primaryKey.map((key) => `${table.key}.${key}`).join(", ")}])`]);
2644
+ if (table.indexes.length) chain.push([
2645
+ `.indexes((${table.key}) => ({`,
2646
+ ...table.indexes.map((index) => ` ${index.key}: ${indexSource(index, table.key, imports)},${comment(index.comments)}`),
2647
+ "}))"
2648
+ ]);
2649
+ if (table.checks.length) {
2650
+ imports.add("sql");
2651
+ chain.push([
2652
+ `.checks((${table.key}) => ({`,
2653
+ ...table.checks.map((check) => ` ${check.key}: sql<boolean>\`${check.expression}\`.is(true),${comment(check.comments)}`),
2654
+ "}))"
2655
+ ]);
2656
+ }
2657
+ const chainIndent = callback ? " " : " ";
2658
+ const chainLines = chain.flatMap((link, position) => link.map((line, lineIndex) => position === chain.length - 1 && lineIndex === link.length - 1 ? `${chainIndent}${line},` : `${chainIndent}${line}`));
2659
+ const closing = chainLines.length ? [`${indent.slice(2)}})`, ...chainLines] : [`${indent.slice(2)}}),`];
2660
+ if (!callback) return [
2661
+ ` ${table.key}: ${constructor}({`,
2662
+ ...body,
2663
+ ...closing
2664
+ ];
2665
+ return [
2666
+ ` ${table.key}: ({ ${targets.join(", ")} }) =>`,
2667
+ ` ${constructor}({`,
2668
+ ...body,
2669
+ ...closing
2670
+ ];
2671
+ };
2672
+ const importLine = (names, module) => {
2673
+ const single = `import { ${names.join(", ")} } from ${quoteString(module)};`;
2674
+ return single.length <= 80 ? single : `import {\n${names.map((name) => ` ${name},`).join("\n")}\n} from ${quoteString(module)};`;
2675
+ };
2676
+ const renderSchema = (model, options = {}) => {
2677
+ const exportName = options.exportName ?? "appSchema";
2678
+ const module = options.module ?? "symmetria";
2679
+ const imports = /* @__PURE__ */ new Set(["schema"]);
2680
+ const tables = model.tables.flatMap((table) => tableSource(table, imports));
2681
+ for (const { table, index } of model.schemaIndexes) indexSource(index, table, imports);
2682
+ const passthrough = model.tables.some((table) => table.members.some((member) => member.kind === "column" && member.type.kind === "custom"));
2683
+ const header = options.header ?? [`Generated by symmetria pull from schema ${quoteString(model.schemaName)}.`, "Lines marked `pull:` are approximations; the command lists every warning."];
2684
+ const schemaIndexLines = model.schemaIndexes.map(({ table, index }) => ` ${/^[a-z_][a-z0-9_]*$/i.test(index.key) ? index.key : quoteString(index.key)}: ${indexSource(index, table, imports)},${comment(index.comments)}`);
2685
+ const optionLines = [...model.extensions.length ? [` extensions: [${model.extensions.map(quoteString).join(", ")}],`] : [], ...schemaIndexLines.length ? [
2686
+ ` indexes: ({ ${[...new Set(model.schemaIndexes.map((entry) => entry.table))].sort().join(", ")} }) => ({`,
2687
+ ...schemaIndexLines,
2688
+ " }),"
2689
+ ] : []];
2690
+ const vectorImport = imports.has("vector") ? [`import { vector } from ${quoteString(options.vectorModule ?? `${module}/vector`)};`] : [];
2691
+ return `${[
2692
+ header.map((line) => `// ${line}`).join("\n"),
2693
+ [importLine(IMPORT_ORDER.filter((name) => imports.has(name)), module), ...vectorImport].join("\n"),
2694
+ ...passthrough ? [PASSTHROUGH] : [],
2695
+ ...model.skippedTables.length ? [model.skippedTables.map((table) => `// pull: table "${table.sqlName}" skipped: ${table.reason}`).join("\n")] : [],
2696
+ optionLines.length ? `export const ${exportName} = schema(\n {\n${tables.map((line) => line ? ` ${line}` : line).join("\n")}\n },\n {\n${optionLines.join("\n")}\n },\n);` : `export const ${exportName} = schema({\n${tables.join("\n")}\n});`
2697
+ ].join("\n\n")}\n`;
2698
+ };
2699
+ //#endregion
2700
+ //#region src/introspection/index.ts
2701
+ const pullSchema = async (options) => {
2702
+ const catalog = await readPullCatalog(options);
2703
+ const model = buildPulledSchema(catalog);
2704
+ const declaredEnums = new Set(model.tables.flatMap((table) => table.members.flatMap((member) => member.kind === "column" && member.type.kind === "enum" ? [`${table.sqlName}_${member.sqlName}_enum`] : [])));
2705
+ return {
2706
+ source: renderSchema(model, options),
2707
+ schemaName: model.schemaName,
2708
+ tables: model.tables.map((table) => table.sqlName),
2709
+ enumerations: catalog.enumerations.map((entry) => entry.name).filter((name) => declaredEnums.has(name)),
2710
+ extensions: model.extensions,
2711
+ warnings: model.warnings
2712
+ };
2713
+ };
2714
+ //#endregion
2715
+ //#region src/graph/mermaid.ts
2716
+ const relationLabel = (column) => column.endsWith("_id") && column.length > 3 ? column.slice(0, -3) : column;
2717
+ /** Tables, columns and foreign-key edges of a declared schema or a migration snapshot. */
2718
+ const schemaGraph = (snapshot) => {
2719
+ const expected = "version" in snapshot ? parseMigrationSnapshot(snapshot) : migrationSnapshot(snapshot);
2720
+ const relationNames = /* @__PURE__ */ new Map();
2721
+ if (!("version" in snapshot)) for (const table of snapshot.tables) for (const relation of table.relations) {
2722
+ const column = relation.kind === "one" && !relation.reverse ? table.columns.find((entry) => entry.name === relation.foreignKey) : void 0;
2723
+ if (column) relationNames.set(`${table.sqlName}.${column.sqlName}`, relation.name);
2724
+ }
2725
+ const edges = [];
2726
+ return {
2727
+ tables: expected.tables.map((table) => {
2728
+ const primaryKey = new Set(table.primaryKey);
2729
+ const ordered = table.columns;
2730
+ const columns = ordered.map((column) => ({
2731
+ name: column.name,
2732
+ type: column.enumeration ?? column.sqlType,
2733
+ primaryKey: primaryKey.has(column.name),
2734
+ foreignKey: !!column.references,
2735
+ unique: column.unique,
2736
+ nullable: !column.notNull,
2737
+ identity: column.identity
2738
+ }));
2739
+ for (const column of ordered) if (column.references) edges.push({
2740
+ from: column.references.table,
2741
+ to: table.name,
2742
+ column: column.name,
2743
+ label: relationNames.get(`${table.name}.${column.name}`) ?? relationLabel(column.name),
2744
+ optional: !column.notNull,
2745
+ one: column.unique,
2746
+ identifying: primaryKey.has(column.name)
2747
+ });
2748
+ const keyColumns = table.columns.filter((column) => primaryKey.has(column.name));
2749
+ return {
2750
+ name: table.name,
2751
+ columns,
2752
+ junction: keyColumns.length === 2 && keyColumns.every((column) => column.references)
2753
+ };
2754
+ }),
2755
+ edges
2756
+ };
2757
+ };
2758
+ const entityName = (name) => /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name) ? name : `"${name.replaceAll("\"", "#quot;")}"`;
2759
+ /** Mermaid attribute types allow letters, digits, `_`, `-`, brackets and parentheses. */
2760
+ const attributeType = (type) => type.replace(/[^A-Za-z0-9_()[\]-]/g, "_");
2761
+ const attributeKeys = (column) => {
2762
+ const keys = [
2763
+ ...column.primaryKey ? ["PK"] : [],
2764
+ ...column.foreignKey ? ["FK"] : [],
2765
+ ...column.unique && !column.primaryKey ? ["UK"] : []
2766
+ ];
2767
+ return keys.length ? ` ${keys.join(", ")}` : "";
2768
+ };
2769
+ const attributeComment = (column) => {
2770
+ const notes = [...column.nullable ? ["nullable"] : [], ...column.identity ? ["identity"] : []];
2771
+ return notes.length ? ` "${notes.join(", ")}"` : "";
2772
+ };
2773
+ const cardinality = (edge) => {
2774
+ const parent = edge.optional ? "|o" : "||";
2775
+ const child = edge.one ? "o|" : "o{";
2776
+ return `${parent}${edge.identifying ? "--" : ".."}${child}`;
2777
+ };
2778
+ const renderMermaid = (graph, options = {}) => {
2779
+ const lines = ["erDiagram"];
2780
+ for (const table of graph.tables) {
2781
+ if (options.compact || !table.columns.length) {
2782
+ lines.push(` ${entityName(table.name)}`);
2783
+ continue;
2784
+ }
2785
+ lines.push(` ${entityName(table.name)} {`);
2786
+ for (const column of table.columns) lines.push(` ${attributeType(column.type)} ${column.name}${attributeKeys(column)}${attributeComment(column)}`);
2787
+ lines.push(" }");
2788
+ }
2789
+ if (graph.edges.length) lines.push("");
2790
+ for (const edge of graph.edges) lines.push(` ${entityName(edge.from)} ${cardinality(edge)} ${entityName(edge.to)} : ${edge.label}`);
2791
+ const diagram = `${lines.join("\n")}\n`;
2792
+ return options.fenced ? `\`\`\`mermaid\n${diagram}\`\`\`\n` : diagram;
2793
+ };
2794
+ //#endregion
2795
+ export { formatLintFindings as _, verifyMigrations as a, detectDrift as c, lintMigrationSQL as d, generateMigration as f, recoverMigrationFiles as g, squashMigrations as h, defineMigrationConfig as i, formatDriftFindings as l, loadMigrations as m, schemaGraph as n, migrator as o, loadMigrationState as p, pullSchema as r, MigrationExecutionError as s, renderMermaid as t, normalizeSqlType as u, lintMigration as v };
2796
+
2797
+ //# sourceMappingURL=src-C2mBlLSB.js.map