@prisma-next/sql-schema-ir 0.14.0-dev.8 → 0.14.0-dev.81

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,668 @@
1
+ import { IRNodeBase, freezeNode } from "@prisma-next/framework-components/ir";
2
+ import { blindCast } from "@prisma-next/utils/casts";
3
+ import { canonicalStringify } from "@prisma-next/utils/canonical-stringify";
4
+ import { ifDefined } from "@prisma-next/utils/defined";
5
+ //#region src/ir/schema-node-kinds.ts
6
+ /**
7
+ * The `nodeKind` discriminant for each relational schema-diff leaf node.
8
+ * Each node carries a unique value; the differ pairs siblings by `id`, and
9
+ * these kinds distinguish the node types that appear as `PostgresTableSchemaNode`
10
+ * children (columns, primary key, foreign keys, uniques, indexes, checks) from
11
+ * each other and from the RLS policy/role kinds a target defines separately.
12
+ */
13
+ const RelationalSchemaNodeKind = {
14
+ schema: "sql-schema",
15
+ table: "sql-table",
16
+ column: "sql-column",
17
+ columnDefault: "sql-column-default",
18
+ primaryKey: "sql-primary-key",
19
+ foreignKey: "sql-foreign-key",
20
+ unique: "sql-unique",
21
+ index: "sql-index",
22
+ check: "sql-check-constraint"
23
+ };
24
+ /**
25
+ * The one real map from a relational `nodeKind` to the framework-neutral
26
+ * {@link DiffSubjectGranularity} its diff issues carry — the SQL family's
27
+ * post-diff filters (issue category, strict-mode gating) and the framework
28
+ * aggregate's unclaimed-elements sweep key on the granularity, never on the
29
+ * `nodeKind` spelling and never on anything stamped on the node. Resolution
30
+ * is by `nodeKind` equality against this map, not a suffix string match.
31
+ * Target-specific node kinds (Postgres namespace/table/policy/role) are
32
+ * outside this family layer's vocabulary and map their own kinds directly.
33
+ */
34
+ const RELATIONAL_NODE_GRANULARITY = {
35
+ [RelationalSchemaNodeKind.schema]: "structural",
36
+ [RelationalSchemaNodeKind.table]: "entity",
37
+ [RelationalSchemaNodeKind.column]: "field",
38
+ [RelationalSchemaNodeKind.columnDefault]: "auxiliary",
39
+ [RelationalSchemaNodeKind.primaryKey]: "auxiliary",
40
+ [RelationalSchemaNodeKind.foreignKey]: "auxiliary",
41
+ [RelationalSchemaNodeKind.unique]: "auxiliary",
42
+ [RelationalSchemaNodeKind.index]: "auxiliary",
43
+ [RelationalSchemaNodeKind.check]: "auxiliary"
44
+ };
45
+ function isRelationalSchemaNodeKind(nodeKind) {
46
+ return Object.hasOwn(RELATIONAL_NODE_GRANULARITY, nodeKind);
47
+ }
48
+ /**
49
+ * Looks up the subject granularity for a relational `nodeKind`. Throws for a
50
+ * `nodeKind` outside this map (a target-specific kind, e.g. Postgres's
51
+ * namespace/table/policy/role) — those map their own kinds directly rather
52
+ * than through this family-level map.
53
+ */
54
+ function relationalNodeGranularity(nodeKind) {
55
+ if (!isRelationalSchemaNodeKind(nodeKind)) throw new Error(`relationalNodeGranularity: unrecognized relational node kind "${nodeKind}"`);
56
+ return RELATIONAL_NODE_GRANULARITY[nodeKind];
57
+ }
58
+ /**
59
+ * The one real map from a relational `nodeKind` to its storage `entityKind`
60
+ * — the same vocabulary the contract storage's `entries` dictionary keys use
61
+ * (`elementCoordinates` walks it). Only the whole-table kind has an entity of
62
+ * its own; every other relational node (a column, an index, …) is nested
63
+ * under one and maps to nothing here.
64
+ */
65
+ const RELATIONAL_NODE_ENTITY_KIND = { [RelationalSchemaNodeKind.table]: "table" };
66
+ /**
67
+ * Looks up the storage `entityKind` for a relational `nodeKind` — sibling of
68
+ * {@link relationalNodeGranularity}, resolved by `nodeKind` equality against
69
+ * {@link RELATIONAL_NODE_ENTITY_KIND}. `undefined` for a target-specific kind
70
+ * (targets map their own kinds directly) or a relational kind with no entity
71
+ * of its own.
72
+ */
73
+ function relationalNodeEntityKind(nodeKind) {
74
+ return isRelationalSchemaNodeKind(nodeKind) ? RELATIONAL_NODE_ENTITY_KIND[nodeKind] : void 0;
75
+ }
76
+ //#endregion
77
+ //#region src/ir/sql-schema-ir-node.ts
78
+ /**
79
+ * SQL Schema IR node base. Carries the family-level
80
+ * `kind = 'sql-schema-ir'` discriminator and inherits the framework's
81
+ * `freezeNode` affordance.
82
+ *
83
+ * SQL Schema IR represents the actual database state as discovered by
84
+ * introspection (the parallel to SQL Contract IR, which represents the
85
+ * desired state).
86
+ *
87
+ * The discriminator is installed as a non-enumerable own property,
88
+ * matching the SqlNode pattern. This keeps `JSON.stringify(node)`
89
+ * canonical (no `kind` field), keeps `toEqual({...})` test assertions
90
+ * against pre-lift flat shapes passing, and keeps `node.kind` readable
91
+ * for dispatch.
92
+ *
93
+ * Both `kind` and `nodeKind` are required: every concrete leaf is a node
94
+ * the generic differ can pair and compare, so every leaf must declare which
95
+ * node it is. `nodeKind` has no default here — every direct subclass sets its
96
+ * own literal value (the relational leaves via `RelationalSchemaNodeKind`,
97
+ * target concretions via their own vocabulary, e.g. `PostgresSchemaNodeKind`).
98
+ */
99
+ var SqlSchemaIRNode = class extends IRNodeBase {
100
+ constructor() {
101
+ super();
102
+ Object.defineProperty(this, "kind", {
103
+ value: "sql-schema-ir",
104
+ writable: false,
105
+ enumerable: false,
106
+ configurable: false
107
+ });
108
+ }
109
+ };
110
+ /**
111
+ * Asserts `node` matches `predicate`, narrowing its type to `T`. The one
112
+ * shared implementation every node class's `static assert` and `isEqualTo`
113
+ * reach for, instead of each hand-writing its own throw: the message names
114
+ * the class the caller expected.
115
+ */
116
+ function assertNode(node, className, predicate) {
117
+ if (node === void 0 || !predicate(node)) throw new Error(`Expected a ${className} but got nodeKind=${node?.nodeKind ?? "undefined"}`);
118
+ }
119
+ /**
120
+ * Defines a non-enumerable own property, the same treatment `kind` gets
121
+ * above: a derivation-time render-support field stays out of
122
+ * `JSON.stringify`, `toEqual({...})` structural assertions, and spreads,
123
+ * while remaining directly readable (`node.field`) for the one consumer
124
+ * that resolves it at plan time. A no-op when `value` is `undefined` — the
125
+ * property is simply absent, matching every other optional field on these
126
+ * nodes.
127
+ */
128
+ function defineNonEnumerable(target, key, value) {
129
+ if (value === void 0) return;
130
+ Object.defineProperty(target, key, {
131
+ value,
132
+ enumerable: false,
133
+ writable: false,
134
+ configurable: false
135
+ });
136
+ }
137
+ //#endregion
138
+ //#region src/ir/primary-key.ts
139
+ /**
140
+ * Primary-key Schema IR node. Mirrors the Contract IR `PrimaryKey`
141
+ * shape (same `columns` + optional `name`) so verification can compare
142
+ * intent and actual structurally. Defined here independently to avoid
143
+ * a sql-schema-ir -> sql-contract dependency.
144
+ *
145
+ * Implements `DiffableNode` so a primary key is directly a table's diff-tree
146
+ * child. `id` is a fixed sentinel — a table has at most one primary key, so
147
+ * there is never a sibling to disambiguate against. `isEqualTo` compares the
148
+ * column tuple; the PK's own `name` is a database-assigned label with no
149
+ * semantic weight, so it is not compared (mirrors the policy node's
150
+ * name-insensitivity to non-identifying detail).
151
+ */
152
+ var PrimaryKey = class PrimaryKey extends SqlSchemaIRNode {
153
+ nodeKind = RelationalSchemaNodeKind.primaryKey;
154
+ columns;
155
+ constructor(input) {
156
+ super();
157
+ this.columns = input.columns;
158
+ if (input.name !== void 0) this.name = input.name;
159
+ freezeNode(this);
160
+ }
161
+ get id() {
162
+ return "primary-key";
163
+ }
164
+ children() {
165
+ return [];
166
+ }
167
+ static is(node) {
168
+ return node.nodeKind === RelationalSchemaNodeKind.primaryKey;
169
+ }
170
+ isEqualTo(other) {
171
+ const node = blindCast(other);
172
+ assertNode(node, "PrimaryKey", PrimaryKey.is);
173
+ return this.columns.length === node.columns.length && this.columns.every((c, i) => c === node.columns[i]);
174
+ }
175
+ };
176
+ //#endregion
177
+ //#region src/ir/sql-check-constraint-ir.ts
178
+ /**
179
+ * Schema IR node for a table-level check constraint that restricts a
180
+ * column to a set of permitted values (an enum-style `IN (...)` check).
181
+ *
182
+ * Carries the **resolved values** rather than a raw SQL predicate so
183
+ * callers can compare value-sets without parsing SQL.
184
+ *
185
+ * Implements `DiffableNode` so a check constraint is directly a table's
186
+ * diff-tree child: `id` is the constraint name. `isEqualTo` compares
187
+ * `column` and the permitted-value set (order-insensitive — the database
188
+ * does not guarantee `IN (...)` ordering).
189
+ */
190
+ var SqlCheckConstraintIR = class SqlCheckConstraintIR extends SqlSchemaIRNode {
191
+ nodeKind = RelationalSchemaNodeKind.check;
192
+ name;
193
+ column;
194
+ permittedValues;
195
+ constructor(input) {
196
+ super();
197
+ this.name = input.name;
198
+ this.column = input.column;
199
+ this.permittedValues = Object.freeze([...input.permittedValues]);
200
+ freezeNode(this);
201
+ }
202
+ get id() {
203
+ return `check:${this.name}`;
204
+ }
205
+ children() {
206
+ return [];
207
+ }
208
+ static is(node) {
209
+ return node.nodeKind === RelationalSchemaNodeKind.check;
210
+ }
211
+ /**
212
+ * Compares the permitted-value sets only (unordered), matching the
213
+ * relational walk's `verifyCheckConstraints`: two checks pairing by name
214
+ * compare their value sets — the `column` field is descriptive, not part
215
+ * of the comparison, so a name-paired check with equal values verifies
216
+ * regardless of which column carries it.
217
+ */
218
+ isEqualTo(other) {
219
+ const node = blindCast(other);
220
+ assertNode(node, "SqlCheckConstraintIR", SqlCheckConstraintIR.is);
221
+ const thisValues = new Set(this.permittedValues);
222
+ const otherValues = new Set(node.permittedValues);
223
+ if (thisValues.size !== otherValues.size) return false;
224
+ return [...thisValues].every((v) => otherValues.has(v));
225
+ }
226
+ };
227
+ //#endregion
228
+ //#region src/ir/resolved-default-equality.ts
229
+ /**
230
+ * Structural equality for two resolved column defaults, ported from the
231
+ * relational walk's `columnDefaultsEqual` normalized branch: kinds must
232
+ * match; literal values are normalized (Date and temporal-typed strings to
233
+ * ISO instants) then compared canonically (JSON objects match their
234
+ * canonical string form); function expressions compare case- and
235
+ * whitespace-insensitively.
236
+ *
237
+ * `nativeType` provides the temporal-normalization context (the actual
238
+ * side's resolved native type in a diff comparison).
239
+ */
240
+ function resolvedDefaultsEqual(expected, actual, nativeType) {
241
+ if (expected.kind !== actual.kind) return false;
242
+ if (expected.kind === "literal" && actual.kind === "literal") return literalValuesEqual(normalizeLiteralValue(expected.value, nativeType), normalizeLiteralValue(actual.value, nativeType));
243
+ if (expected.kind === "function" && actual.kind === "function") return normalizeFunctionExpression(expected.expression) === normalizeFunctionExpression(actual.expression);
244
+ return false;
245
+ }
246
+ function normalizeFunctionExpression(expression) {
247
+ return expression.toLowerCase().replace(/\s+/g, "");
248
+ }
249
+ function isTemporalNativeType(nativeType) {
250
+ if (!nativeType) return false;
251
+ const normalized = nativeType.toLowerCase();
252
+ return normalized.includes("timestamp") || normalized === "date";
253
+ }
254
+ function normalizeLiteralValue(value, nativeType) {
255
+ if (value instanceof Date) return value.toISOString();
256
+ if (typeof value === "string" && isTemporalNativeType(nativeType)) {
257
+ const parsed = new Date(value);
258
+ if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
259
+ }
260
+ return value;
261
+ }
262
+ function literalValuesEqual(a, b) {
263
+ if (a === b) return true;
264
+ if (typeof a === "object" && a !== null && typeof b === "object" && b !== null) return canonicalStringify(a) === canonicalStringify(b);
265
+ if (typeof a === "object" && a !== null && typeof b === "string") try {
266
+ return canonicalStringify(a) === canonicalStringify(JSON.parse(b));
267
+ } catch {
268
+ return false;
269
+ }
270
+ if (typeof a === "string" && typeof b === "object" && b !== null) try {
271
+ return canonicalStringify(JSON.parse(a)) === canonicalStringify(b);
272
+ } catch {
273
+ return false;
274
+ }
275
+ return false;
276
+ }
277
+ //#endregion
278
+ //#region src/ir/sql-column-default-ir.ts
279
+ /**
280
+ * Schema-diff node for a column's default value. The default is the one
281
+ * column attribute with an extra/missing/drift lifecycle of its own, so it
282
+ * is a child node of the column rather than a compared attribute: an
283
+ * undeclared live default surfaces as `not-expected`, a declared default the
284
+ * database lacks as `not-found`, and a divergent value as `not-equal` — the
285
+ * three reasons cover the legacy `extra_default` / `default_missing` /
286
+ * `default_mismatch` vocabulary with no attribute inspection.
287
+ *
288
+ * `id` is a fixed sentinel — a column has at most one default. Built
289
+ * transiently by `SqlColumnIR.children()` from the column's own fields;
290
+ * never constructed by derivation or introspection directly.
291
+ */
292
+ var SqlColumnDefaultIR = class SqlColumnDefaultIR extends SqlSchemaIRNode {
293
+ nodeKind = RelationalSchemaNodeKind.columnDefault;
294
+ constructor(input) {
295
+ super();
296
+ if (input.resolved !== void 0) this.resolved = input.resolved;
297
+ if (input.raw !== void 0) this.raw = input.raw;
298
+ if (input.nativeTypeContext !== void 0) this.nativeTypeContext = input.nativeTypeContext;
299
+ defineNonEnumerable(this, "many", input.many);
300
+ freezeNode(this);
301
+ }
302
+ get id() {
303
+ return "default";
304
+ }
305
+ children() {
306
+ return [];
307
+ }
308
+ static is(node) {
309
+ return node.nodeKind === RelationalSchemaNodeKind.columnDefault;
310
+ }
311
+ /**
312
+ * Structured comparison with `this` as the expected side: both sides
313
+ * resolved compare per the relational walk's `columnDefaultsEqual`
314
+ * semantics; a declared expected default against an unparseable actual
315
+ * (raw present, no resolved parse) is a mismatch; two raw-only nodes fall
316
+ * back to raw string equality.
317
+ */
318
+ isEqualTo(other) {
319
+ const node = blindCast(other);
320
+ assertNode(node, "SqlColumnDefaultIR", SqlColumnDefaultIR.is);
321
+ if (this.resolved !== void 0 && node.resolved !== void 0) return resolvedDefaultsEqual(this.resolved, node.resolved, node.nativeTypeContext ?? this.nativeTypeContext);
322
+ if (this.resolved !== void 0 || node.resolved !== void 0) return false;
323
+ return this.raw === node.raw;
324
+ }
325
+ };
326
+ //#endregion
327
+ //#region src/ir/sql-column-ir.ts
328
+ /**
329
+ * Schema IR node for a single column on a table, as observed by
330
+ * introspection. Unlike the Contract IR `StorageColumn`, this carries
331
+ * the column's `name` (Schema IR columns are returned as arrays from
332
+ * introspection queries; the parent table re-keys them into a record
333
+ * for downstream consumers).
334
+ *
335
+ * Implements `DiffableNode` so a column is directly a table's diff-tree
336
+ * child: `id` is the column name (unique among a table's columns); `isEqualTo`
337
+ * compares this column's own attributes only — never children, since a
338
+ * column is a leaf. When both sides carry `resolvedNativeType` (stamped at
339
+ * derivation/introspection), the comparison uses the resolved values —
340
+ * resolved native type, nullability, and structured default equality per
341
+ * the relational walk's `columnDefaultsEqual` semantics, with `this` as the
342
+ * expected side. Otherwise it falls back to comparing raw fields.
343
+ */
344
+ var SqlColumnIR = class SqlColumnIR extends SqlSchemaIRNode {
345
+ nodeKind = RelationalSchemaNodeKind.column;
346
+ name;
347
+ nativeType;
348
+ nullable;
349
+ constructor(input) {
350
+ super();
351
+ this.name = input.name;
352
+ this.nativeType = input.nativeType;
353
+ this.nullable = input.nullable;
354
+ if (input.default !== void 0) this.default = input.default;
355
+ if (input.annotations !== void 0) this.annotations = input.annotations;
356
+ if (input.many !== void 0) this.many = input.many;
357
+ if (input.resolvedNativeType !== void 0) this.resolvedNativeType = input.resolvedNativeType;
358
+ if (input.resolvedDefault !== void 0) this.resolvedDefault = input.resolvedDefault;
359
+ defineNonEnumerable(this, "codecRef", input.codecRef);
360
+ defineNonEnumerable(this, "codecBaseNativeType", input.codecBaseNativeType);
361
+ defineNonEnumerable(this, "codecNamedType", input.codecNamedType);
362
+ freezeNode(this);
363
+ }
364
+ get id() {
365
+ return `column:${this.name}`;
366
+ }
367
+ /**
368
+ * The column's default, when declared/present, is the column's one child
369
+ * node — it has an extra/missing/drift lifecycle of its own, so the differ
370
+ * recurses to it rather than `isEqualTo` comparing it. Built transiently
371
+ * from this column's own fields.
372
+ */
373
+ children() {
374
+ if (this.resolvedDefault === void 0 && this.default === void 0) return [];
375
+ return [new SqlColumnDefaultIR({
376
+ ...ifDefined("resolved", this.resolvedDefault),
377
+ ...ifDefined("raw", this.default),
378
+ ...ifDefined("nativeTypeContext", this.resolvedNativeType),
379
+ ...ifDefined("many", this.many ?? this.codecRef?.many)
380
+ })];
381
+ }
382
+ static is(node) {
383
+ return node.nodeKind === RelationalSchemaNodeKind.column;
384
+ }
385
+ /**
386
+ * Compares the column's own attributes only — the default lives on the
387
+ * child node. When both sides carry `resolvedNativeType`, the resolved
388
+ * value governs (array-ness rides on its `[]` suffix); otherwise raw
389
+ * fields compare.
390
+ */
391
+ isEqualTo(other) {
392
+ const node = blindCast(other);
393
+ assertNode(node, "SqlColumnIR", SqlColumnIR.is);
394
+ if (this.resolvedNativeType !== void 0 && node.resolvedNativeType !== void 0) return this.resolvedNativeType === node.resolvedNativeType && this.nullable === node.nullable;
395
+ return this.nativeType === node.nativeType && this.nullable === node.nullable && Boolean(this.many) === Boolean(node.many);
396
+ }
397
+ };
398
+ //#endregion
399
+ //#region src/ir/sql-foreign-key-ir.ts
400
+ /**
401
+ * Schema IR node for a foreign-key constraint as observed by
402
+ * introspection. The `referencedTable` / `referencedColumns` field
403
+ * names match the introspection vocabulary (`pg_constraint.confkey`,
404
+ * etc.) and intentionally differ from the Contract IR's nested
405
+ * `references: { table, columns }` shape so that the verifier's
406
+ * structural comparison stays explicit about which side it's reading.
407
+ *
408
+ * Implements `DiffableNode` so a foreign key is directly a table's diff-tree
409
+ * child. Foreign keys are frequently unnamed (introspection may not carry a
410
+ * constraint name, and the contract side never invents one), so `id` is
411
+ * derived from the referencing/referenced coordinates rather than `name` —
412
+ * the same tuple that makes two FK constraints the same constraint. This
413
+ * also serves as the comparison key: two FKs with the same coordinates are
414
+ * paired by the differ, and `isEqualTo` then compares the remaining
415
+ * attribute — the referential actions.
416
+ */
417
+ var SqlForeignKeyIR = class SqlForeignKeyIR extends SqlSchemaIRNode {
418
+ nodeKind = RelationalSchemaNodeKind.foreignKey;
419
+ columns;
420
+ referencedTable;
421
+ referencedColumns;
422
+ constructor(input) {
423
+ super();
424
+ this.columns = input.columns;
425
+ this.referencedTable = input.referencedTable;
426
+ this.referencedColumns = input.referencedColumns;
427
+ if (input.referencedSchema !== void 0) this.referencedSchema = input.referencedSchema;
428
+ if (input.name !== void 0) this.name = input.name;
429
+ if (input.onDelete !== void 0) this.onDelete = input.onDelete;
430
+ if (input.onUpdate !== void 0) this.onUpdate = input.onUpdate;
431
+ if (input.annotations !== void 0) this.annotations = input.annotations;
432
+ const resolvedReferencedNamespace = input.resolvedReferencedNamespace ?? input.referencedSchema;
433
+ if (resolvedReferencedNamespace !== void 0) this.resolvedReferencedNamespace = resolvedReferencedNamespace;
434
+ freezeNode(this);
435
+ }
436
+ get id() {
437
+ const referencedNamespace = this.resolvedReferencedNamespace ?? "";
438
+ return `foreign-key:${this.columns.join(",")}->${referencedNamespace}.${this.referencedTable}(${this.referencedColumns.join(",")})`;
439
+ }
440
+ children() {
441
+ return [];
442
+ }
443
+ static is(node) {
444
+ return node.nodeKind === RelationalSchemaNodeKind.foreignKey;
445
+ }
446
+ /**
447
+ * Referential-action comparison with `this` as the expected side, matching
448
+ * the relational walk's `getReferentialActionMismatches`: `noAction` is the
449
+ * database default and equivalent to an undeclared action, and drift is
450
+ * flagged only when the expected side declares a (normalized) action.
451
+ */
452
+ isEqualTo(other) {
453
+ const node = blindCast(other);
454
+ assertNode(node, "SqlForeignKeyIR", SqlForeignKeyIR.is);
455
+ return referentialActionMatches(this.onDelete, node.onDelete) && referentialActionMatches(this.onUpdate, node.onUpdate);
456
+ }
457
+ };
458
+ function referentialActionMatches(expected, actual) {
459
+ const normalizedExpected = expected === "noAction" ? void 0 : expected;
460
+ if (normalizedExpected === void 0) return true;
461
+ return normalizedExpected === (actual === "noAction" ? void 0 : actual);
462
+ }
463
+ //#endregion
464
+ //#region src/ir/sql-index-ir.ts
465
+ /**
466
+ * Schema IR node for a secondary index as observed by introspection.
467
+ * Unlike the Contract IR `Index`, the Schema IR carries an explicit
468
+ * `unique` field — introspection sees the underlying index regardless
469
+ * of whether the user expressed it as `@@index` or `@@unique`, and the
470
+ * verifier needs to distinguish them when comparing to the Contract.
471
+ *
472
+ * Implements `DiffableNode` so an index is directly a table's diff-tree
473
+ * child. Indexes are frequently unnamed, so `id` is derived from the column
474
+ * tuple — the same tuple that makes two indexes the same index, so it
475
+ * doubles as the pairing key. `isEqualTo` is symmetric structural equality
476
+ * on the remaining attributes: `unique`, `type`, and `options`. A unique
477
+ * index and a non-unique index on the same columns are different objects
478
+ * and are not equal — there is no "stronger satisfies weaker".
479
+ */
480
+ var SqlIndexIR = class SqlIndexIR extends SqlSchemaIRNode {
481
+ nodeKind = RelationalSchemaNodeKind.index;
482
+ columns;
483
+ unique;
484
+ constructor(input) {
485
+ super();
486
+ this.columns = input.columns;
487
+ this.unique = input.unique;
488
+ if (input.name !== void 0) this.name = input.name;
489
+ if (input.type !== void 0) this.type = input.type;
490
+ if (input.options !== void 0) this.options = input.options;
491
+ if (input.annotations !== void 0) this.annotations = input.annotations;
492
+ freezeNode(this);
493
+ }
494
+ get id() {
495
+ return `index:${this.columns.join(",")}`;
496
+ }
497
+ children() {
498
+ return [];
499
+ }
500
+ static is(node) {
501
+ return node.nodeKind === RelationalSchemaNodeKind.index;
502
+ }
503
+ /**
504
+ * Symmetric structural equality: two paired index nodes are equal iff their
505
+ * `unique` flag, `type`, and (loosely-compared) `options` all match. There
506
+ * is no satisfaction — a unique index does not equal a non-unique index.
507
+ * `options` compares loosely (introspection stringifies reloptions); `type`
508
+ * compares strictly after the introspection-side btree→undefined
509
+ * normalization done at construction.
510
+ */
511
+ isEqualTo(other) {
512
+ const node = blindCast(other);
513
+ assertNode(node, "SqlIndexIR", SqlIndexIR.is);
514
+ return this.unique === node.unique && this.type === node.type && indexOptionsLooselyEqual(this.options, node.options);
515
+ }
516
+ };
517
+ /**
518
+ * Option-bag equality ported from the relational walk: same key set, values
519
+ * compared via `String()` coercion — Postgres introspection returns
520
+ * reloptions values as raw strings (`'70'`, `'false'`) while contract option
521
+ * leaves are typed (number, boolean, string).
522
+ */
523
+ function indexOptionsLooselyEqual(a, b) {
524
+ const aKeys = a ? Object.keys(a).sort() : [];
525
+ const bKeys = b ? Object.keys(b).sort() : [];
526
+ if (aKeys.length !== bKeys.length) return false;
527
+ for (let i = 0; i < aKeys.length; i += 1) if (aKeys[i] !== bKeys[i]) return false;
528
+ if (aKeys.length === 0) return true;
529
+ for (const key of aKeys) if (String(a?.[key]) !== String(b?.[key])) return false;
530
+ return true;
531
+ }
532
+ //#endregion
533
+ //#region src/ir/sql-unique-ir.ts
534
+ /**
535
+ * Schema IR node for a table-level unique constraint as observed by
536
+ * introspection.
537
+ *
538
+ * Implements `DiffableNode` so a unique constraint is directly a table's
539
+ * diff-tree child. Unique constraints are frequently unnamed, so `id` is
540
+ * derived from the column tuple rather than `name` — the column tuple is
541
+ * also what makes two unique constraints the same constraint, so it doubles
542
+ * as the pairing key. There are no further attributes to compare once
543
+ * columns are equal (the differ pairs on `id`), so `isEqualTo` is identity.
544
+ */
545
+ var SqlUniqueIR = class SqlUniqueIR extends SqlSchemaIRNode {
546
+ nodeKind = RelationalSchemaNodeKind.unique;
547
+ columns;
548
+ constructor(input) {
549
+ super();
550
+ this.columns = [...input.columns];
551
+ if (input.name !== void 0) this.name = input.name;
552
+ if (input.annotations !== void 0) this.annotations = input.annotations;
553
+ freezeNode(this);
554
+ }
555
+ get id() {
556
+ return `unique:${this.columns.join(",")}`;
557
+ }
558
+ children() {
559
+ return [];
560
+ }
561
+ static is(node) {
562
+ return node.nodeKind === RelationalSchemaNodeKind.unique;
563
+ }
564
+ isEqualTo(other) {
565
+ const node = blindCast(other);
566
+ assertNode(node, "SqlUniqueIR", SqlUniqueIR.is);
567
+ return this.id === node.id;
568
+ }
569
+ };
570
+ //#endregion
571
+ //#region src/ir/sql-table-ir.ts
572
+ /**
573
+ * Schema IR node for a single table as observed by introspection.
574
+ *
575
+ * Unlike the Contract IR `StorageTable`, this carries the table's
576
+ * `name` — introspection queries return tables as arrays and the
577
+ * verifier keys them into `SqlSchemaIR.tables` afterwards, so the name
578
+ * stays on the table object for downstream call sites that walk
579
+ * `Object.values(schema.tables)`.
580
+ *
581
+ * The constructor normalises nested IR-class fields so downstream
582
+ * walks see a uniform AST regardless of whether the input was a
583
+ * plain-data literal (from introspection) or already-constructed
584
+ * class instances.
585
+ *
586
+ * Implements `DiffableNode` so a flat (single-schema) tree is directly
587
+ * diffable: `id` is the table name; `isEqualTo` is identity (the table's
588
+ * structural drift is entirely expressed by its children); `children()`
589
+ * yields every column, the primary key (when present), every foreign key,
590
+ * unique, index, and check constraint — the same composition and order as
591
+ * the Postgres table node, minus policies.
592
+ */
593
+ var SqlTableIR = class extends SqlSchemaIRNode {
594
+ nodeKind = RelationalSchemaNodeKind.table;
595
+ name;
596
+ columns;
597
+ foreignKeys;
598
+ uniques;
599
+ indexes;
600
+ constructor(input) {
601
+ super();
602
+ this.name = input.name;
603
+ this.columns = Object.freeze(Object.fromEntries(Object.entries(input.columns).map(([key, col]) => [key, col instanceof SqlColumnIR ? col : new SqlColumnIR(col)])));
604
+ this.foreignKeys = Object.freeze(input.foreignKeys.map((fk) => fk instanceof SqlForeignKeyIR ? fk : new SqlForeignKeyIR(fk)));
605
+ this.uniques = Object.freeze(input.uniques.map((u) => u instanceof SqlUniqueIR ? u : new SqlUniqueIR(u)));
606
+ this.indexes = Object.freeze(input.indexes.map((i) => i instanceof SqlIndexIR ? i : new SqlIndexIR(i)));
607
+ if (input.primaryKey !== void 0) this.primaryKey = input.primaryKey instanceof PrimaryKey ? input.primaryKey : new PrimaryKey(input.primaryKey);
608
+ if (input.annotations !== void 0) this.annotations = input.annotations;
609
+ if (input.checks !== void 0 && input.checks.length > 0) this.checks = Object.freeze(input.checks.map((c) => c instanceof SqlCheckConstraintIR ? c : new SqlCheckConstraintIR(c)));
610
+ freezeNode(this);
611
+ }
612
+ get id() {
613
+ return this.name;
614
+ }
615
+ isEqualTo(other) {
616
+ return this.id === other.id;
617
+ }
618
+ children() {
619
+ return [
620
+ ...Object.values(this.columns),
621
+ ...this.primaryKey ? [this.primaryKey] : [],
622
+ ...this.foreignKeys,
623
+ ...this.uniques,
624
+ ...this.indexes,
625
+ ...this.checks ?? []
626
+ ];
627
+ }
628
+ };
629
+ //#endregion
630
+ //#region src/ir/sql-schema-ir.ts
631
+ /**
632
+ * Root Schema IR node representing the complete database schema as
633
+ * observed by introspection. Target-agnostic; used by both verifiers
634
+ * (compare against intended Contract storage) and migration planners
635
+ * (derive operations needed to reconcile).
636
+ *
637
+ * The constructor normalises nested `SqlTableIR` instances so
638
+ * downstream walks see a uniform AST regardless of whether the input
639
+ * was a plain-data literal or already-constructed class instances.
640
+ *
641
+ * Implements `DiffableNode` as the root of a flat (single-schema) diff
642
+ * tree: `id` is the fixed sentinel `'database'` (roots have no siblings),
643
+ * `isEqualTo` is identity (a container has no own attributes), and
644
+ * `children()` yields the table nodes.
645
+ */
646
+ var SqlSchemaIR = class extends SqlSchemaIRNode {
647
+ nodeKind = RelationalSchemaNodeKind.schema;
648
+ tables;
649
+ constructor(input) {
650
+ super();
651
+ this.tables = Object.freeze(Object.fromEntries(Object.entries(input.tables).map(([key, t]) => [key, t instanceof SqlTableIR ? t : new SqlTableIR(t)])));
652
+ if (input.annotations !== void 0) this.annotations = input.annotations;
653
+ freezeNode(this);
654
+ }
655
+ get id() {
656
+ return "database";
657
+ }
658
+ isEqualTo(other) {
659
+ return this.id === other.id;
660
+ }
661
+ children() {
662
+ return Object.values(this.tables);
663
+ }
664
+ };
665
+ //#endregion
666
+ export { SqlForeignKeyIR as a, SqlCheckConstraintIR as c, assertNode as d, RelationalSchemaNodeKind as f, SqlIndexIR as i, PrimaryKey as l, relationalNodeGranularity as m, SqlTableIR as n, SqlColumnIR as o, relationalNodeEntityKind as p, SqlUniqueIR as r, SqlColumnDefaultIR as s, SqlSchemaIR as t, SqlSchemaIRNode as u };
667
+
668
+ //# sourceMappingURL=types-DGBX_sNF.mjs.map