@prisma-next/family-sql 0.14.0-dev.39 → 0.14.0-dev.40

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.
Files changed (46) hide show
  1. package/dist/contract-to-schema-ir-S-evq8E6.mjs +264 -0
  2. package/dist/contract-to-schema-ir-S-evq8E6.mjs.map +1 -0
  3. package/dist/{control-adapter-B2q9WN1V.d.mts → control-adapter-DHYFuOBy.d.mts} +14 -17
  4. package/dist/{control-adapter-B2q9WN1V.d.mts.map → control-adapter-DHYFuOBy.d.mts.map} +1 -1
  5. package/dist/control-adapter.d.mts +1 -1
  6. package/dist/control.d.mts +17 -2
  7. package/dist/control.d.mts.map +1 -1
  8. package/dist/control.mjs +42 -943
  9. package/dist/control.mjs.map +1 -1
  10. package/dist/{schema-verify.d.mts → diff.d.mts} +4 -4
  11. package/dist/diff.d.mts.map +1 -0
  12. package/dist/{verify-sql-schema-CEY7b78t.mjs → diff.mjs} +154 -244
  13. package/dist/diff.mjs.map +1 -0
  14. package/dist/migration.d.mts +1 -1
  15. package/dist/psl-infer.d.mts +80 -0
  16. package/dist/psl-infer.d.mts.map +1 -0
  17. package/dist/psl-infer.mjs +334 -0
  18. package/dist/psl-infer.mjs.map +1 -0
  19. package/dist/{verify-sql-schema-B8uEjw2s.d.mts → sql-schema-diff-6z36dZt6.d.mts} +43 -4
  20. package/dist/sql-schema-diff-6z36dZt6.d.mts.map +1 -0
  21. package/dist/{types-BxsFkHYv.d.mts → types-CkOIJXxU.d.mts} +83 -16
  22. package/dist/types-CkOIJXxU.d.mts.map +1 -0
  23. package/package.json +23 -22
  24. package/src/core/control-adapter.ts +12 -24
  25. package/src/core/control-instance.ts +113 -45
  26. package/src/core/{schema-verify/verify-sql-schema.ts → diff/sql-schema-diff.ts} +196 -8
  27. package/src/core/{schema-verify → diff}/verify-helpers.ts +12 -0
  28. package/src/core/migrations/contract-to-schema-ir.ts +48 -13
  29. package/src/core/migrations/field-event-planner.ts +3 -8
  30. package/src/core/migrations/schema-differ.ts +40 -0
  31. package/src/core/migrations/types.ts +43 -2
  32. package/src/core/psl-contract-infer/printer-config.ts +0 -6
  33. package/src/exports/control.ts +1 -0
  34. package/src/exports/diff.ts +18 -0
  35. package/src/exports/psl-infer.ts +36 -0
  36. package/dist/schema-verify.d.mts.map +0 -1
  37. package/dist/schema-verify.mjs +0 -2
  38. package/dist/types-BxsFkHYv.d.mts.map +0 -1
  39. package/dist/verify-sql-schema-B8uEjw2s.d.mts.map +0 -1
  40. package/dist/verify-sql-schema-CEY7b78t.mjs.map +0 -1
  41. package/src/core/psl-contract-infer/postgres-default-mapping.ts +0 -16
  42. package/src/core/psl-contract-infer/postgres-type-map.ts +0 -157
  43. package/src/core/psl-contract-infer/sql-schema-ir-to-psl-ast.ts +0 -795
  44. package/src/exports/schema-verify.ts +0 -18
  45. /package/src/core/{schema-verify → diff}/control-verify-emit.ts +0 -0
  46. /package/src/core/{schema-verify → diff}/verifier-disposition.ts +0 -0
package/dist/control.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { i as sqlFamilyPslBlockDescriptors, n as sqlFamilyAuthoringFieldPresets, r as sqlFamilyEntityTypes, t as sqlFamilyAuthoringTypes } from "./authoring-type-constructors-CXd-8ydc.mjs";
2
2
  import { t as SqlContractSerializer } from "./sql-contract-serializer-CYtXg_zs.mjs";
3
- import { a as contractToSchemaIR, c as extractCodecControlHooks, o as detectDestructiveChanges, s as resolveValueSetValues, t as verifySqlSchema } from "./verify-sql-schema-CEY7b78t.mjs";
4
3
  import { t as collectSupportedCodecTypeIds } from "./verify-C-G0obRm.mjs";
4
+ import { a as extractCodecControlHooks, i as resolveValueSetValues, n as contractToSchemaIR, r as detectDestructiveChanges, t as contractNamespaceToSchemaIR } from "./contract-to-schema-ir-S-evq8E6.mjs";
5
5
  import { n as temporalAuthoringPresets, r as timestampNowControlDescriptor } from "./timestamp-now-generator-CloimujU.mjs";
6
6
  import { sqlEmission } from "@prisma-next/sql-contract-emitter";
7
7
  import { blindCast } from "@prisma-next/utils/casts";
@@ -12,8 +12,7 @@ import { assertDescriptorSelfConsistency } from "@prisma-next/migration-tools/sp
12
12
  import { sqlContractCanonicalizationHooks } from "@prisma-next/sql-contract/canonicalization-hooks";
13
13
  import { defaultIndexName } from "@prisma-next/sql-schema-ir/naming";
14
14
  import { ifDefined } from "@prisma-next/utils/defined";
15
- import { isStorageTable } from "@prisma-next/sql-contract/types";
16
- import { UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma-next/framework-components/psl-ast";
15
+ import { StorageTable } from "@prisma-next/sql-contract/types";
17
16
  import { notOk, ok } from "@prisma-next/utils/result";
18
17
  //#region src/core/operation-preview.ts
19
18
  function isDdlStatement(sqlStatement) {
@@ -48,921 +47,6 @@ function sqlOperationsToPreview(operations) {
48
47
  })) };
49
48
  }
50
49
  //#endregion
51
- //#region src/core/psl-contract-infer/default-mapping.ts
52
- const DEFAULT_FUNCTION_ATTRIBUTES = {
53
- "autoincrement()": "@default(autoincrement())",
54
- "now()": "@default(now())"
55
- };
56
- function mapDefault(columnDefault, options) {
57
- switch (columnDefault.kind) {
58
- case "literal": return { attribute: `@default(${formatLiteralValue(columnDefault.value)})` };
59
- case "function": {
60
- const attribute = options?.functionAttributes?.[columnDefault.expression] ?? DEFAULT_FUNCTION_ATTRIBUTES[columnDefault.expression] ?? options?.fallbackFunctionAttribute?.(columnDefault.expression);
61
- return attribute ? { attribute } : { comment: `// Raw default: ${columnDefault.expression.replace(/[\r\n]+/g, " ")}` };
62
- }
63
- }
64
- }
65
- function formatLiteralValue(value) {
66
- if (value === null) return "null";
67
- switch (typeof value) {
68
- case "boolean":
69
- case "number": return String(value);
70
- case "string": return quoteString(value);
71
- default: return quoteString(JSON.stringify(value));
72
- }
73
- }
74
- function quoteString(str) {
75
- return `"${escapeString(str)}"`;
76
- }
77
- function escapeString(str) {
78
- return JSON.stringify(str).slice(1, -1);
79
- }
80
- //#endregion
81
- //#region src/core/psl-contract-infer/name-transforms.ts
82
- const PSL_RESERVED_WORDS = new Set([
83
- "model",
84
- "enum",
85
- "types",
86
- "type",
87
- "generator",
88
- "datasource"
89
- ]);
90
- const IDENTIFIER_PART_PATTERN = /[A-Za-z0-9]+/g;
91
- function hasSeparators(input) {
92
- return /[^A-Za-z0-9]/.test(input);
93
- }
94
- function extractIdentifierParts(input) {
95
- return input.match(IDENTIFIER_PART_PATTERN) ?? [];
96
- }
97
- function createSyntheticIdentifier(input) {
98
- let hash = 2166136261;
99
- for (const char of input) {
100
- hash ^= char.codePointAt(0) ?? 0;
101
- hash = Math.imul(hash, 16777619);
102
- }
103
- return `x${(hash >>> 0).toString(16)}`;
104
- }
105
- function sanitizeIdentifierCharacters(input) {
106
- const sanitized = input.replace(/[^\w]/g, "");
107
- return sanitized.length > 0 ? sanitized : createSyntheticIdentifier(input);
108
- }
109
- function capitalize(word) {
110
- return word.charAt(0).toUpperCase() + word.slice(1);
111
- }
112
- function snakeToPascalCase(input) {
113
- const parts = extractIdentifierParts(input);
114
- if (parts.length === 0) return capitalize(sanitizeIdentifierCharacters(input));
115
- return parts.map(capitalize).join("");
116
- }
117
- function snakeToCamelCase(input) {
118
- const parts = extractIdentifierParts(input);
119
- if (parts.length === 0) return sanitizeIdentifierCharacters(input);
120
- const [firstPart = input, ...rest] = parts;
121
- return firstPart.charAt(0).toLowerCase() + firstPart.slice(1) + rest.map(capitalize).join("");
122
- }
123
- function needsEscaping(name) {
124
- return PSL_RESERVED_WORDS.has(name.toLowerCase()) || /^\d/.test(name);
125
- }
126
- function escapeName(name) {
127
- return `_${name}`;
128
- }
129
- function escapeIfNeeded(name) {
130
- return needsEscaping(name) ? escapeName(name) : name;
131
- }
132
- function toModelName(tableName) {
133
- let name;
134
- if (hasSeparators(tableName)) name = snakeToPascalCase(tableName);
135
- else name = tableName.charAt(0).toUpperCase() + tableName.slice(1);
136
- if (needsEscaping(name)) return {
137
- name: escapeName(name),
138
- map: tableName
139
- };
140
- if (name !== tableName) return {
141
- name,
142
- map: tableName
143
- };
144
- return { name };
145
- }
146
- function toFieldName(columnName) {
147
- let name;
148
- if (hasSeparators(columnName)) name = snakeToCamelCase(columnName);
149
- else name = columnName.charAt(0).toLowerCase() + columnName.slice(1);
150
- if (needsEscaping(name)) return {
151
- name: escapeName(name),
152
- map: columnName
153
- };
154
- if (name !== columnName) return {
155
- name,
156
- map: columnName
157
- };
158
- return { name };
159
- }
160
- function pluralize(word) {
161
- if (word.endsWith("s") || word.endsWith("x") || word.endsWith("z") || word.endsWith("ch") || word.endsWith("sh")) return `${word}es`;
162
- if (word.endsWith("y") && !/[aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
163
- return `${word}s`;
164
- }
165
- function deriveRelationFieldName(fkColumns, referencedTableName) {
166
- if (fkColumns.length === 1) {
167
- const [col = referencedTableName] = fkColumns;
168
- const stripped = col.replace(/_id$/i, "").replace(/Id$/, "");
169
- if (stripped.length > 0 && stripped !== col) return escapeIfNeeded(snakeToCamelCase(stripped));
170
- return escapeIfNeeded(snakeToCamelCase(referencedTableName));
171
- }
172
- return escapeIfNeeded(snakeToCamelCase(referencedTableName));
173
- }
174
- function deriveBackRelationFieldName(childModelName, isOneToOne) {
175
- const base = childModelName.charAt(0).toLowerCase() + childModelName.slice(1);
176
- return isOneToOne ? base : pluralize(base);
177
- }
178
- function toNamedTypeName(columnName) {
179
- let name;
180
- if (hasSeparators(columnName)) name = snakeToPascalCase(columnName);
181
- else name = columnName.charAt(0).toUpperCase() + columnName.slice(1);
182
- return escapeIfNeeded(name);
183
- }
184
- //#endregion
185
- //#region src/core/psl-contract-infer/postgres-default-mapping.ts
186
- const POSTGRES_FUNCTION_ATTRIBUTES = { "gen_random_uuid()": "@default(dbgenerated(\"gen_random_uuid()\"))" };
187
- function formatDbGeneratedAttribute(expression) {
188
- return `@default(dbgenerated(${JSON.stringify(expression)}))`;
189
- }
190
- function createPostgresDefaultMapping() {
191
- return {
192
- functionAttributes: POSTGRES_FUNCTION_ATTRIBUTES,
193
- fallbackFunctionAttribute: formatDbGeneratedAttribute
194
- };
195
- }
196
- //#endregion
197
- //#region src/core/psl-contract-infer/postgres-type-map.ts
198
- const POSTGRES_TO_PSL = {
199
- text: "String",
200
- bool: "Boolean",
201
- boolean: "Boolean",
202
- int4: "Int",
203
- integer: "Int",
204
- int8: "BigInt",
205
- bigint: "BigInt",
206
- float8: "Float",
207
- "double precision": "Float",
208
- numeric: "Decimal",
209
- decimal: "Decimal",
210
- timestamptz: "DateTime",
211
- "timestamp with time zone": "DateTime",
212
- jsonb: "Json",
213
- bytea: "Bytes"
214
- };
215
- const PRESERVED_NATIVE_TYPES = {
216
- "character varying": {
217
- pslType: "String",
218
- attributeName: "db.VarChar"
219
- },
220
- character: {
221
- pslType: "String",
222
- attributeName: "db.Char"
223
- },
224
- char: {
225
- pslType: "String",
226
- attributeName: "db.Char"
227
- },
228
- varchar: {
229
- pslType: "String",
230
- attributeName: "db.VarChar"
231
- },
232
- uuid: {
233
- pslType: "String",
234
- attributeName: "db.Uuid"
235
- },
236
- int2: {
237
- pslType: "Int",
238
- attributeName: "db.SmallInt"
239
- },
240
- smallint: {
241
- pslType: "Int",
242
- attributeName: "db.SmallInt"
243
- },
244
- float4: {
245
- pslType: "Float",
246
- attributeName: "db.Real"
247
- },
248
- real: {
249
- pslType: "Float",
250
- attributeName: "db.Real"
251
- },
252
- timestamp: {
253
- pslType: "DateTime",
254
- attributeName: "db.Timestamp"
255
- },
256
- "timestamp without time zone": {
257
- pslType: "DateTime",
258
- attributeName: "db.Timestamp"
259
- },
260
- date: {
261
- pslType: "DateTime",
262
- attributeName: "db.Date"
263
- },
264
- time: {
265
- pslType: "DateTime",
266
- attributeName: "db.Time"
267
- },
268
- "time without time zone": {
269
- pslType: "DateTime",
270
- attributeName: "db.Time"
271
- },
272
- timetz: {
273
- pslType: "DateTime",
274
- attributeName: "db.Timetz"
275
- },
276
- "time with time zone": {
277
- pslType: "DateTime",
278
- attributeName: "db.Timetz"
279
- },
280
- json: {
281
- pslType: "Json",
282
- attributeName: "db.Json"
283
- }
284
- };
285
- const PARAMETERIZED_NATIVE_TYPES = {
286
- "character varying": {
287
- pslType: "String",
288
- attributeName: "db.VarChar"
289
- },
290
- character: {
291
- pslType: "String",
292
- attributeName: "db.Char"
293
- },
294
- char: {
295
- pslType: "String",
296
- attributeName: "db.Char"
297
- },
298
- varchar: {
299
- pslType: "String",
300
- attributeName: "db.VarChar"
301
- },
302
- numeric: {
303
- pslType: "Decimal",
304
- attributeName: "db.Numeric"
305
- },
306
- timestamp: {
307
- pslType: "DateTime",
308
- attributeName: "db.Timestamp"
309
- },
310
- timestamptz: {
311
- pslType: "DateTime",
312
- attributeName: "db.Timestamptz"
313
- },
314
- time: {
315
- pslType: "DateTime",
316
- attributeName: "db.Time"
317
- },
318
- timetz: {
319
- pslType: "DateTime",
320
- attributeName: "db.Timetz"
321
- }
322
- };
323
- const PARAMETERIZED_TYPE_PATTERN = /^(.+?)\((.+)\)$/;
324
- function getOwnMappingValue(map, key) {
325
- return Object.hasOwn(map, key) ? map[key] : void 0;
326
- }
327
- function getOwnRecordValue(map, key) {
328
- return Object.hasOwn(map, key) ? map[key] : void 0;
329
- }
330
- function createNativeTypeAttribute(name, args) {
331
- return args && args.length > 0 ? {
332
- name,
333
- args
334
- } : { name };
335
- }
336
- function splitTypeParameterList(params) {
337
- return params.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
338
- }
339
- function createPostgresTypeMap(enumTypeNames) {
340
- return { resolve(nativeType) {
341
- if (enumTypeNames?.has(nativeType)) return {
342
- pslType: nativeType,
343
- nativeType
344
- };
345
- const paramMatch = nativeType.match(PARAMETERIZED_TYPE_PATTERN);
346
- if (paramMatch) {
347
- const [, baseType = nativeType, params = ""] = paramMatch;
348
- const template = getOwnRecordValue(PARAMETERIZED_NATIVE_TYPES, baseType);
349
- if (template) return {
350
- pslType: template.pslType,
351
- nativeType,
352
- typeParams: {
353
- baseType,
354
- params
355
- },
356
- nativeTypeAttribute: createNativeTypeAttribute(template.attributeName, splitTypeParameterList(params))
357
- };
358
- }
359
- const preservedType = getOwnRecordValue(PRESERVED_NATIVE_TYPES, nativeType);
360
- if (preservedType) return {
361
- pslType: preservedType.pslType,
362
- nativeType,
363
- nativeTypeAttribute: createNativeTypeAttribute(preservedType.attributeName)
364
- };
365
- const pslType = getOwnMappingValue(POSTGRES_TO_PSL, nativeType);
366
- if (pslType) return {
367
- pslType,
368
- nativeType
369
- };
370
- return {
371
- unsupported: true,
372
- nativeType
373
- };
374
- } };
375
- }
376
- function extractEnumInfo(annotations) {
377
- const nativeEnumTypeNames = (annotations?.["pg"])?.["nativeEnumTypeNames"];
378
- const typeNames = /* @__PURE__ */ new Set();
379
- const definitions = /* @__PURE__ */ new Map();
380
- if (Array.isArray(nativeEnumTypeNames)) {
381
- for (const name of nativeEnumTypeNames) if (typeof name === "string") typeNames.add(name);
382
- }
383
- return {
384
- typeNames,
385
- definitions
386
- };
387
- }
388
- //#endregion
389
- //#region src/core/psl-contract-infer/raw-default-parser.ts
390
- const NEXTVAL_PATTERN = /^nextval\s*\(/i;
391
- const NOW_FUNCTION_PATTERN = /^(now\s*\(\s*\)|CURRENT_TIMESTAMP)$/i;
392
- const CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\s*\(\s*\)$/i;
393
- const TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\s+(?:with|without)\s+time\s+zone)?$/i;
394
- const TEXT_CAST_SUFFIX = /::text$/i;
395
- const NOW_LITERAL_PATTERN = /^'now'$/i;
396
- const UUID_PATTERN = /^gen_random_uuid\s*\(\s*\)$/i;
397
- const UUID_OSSP_PATTERN = /^uuid_generate_v4\s*\(\s*\)$/i;
398
- const NULL_PATTERN = /^NULL(?:::.+)?$/i;
399
- const TRUE_PATTERN = /^true$/i;
400
- const FALSE_PATTERN = /^false$/i;
401
- const NUMERIC_PATTERN = /^-?\d+(\.\d+)?$/;
402
- const JSON_CAST_SUFFIX = /::jsonb?$/i;
403
- const STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:"[^"]+"|[\w\s]+)(?:\(\d+\))?)?$/;
404
- function canonicalizeTimestampDefault(expr) {
405
- if (NOW_FUNCTION_PATTERN.test(expr)) return "now()";
406
- if (CLOCK_TIMESTAMP_PATTERN.test(expr)) return "clock_timestamp()";
407
- if (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;
408
- let inner = expr.replace(TIMESTAMP_CAST_SUFFIX, "").trim();
409
- if (inner.startsWith("(") && inner.endsWith(")")) inner = inner.slice(1, -1).trim();
410
- if (NOW_FUNCTION_PATTERN.test(inner)) return "now()";
411
- if (CLOCK_TIMESTAMP_PATTERN.test(inner)) return "clock_timestamp()";
412
- inner = inner.replace(TEXT_CAST_SUFFIX, "").trim();
413
- if (NOW_LITERAL_PATTERN.test(inner)) return "now()";
414
- }
415
- function parseRawDefault(rawDefault, nativeType) {
416
- const trimmed = rawDefault.trim();
417
- const normalizedType = nativeType?.toLowerCase();
418
- if (NEXTVAL_PATTERN.test(trimmed)) return {
419
- kind: "function",
420
- expression: "autoincrement()"
421
- };
422
- const canonicalTimestamp = canonicalizeTimestampDefault(trimmed);
423
- if (canonicalTimestamp) return {
424
- kind: "function",
425
- expression: canonicalTimestamp
426
- };
427
- if (UUID_PATTERN.test(trimmed) || UUID_OSSP_PATTERN.test(trimmed)) return {
428
- kind: "function",
429
- expression: "gen_random_uuid()"
430
- };
431
- if (NULL_PATTERN.test(trimmed)) return {
432
- kind: "literal",
433
- value: null
434
- };
435
- if (TRUE_PATTERN.test(trimmed)) return {
436
- kind: "literal",
437
- value: true
438
- };
439
- if (FALSE_PATTERN.test(trimmed)) return {
440
- kind: "literal",
441
- value: false
442
- };
443
- if (NUMERIC_PATTERN.test(trimmed)) return {
444
- kind: "literal",
445
- value: Number(trimmed)
446
- };
447
- const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);
448
- if (stringMatch?.[1] !== void 0) {
449
- const unescaped = stringMatch[1].replace(/''/g, "'");
450
- if (normalizedType === "json" || normalizedType === "jsonb") {
451
- if (JSON_CAST_SUFFIX.test(trimmed)) return {
452
- kind: "function",
453
- expression: trimmed
454
- };
455
- try {
456
- return {
457
- kind: "literal",
458
- value: JSON.parse(unescaped)
459
- };
460
- } catch {}
461
- }
462
- return {
463
- kind: "literal",
464
- value: unescaped
465
- };
466
- }
467
- return {
468
- kind: "function",
469
- expression: trimmed
470
- };
471
- }
472
- //#endregion
473
- //#region src/core/psl-contract-infer/relation-inference.ts
474
- const DEFAULT_ON_DELETE = "noAction";
475
- const DEFAULT_ON_UPDATE = "noAction";
476
- const REFERENTIAL_ACTION_PSL = {
477
- noAction: "NoAction",
478
- restrict: "Restrict",
479
- cascade: "Cascade",
480
- setNull: "SetNull",
481
- setDefault: "SetDefault"
482
- };
483
- function inferRelations(tables, modelNameMap) {
484
- const relationsByTable = /* @__PURE__ */ new Map();
485
- const fkCountByPair = /* @__PURE__ */ new Map();
486
- for (const table of Object.values(tables)) for (const fk of table.foreignKeys) {
487
- const pairKey = `${table.name}→${fk.referencedTable}`;
488
- fkCountByPair.set(pairKey, (fkCountByPair.get(pairKey) ?? 0) + 1);
489
- }
490
- const usedFieldNames = /* @__PURE__ */ new Map();
491
- for (const table of Object.values(tables)) {
492
- const names = /* @__PURE__ */ new Set();
493
- for (const col of Object.values(table.columns)) names.add(col.name);
494
- usedFieldNames.set(table.name, names);
495
- }
496
- for (const table of Object.values(tables)) for (const fk of table.foreignKeys) {
497
- const childTableName = table.name;
498
- const parentTableName = fk.referencedTable;
499
- const childUsed = usedFieldNames.get(childTableName);
500
- const childModelName = modelNameMap.get(childTableName) ?? childTableName;
501
- const parentModelName = modelNameMap.get(parentTableName) ?? parentTableName;
502
- const pairKey = `${childTableName}→${parentTableName}`;
503
- const isSelfRelation = childTableName === parentTableName;
504
- const needsRelationName = fkCountByPair.get(pairKey) > 1 || isSelfRelation;
505
- const isOneToOne = detectOneToOne(fk, table);
506
- const childRelFieldName = resolveUniqueFieldName(deriveRelationFieldName(fk.columns, parentTableName), childUsed, parentModelName);
507
- const relationName = needsRelationName ? deriveRelationName(fk, childRelFieldName, parentModelName, isSelfRelation) : void 0;
508
- addRelationField(relationsByTable, childTableName, buildChildRelationField(childRelFieldName, parentModelName, fk, fk.columns.some((columnName) => table.columns[columnName]?.nullable ?? false), relationName));
509
- childUsed.add(childRelFieldName);
510
- const parentUsed = usedFieldNames.get(parentTableName) ?? /* @__PURE__ */ new Set();
511
- usedFieldNames.set(parentTableName, parentUsed);
512
- const backRelFieldName = resolveUniqueFieldName(deriveBackRelationFieldName(childModelName, isOneToOne), parentUsed, childModelName);
513
- addRelationField(relationsByTable, parentTableName, {
514
- fieldName: backRelFieldName,
515
- typeName: childModelName,
516
- optional: isOneToOne,
517
- list: !isOneToOne,
518
- relationName
519
- });
520
- parentUsed.add(backRelFieldName);
521
- }
522
- return { relationsByTable };
523
- }
524
- function detectOneToOne(fk, table) {
525
- const fkCols = [...fk.columns].sort();
526
- if (table.primaryKey) {
527
- const pkCols = [...table.primaryKey.columns].sort();
528
- if (pkCols.length === fkCols.length && pkCols.every((c, i) => c === fkCols[i])) return true;
529
- }
530
- for (const unique of table.uniques) {
531
- const uniqueCols = [...unique.columns].sort();
532
- if (uniqueCols.length === fkCols.length && uniqueCols.every((c, i) => c === fkCols[i])) return true;
533
- }
534
- return false;
535
- }
536
- function deriveRelationName(fk, childRelationFieldName, parentModelName, isSelfRelation) {
537
- if (fk.name) return fk.name;
538
- if (isSelfRelation) return `${childRelationFieldName.charAt(0).toUpperCase() + childRelationFieldName.slice(1)}${pluralize(parentModelName)}`;
539
- return fk.columns.join("_");
540
- }
541
- function buildChildRelationField(fieldName, parentModelName, fk, optional, relationName) {
542
- const onDelete = fk.onDelete && fk.onDelete !== DEFAULT_ON_DELETE ? fk.onDelete : void 0;
543
- const onUpdate = fk.onUpdate && fk.onUpdate !== DEFAULT_ON_UPDATE ? fk.onUpdate : void 0;
544
- return {
545
- fieldName,
546
- typeName: parentModelName,
547
- referencedTableName: fk.referencedTable,
548
- optional,
549
- list: false,
550
- relationName,
551
- fkName: fk.name,
552
- fields: fk.columns,
553
- references: fk.referencedColumns,
554
- onDelete: onDelete ? REFERENTIAL_ACTION_PSL[onDelete] : void 0,
555
- onUpdate: onUpdate ? REFERENTIAL_ACTION_PSL[onUpdate] : void 0
556
- };
557
- }
558
- function resolveUniqueFieldName(desired, usedNames, fallbackSuffix) {
559
- if (!usedNames.has(desired)) return desired;
560
- const withSuffix = `${desired}${fallbackSuffix}`;
561
- if (!usedNames.has(withSuffix)) return withSuffix;
562
- let counter = 2;
563
- while (usedNames.has(`${desired}${counter}`)) counter++;
564
- return `${desired}${counter}`;
565
- }
566
- function addRelationField(map, tableName, field) {
567
- const existing = map.get(tableName);
568
- if (existing) existing.push(field);
569
- else map.set(tableName, [field]);
570
- }
571
- //#endregion
572
- //#region src/core/psl-contract-infer/sql-schema-ir-to-psl-ast.ts
573
- const SYNTHETIC_SPAN = {
574
- start: {
575
- offset: 0,
576
- line: 1,
577
- column: 1
578
- },
579
- end: {
580
- offset: 0,
581
- line: 1,
582
- column: 1
583
- }
584
- };
585
- const PSL_SCALAR_TYPE_NAMES = new Set([
586
- "String",
587
- "Boolean",
588
- "Int",
589
- "BigInt",
590
- "Float",
591
- "Decimal",
592
- "DateTime",
593
- "Json",
594
- "Bytes"
595
- ]);
596
- /**
597
- * Converts a SQL schema IR into a PSL AST suitable for `printPsl`.
598
- *
599
- * This function owns all SQL-specific concerns: native type mapping (Postgres),
600
- * relation inference from foreign keys, enum extraction, and raw default parsing.
601
- * The output is a fully-formed `PslDocumentAst` with synthetic spans.
602
- */
603
- function sqlSchemaIrToPslAst(schemaIR) {
604
- const enumInfo = extractEnumInfo(schemaIR.annotations);
605
- if (enumInfo.typeNames.size > 0) {
606
- const names = [...enumInfo.typeNames].join(", ");
607
- throw new Error(`contract infer: the database contains native Postgres enum type(s): ${names}. Native Postgres enums (CREATE TYPE … AS ENUM) are not adoptable by contract infer. Drop the native type and replace each column with a text column carrying a CHECK constraint, then re-run contract infer. The domain enum (enum Name { @@type("pg/text@1") … }) authoring surface generates the required check automatically.`);
608
- }
609
- return buildPslDocumentAst(schemaIR, {
610
- typeMap: createPostgresTypeMap(/* @__PURE__ */ new Set()),
611
- defaultMapping: createPostgresDefaultMapping(),
612
- parseRawDefault
613
- });
614
- }
615
- function buildPslDocumentAst(schemaIR, options) {
616
- const { typeMap, defaultMapping, parseRawDefault: rawDefaultParser } = options;
617
- const modelNames = buildTopLevelNameMap(Object.keys(schemaIR.tables), toModelName, "model", "table");
618
- const modelNameMap = new Map([...modelNames].map(([tableName, result]) => [tableName, result.name]));
619
- const reservedNamedTypeNames = createReservedNamedTypeNames(modelNames);
620
- const fieldNamesByTable = buildFieldNamesByTable(schemaIR.tables);
621
- const { relationsByTable } = inferRelations(schemaIR.tables, modelNameMap);
622
- const namedTypes = seedNamedTypeRegistry(schemaIR, typeMap, /* @__PURE__ */ new Map(), reservedNamedTypeNames);
623
- const models = [];
624
- for (const table of Object.values(schemaIR.tables)) models.push(buildModel(table, typeMap, /* @__PURE__ */ new Map(), fieldNamesByTable, namedTypes, defaultMapping, rawDefaultParser, relationsByTable.get(table.name) ?? []));
625
- const sortedModels = topologicalSort(models, schemaIR.tables, modelNameMap);
626
- const namedTypeEntries = [...namedTypes.entriesByKey.values()].sort((a, b) => a.name.localeCompare(b.name));
627
- const types = namedTypeEntries.length > 0 ? {
628
- kind: "types",
629
- declarations: namedTypeEntries.map(buildNamedTypeDeclaration),
630
- span: SYNTHETIC_SPAN
631
- } : void 0;
632
- return {
633
- kind: "document",
634
- sourceId: "<sql-schema-ir>",
635
- namespaces: [makePslNamespace({
636
- kind: "namespace",
637
- name: UNSPECIFIED_PSL_NAMESPACE_ID,
638
- entries: makePslNamespaceEntries(sortedModels, [], []),
639
- span: SYNTHETIC_SPAN
640
- })],
641
- ...types ? { types } : {},
642
- span: SYNTHETIC_SPAN
643
- };
644
- }
645
- function buildModel(table, typeMap, enumNameMap, fieldNamesByTable, namedTypes, defaultMapping, rawDefaultParser, relationFields) {
646
- const { name: modelName, map: mapName } = toModelName(table.name);
647
- const fieldNameMap = fieldNamesByTable.get(table.name);
648
- const pkColumns = new Set(table.primaryKey?.columns ?? []);
649
- const isSinglePk = pkColumns.size === 1;
650
- const singlePkConstraintName = isSinglePk ? table.primaryKey?.name : void 0;
651
- const uniqueColumns = /* @__PURE__ */ new Map();
652
- for (const unique of table.uniques) if (unique.columns.length === 1) {
653
- const [columnName = ""] = unique.columns;
654
- const existingConstraintName = uniqueColumns.get(columnName);
655
- if (!uniqueColumns.has(columnName) || existingConstraintName === void 0 && unique.name) uniqueColumns.set(columnName, unique.name);
656
- }
657
- const fields = [];
658
- for (const column of Object.values(table.columns)) fields.push(buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns));
659
- const usedFieldNames = new Set(fields.map((field) => field.name));
660
- for (const rel of relationFields) fields.push(buildRelationField(rel, table.name, fieldNamesByTable, usedFieldNames));
661
- const modelAttributes = [];
662
- if (table.primaryKey && table.primaryKey.columns.length > 1) {
663
- const pkFieldNames = table.primaryKey.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
664
- modelAttributes.push(buildModelConstraintAttribute("id", pkFieldNames, table.primaryKey.name));
665
- }
666
- for (const unique of table.uniques) if (unique.columns.length > 1) {
667
- const uniqueFieldNames = unique.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
668
- modelAttributes.push(buildModelConstraintAttribute("unique", uniqueFieldNames, unique.name));
669
- }
670
- for (const index of table.indexes) if (!index.unique) {
671
- const indexFieldNames = index.columns.map((columnName) => resolveColumnFieldName(fieldNamesByTable, table.name, columnName));
672
- modelAttributes.push(buildModelConstraintAttribute("index", indexFieldNames, index.name));
673
- }
674
- if (mapName) modelAttributes.push(buildMapAttribute("model", mapName));
675
- const comment = table.primaryKey ? void 0 : "// WARNING: This table has no primary key in the database";
676
- return {
677
- kind: "model",
678
- name: modelName,
679
- fields,
680
- attributes: modelAttributes,
681
- span: SYNTHETIC_SPAN,
682
- ...comment !== void 0 ? { comment } : {}
683
- };
684
- }
685
- function buildScalarField(column, table, typeMap, enumNameMap, fieldNameMap, namedTypes, defaultMapping, rawDefaultParser, pkColumns, isSinglePk, singlePkConstraintName, uniqueColumns) {
686
- const resolvedField = fieldNameMap?.get(column.name);
687
- const fieldName = resolvedField?.fieldName ?? toFieldName(column.name).name;
688
- const fieldMap = resolvedField?.fieldMap;
689
- const resolution = typeMap.resolve(column.nativeType, table.annotations);
690
- if ("unsupported" in resolution) {
691
- const attrs = [];
692
- if (fieldMap !== void 0) attrs.push(buildMapAttribute("field", fieldMap));
693
- return {
694
- kind: "field",
695
- name: fieldName,
696
- typeName: `Unsupported("${escapePslString(resolution.nativeType)}")`,
697
- optional: column.nullable,
698
- list: column.many === true,
699
- attributes: attrs,
700
- span: SYNTHETIC_SPAN
701
- };
702
- }
703
- let typeName = resolution.pslType;
704
- const enumPslName = enumNameMap.get(column.nativeType);
705
- if (enumPslName) typeName = enumPslName;
706
- if (resolution.nativeTypeAttribute && !enumPslName) typeName = resolveNamedTypeName(namedTypes, resolution);
707
- const attributes = [];
708
- const isId = isSinglePk && pkColumns.has(column.name);
709
- if (isId) attributes.push(buildSimpleConstraintFieldAttribute("id", singlePkConstraintName));
710
- if (column.default !== void 0) {
711
- const parsed = parseColumnDefault(column.default, column.nativeType, rawDefaultParser);
712
- if (parsed) {
713
- const result = mapDefault(parsed, defaultMapping);
714
- if ("attribute" in result) attributes.push(parseDefaultAttributeString(result.attribute));
715
- }
716
- }
717
- if (uniqueColumns.has(column.name) && !isId) {
718
- const uniqueConstraintName = uniqueColumns.get(column.name);
719
- attributes.push(buildSimpleConstraintFieldAttribute("unique", uniqueConstraintName));
720
- }
721
- if (fieldMap !== void 0) attributes.push(buildMapAttribute("field", fieldMap));
722
- return {
723
- kind: "field",
724
- name: fieldName,
725
- typeName,
726
- optional: column.nullable,
727
- list: column.many === true,
728
- attributes,
729
- span: SYNTHETIC_SPAN
730
- };
731
- }
732
- function buildRelationField(rel, hostTableName, fieldNamesByTable, usedFieldNames) {
733
- const fieldName = createUniqueFieldName(rel.fieldName, usedFieldNames);
734
- usedFieldNames.add(fieldName);
735
- const args = [];
736
- if (rel.fields && rel.references) {
737
- if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
738
- args.push(namedArg("fields", `[${rel.fields.map((columnName) => resolveColumnFieldName(fieldNamesByTable, hostTableName, columnName)).join(", ")}]`));
739
- args.push(namedArg("references", `[${rel.references.map((columnName) => resolveColumnFieldName(fieldNamesByTable, rel.referencedTableName ?? "", columnName)).join(", ")}]`));
740
- if (rel.onDelete) args.push(namedArg("onDelete", rel.onDelete));
741
- if (rel.onUpdate) args.push(namedArg("onUpdate", rel.onUpdate));
742
- if (rel.fkName) args.push(namedArg("map", `"${escapePslString(rel.fkName)}"`));
743
- } else if (rel.relationName) args.push(namedArg("name", `"${escapePslString(rel.relationName)}"`));
744
- const attrs = args.length > 0 ? [buildAttribute("field", "relation", args)] : [];
745
- return {
746
- kind: "field",
747
- name: fieldName,
748
- typeName: rel.typeName,
749
- optional: rel.optional,
750
- list: rel.list,
751
- attributes: attrs,
752
- span: SYNTHETIC_SPAN
753
- };
754
- }
755
- function buildModelConstraintAttribute(name, fields, constraintName) {
756
- const args = [positionalArg(`[${fields.join(", ")}]`)];
757
- if (constraintName !== void 0) args.push(namedArg("map", `"${escapePslString(constraintName)}"`));
758
- return buildAttribute("model", name, args);
759
- }
760
- function buildSimpleConstraintFieldAttribute(name, constraintName) {
761
- if (constraintName === void 0) return buildAttribute("field", name, []);
762
- return buildAttribute("field", name, [namedArg("map", `"${escapePslString(constraintName)}"`)]);
763
- }
764
- function parseDefaultAttributeString(attributeText) {
765
- return buildAttribute("field", "default", [positionalArg(attributeText.replace(/^@default\(/, "").replace(/\)$/, ""))]);
766
- }
767
- function buildMapAttribute(target, mapName) {
768
- return buildAttribute(target, "map", [positionalArg(`"${escapePslString(mapName)}"`)]);
769
- }
770
- function buildAttribute(target, name, args) {
771
- return {
772
- kind: "attribute",
773
- target,
774
- name,
775
- args,
776
- span: SYNTHETIC_SPAN
777
- };
778
- }
779
- function positionalArg(value) {
780
- return {
781
- kind: "positional",
782
- value,
783
- span: SYNTHETIC_SPAN
784
- };
785
- }
786
- function namedArg(name, value) {
787
- return {
788
- kind: "named",
789
- name,
790
- value,
791
- span: SYNTHETIC_SPAN
792
- };
793
- }
794
- function buildNamedTypeDeclaration(entry) {
795
- const attribute = buildAttribute("namedType", entry.nativeTypeAttribute.name, (entry.nativeTypeAttribute.args ?? []).map(positionalArg));
796
- return {
797
- kind: "namedType",
798
- name: entry.name,
799
- baseType: entry.baseType,
800
- attributes: [attribute],
801
- span: SYNTHETIC_SPAN
802
- };
803
- }
804
- function escapePslString(value) {
805
- return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
806
- }
807
- /**
808
- * Resolves a `SqlColumnIR.default` value into a normalized {@link ColumnDefault}.
809
- *
810
- * `SqlSchemaIR` types the column default as `string` (a raw database default
811
- * expression). Some legacy fixtures and tests still pass already-normalized
812
- * `ColumnDefault` objects in the same slot, so we accept either shape
813
- * defensively at runtime.
814
- */
815
- function parseColumnDefault(value, nativeType, rawDefaultParser) {
816
- if (typeof value === "string") return rawDefaultParser ? rawDefaultParser(value, nativeType) : void 0;
817
- if (value !== null && typeof value === "object" && "kind" in value) return value;
818
- }
819
- function buildFieldNamesByTable(tables) {
820
- const fieldNamesByTable = /* @__PURE__ */ new Map();
821
- for (const table of Object.values(tables)) {
822
- const assignmentOrder = [...Object.values(table.columns).map((column, index) => {
823
- const { name, map } = toFieldName(column.name);
824
- return {
825
- columnName: column.name,
826
- desiredFieldName: name,
827
- fieldMap: map,
828
- index
829
- };
830
- })].sort((left, right) => {
831
- const mapComparison = Number(left.fieldMap !== void 0) - Number(right.fieldMap !== void 0);
832
- if (mapComparison !== 0) return mapComparison;
833
- return left.index - right.index;
834
- });
835
- const usedFieldNames = /* @__PURE__ */ new Set();
836
- const tableFieldNames = /* @__PURE__ */ new Map();
837
- for (const column of assignmentOrder) {
838
- const fieldName = createUniqueFieldName(column.desiredFieldName, usedFieldNames);
839
- usedFieldNames.add(fieldName);
840
- tableFieldNames.set(column.columnName, {
841
- fieldName,
842
- fieldMap: column.fieldMap
843
- });
844
- }
845
- fieldNamesByTable.set(table.name, tableFieldNames);
846
- }
847
- return fieldNamesByTable;
848
- }
849
- function resolveColumnFieldName(fieldNamesByTable, tableName, columnName) {
850
- return fieldNamesByTable.get(tableName)?.get(columnName)?.fieldName ?? toFieldName(columnName).name;
851
- }
852
- function createUniqueFieldName(desiredName, usedFieldNames) {
853
- if (!usedFieldNames.has(desiredName)) return desiredName;
854
- let counter = 2;
855
- while (usedFieldNames.has(`${desiredName}${counter}`)) counter++;
856
- return `${desiredName}${counter}`;
857
- }
858
- function buildTopLevelNameMap(sources, normalize, kind, sourceKind) {
859
- const results = /* @__PURE__ */ new Map();
860
- const normalizedToSources = /* @__PURE__ */ new Map();
861
- for (const source of sources) {
862
- const normalized = normalize(source);
863
- results.set(source, normalized);
864
- normalizedToSources.set(normalized.name, [...normalizedToSources.get(normalized.name) ?? [], source]);
865
- }
866
- const duplicates = [...normalizedToSources.entries()].filter(([, conflictingSources]) => conflictingSources.length > 1);
867
- if (duplicates.length > 0) {
868
- const details = duplicates.map(([normalizedName, conflictingSources]) => `- ${kind} "${normalizedName}" from ${sourceKind}s ${conflictingSources.map((source) => `"${source}"`).join(", ")}`);
869
- throw new Error(`PSL ${kind} name collisions detected:\n${details.join("\n")}`);
870
- }
871
- return results;
872
- }
873
- function createReservedNamedTypeNames(modelNames) {
874
- const reservedNames = new Set(PSL_SCALAR_TYPE_NAMES);
875
- for (const result of modelNames.values()) reservedNames.add(result.name);
876
- return reservedNames;
877
- }
878
- function seedNamedTypeRegistry(schemaIR, typeMap, enumNameMap, reservedNames) {
879
- const seeds = /* @__PURE__ */ new Map();
880
- for (const tableName of Object.keys(schemaIR.tables).sort()) {
881
- const table = schemaIR.tables[tableName];
882
- if (!table) continue;
883
- for (const columnName of Object.keys(table.columns).sort()) {
884
- const column = table.columns[columnName];
885
- if (!column) continue;
886
- const resolution = typeMap.resolve(column.nativeType, table.annotations);
887
- if ("unsupported" in resolution || enumNameMap.has(column.nativeType) || !resolution.nativeTypeAttribute) continue;
888
- const signatureKey = createNamedTypeSignatureKey(resolution);
889
- if (!seeds.has(signatureKey)) seeds.set(signatureKey, {
890
- baseType: resolution.pslType,
891
- desiredName: toNamedTypeName(column.name),
892
- nativeTypeAttribute: resolution.nativeTypeAttribute
893
- });
894
- }
895
- }
896
- const registry = {
897
- entriesByKey: /* @__PURE__ */ new Map(),
898
- usedNames: new Set(reservedNames)
899
- };
900
- const sortedSeeds = [...seeds.entries()].sort((left, right) => {
901
- const desiredNameComparison = left[1].desiredName.localeCompare(right[1].desiredName);
902
- if (desiredNameComparison !== 0) return desiredNameComparison;
903
- return left[0].localeCompare(right[0]);
904
- });
905
- for (const [signatureKey, seed] of sortedSeeds) {
906
- const name = createUniqueFieldName(seed.desiredName, registry.usedNames);
907
- registry.entriesByKey.set(signatureKey, {
908
- name,
909
- baseType: seed.baseType,
910
- nativeTypeAttribute: seed.nativeTypeAttribute
911
- });
912
- registry.usedNames.add(name);
913
- }
914
- return registry;
915
- }
916
- function resolveNamedTypeName(registry, resolution) {
917
- const key = createNamedTypeSignatureKey(resolution);
918
- const existing = registry.entriesByKey.get(key);
919
- if (existing) return existing.name;
920
- throw new Error(`Named type registry was not seeded for native type "${resolution.nativeType}"`);
921
- }
922
- function createNamedTypeSignatureKey(resolution) {
923
- return JSON.stringify({
924
- baseType: resolution.pslType,
925
- nativeTypeAttribute: resolution.nativeTypeAttribute ? {
926
- name: resolution.nativeTypeAttribute.name,
927
- args: resolution.nativeTypeAttribute.args ?? null
928
- } : null
929
- });
930
- }
931
- function topologicalSort(models, tables, modelNameMap) {
932
- const modelByName = /* @__PURE__ */ new Map();
933
- for (const model of models) modelByName.set(model.name, model);
934
- const deps = /* @__PURE__ */ new Map();
935
- const tableToModel = /* @__PURE__ */ new Map();
936
- for (const tableName of Object.keys(tables)) {
937
- const modelName = modelNameMap.get(tableName);
938
- tableToModel.set(tableName, modelName);
939
- deps.set(modelName, /* @__PURE__ */ new Set());
940
- }
941
- for (const [tableName, table] of Object.entries(tables)) {
942
- const modelName = tableToModel.get(tableName);
943
- for (const fk of table.foreignKeys) {
944
- const refModelName = tableToModel.get(fk.referencedTable);
945
- if (refModelName && refModelName !== modelName) deps.get(modelName).add(refModelName);
946
- }
947
- }
948
- const result = [];
949
- const visited = /* @__PURE__ */ new Set();
950
- const visiting = /* @__PURE__ */ new Set();
951
- const sortedNames = [...deps.keys()].sort();
952
- function visit(name) {
953
- if (visited.has(name)) return;
954
- if (visiting.has(name)) return;
955
- visiting.add(name);
956
- const sortedDeps = [...deps.get(name)].sort();
957
- for (const dep of sortedDeps) visit(dep);
958
- visiting.delete(name);
959
- visited.add(name);
960
- result.push(modelByName.get(name));
961
- }
962
- for (const name of sortedNames) visit(name);
963
- return result;
964
- }
965
- //#endregion
966
50
  //#region src/core/control-instance.ts
967
51
  function extractCodecTypeIdsFromContract(contract) {
968
52
  const typeIds = /* @__PURE__ */ new Set();
@@ -1125,6 +209,9 @@ function createSqlFamilyInstance(stack) {
1125
209
  let controlAdapter;
1126
210
  const getControlAdapter = () => controlAdapter ??= adapter.create(stack);
1127
211
  const targetSerializer = target.contractSerializer;
212
+ const targetInferPslContract = blindCast(target).inferPslContract;
213
+ const verifyDatabaseSchema = blindCast(target).verifyDatabaseSchema;
214
+ if (!verifyDatabaseSchema) throw new Error(`SQL target "${target.targetId}" is missing the required verifyDatabaseSchema descriptor operation`);
1128
215
  const deserializeWithTargetSerializer = (contractOrJson) => {
1129
216
  const serializer = targetSerializer ?? new SqlContractSerializer();
1130
217
  const json = targetSerializer !== void 0 && !isPlainRecord(contractOrJson) ? targetSerializer.serializeContract(blindCast(contractOrJson)) : contractOrJson;
@@ -1231,19 +318,26 @@ function createSqlFamilyInstance(stack) {
1231
318
  },
1232
319
  verifySchema(options) {
1233
320
  const contract = deserializeWithTargetSerializer(options.contract);
1234
- const controlAdapter = getControlAdapter();
1235
- const sqlResult = verifySqlSchema({
321
+ const sqlResult = verifyDatabaseSchema({
1236
322
  contract,
1237
323
  schema: options.schema,
1238
324
  strict: options.strict,
1239
325
  typeMetadataRegistry,
1240
- frameworkComponents: options.frameworkComponents,
1241
- ...ifDefined("normalizeDefault", controlAdapter.normalizeDefault),
1242
- ...ifDefined("normalizeNativeType", controlAdapter.normalizeNativeType)
326
+ frameworkComponents: options.frameworkComponents
1243
327
  });
1244
- const schemaDiffIssues = filterSchemaDiffIssues(controlAdapter.collectSchemaDiffIssues?.(contract, options.schema) ?? [], contract.defaultControlPolicy);
1245
- if (schemaDiffIssues.length === 0) return sqlResult;
1246
- const totalFails = sqlResult.schema.counts.fail + schemaDiffIssues.length;
328
+ const schemaDiffIssues = filterSchemaDiffIssues(sqlResult.schema.schemaDiffIssues, contract.defaultControlPolicy);
329
+ const relationalFails = sqlResult.schema.counts.fail;
330
+ if (schemaDiffIssues.length === 0) {
331
+ if (schemaDiffIssues === sqlResult.schema.schemaDiffIssues) return sqlResult;
332
+ return {
333
+ ...sqlResult,
334
+ schema: {
335
+ ...sqlResult.schema,
336
+ schemaDiffIssues
337
+ }
338
+ };
339
+ }
340
+ const totalFails = relationalFails + schemaDiffIssues.length;
1247
341
  return {
1248
342
  ...sqlResult,
1249
343
  ok: false,
@@ -1347,7 +441,8 @@ function createSqlFamilyInstance(stack) {
1347
441
  return getControlAdapter().introspect(options.driver, options.contract);
1348
442
  },
1349
443
  inferPslContract(schemaIR) {
1350
- return sqlSchemaIrToPslAst(schemaIR);
444
+ if (!targetInferPslContract) throw new Error(`Target "${target.targetId}" does not support contract infer (no inferPslContract on its descriptor).`);
445
+ return targetInferPslContract(schemaIR);
1351
446
  },
1352
447
  lowerAst(ast, context) {
1353
448
  return getControlAdapter().lowerToExecuteRequest(ast, context);
@@ -1355,21 +450,25 @@ function createSqlFamilyInstance(stack) {
1355
450
  bootstrapControlTableQueries() {
1356
451
  return getControlAdapter().bootstrapControlTableQueries();
1357
452
  },
1358
- bootstrapSignMarkerQueries() {
1359
- return getControlAdapter().bootstrapSignMarkerQueries();
1360
- },
1361
453
  toOperationPreview(operations) {
1362
454
  return sqlOperationsToPreview(operations);
1363
455
  },
1364
456
  toSchemaView(schema) {
1365
- const tableNodes = Object.entries(schema.tables).map(([tableName, table]) => {
457
+ const root = blindCast(schema);
458
+ const namespaceEntries = root.namespaces !== void 0 ? Object.entries(root.namespaces).map(([namespaceKey, namespace]) => [namespaceKey, namespace.tables]) : [[void 0, root.tables ?? {}]];
459
+ const qualify = namespaceEntries.length > 1;
460
+ const tableNodes = namespaceEntries.flatMap(([namespaceKey, tables]) => Object.entries(tables).map(([tableName, table]) => [
461
+ qualify && namespaceKey !== void 0 ? `${namespaceKey}.${tableName}` : tableName,
462
+ tableName,
463
+ table
464
+ ])).map(([displayName, tableName, table]) => {
1366
465
  const children = [];
1367
466
  const columnNodes = [];
1368
467
  for (const [columnName, column] of Object.entries(table.columns)) {
1369
468
  const label = `${columnName}: ${column.nativeType} (${column.nullable ? "nullable" : "not nullable"})`;
1370
469
  columnNodes.push(new SchemaTreeNode({
1371
470
  kind: "field",
1372
- id: `column-${tableName}-${columnName}`,
471
+ id: `column-${displayName}-${columnName}`,
1373
472
  label,
1374
473
  meta: {
1375
474
  nativeType: column.nativeType,
@@ -1380,7 +479,7 @@ function createSqlFamilyInstance(stack) {
1380
479
  }
1381
480
  if (columnNodes.length > 0) children.push(new SchemaTreeNode({
1382
481
  kind: "collection",
1383
- id: `columns-${tableName}`,
482
+ id: `columns-${displayName}`,
1384
483
  label: "columns",
1385
484
  children: columnNodes
1386
485
  }));
@@ -1388,7 +487,7 @@ function createSqlFamilyInstance(stack) {
1388
487
  const pkColumns = table.primaryKey.columns.join(", ");
1389
488
  children.push(new SchemaTreeNode({
1390
489
  kind: "index",
1391
- id: `primary-key-${tableName}`,
490
+ id: `primary-key-${displayName}`,
1392
491
  label: `primary key: ${pkColumns}`,
1393
492
  meta: {
1394
493
  columns: table.primaryKey.columns,
@@ -1401,7 +500,7 @@ function createSqlFamilyInstance(stack) {
1401
500
  const label = `unique ${name}`;
1402
501
  children.push(new SchemaTreeNode({
1403
502
  kind: "index",
1404
- id: `unique-${tableName}-${name}`,
503
+ id: `unique-${displayName}-${name}`,
1405
504
  label,
1406
505
  meta: {
1407
506
  columns: unique.columns,
@@ -1414,7 +513,7 @@ function createSqlFamilyInstance(stack) {
1414
513
  const label = index.unique ? `unique index ${name}` : `index ${name}`;
1415
514
  children.push(new SchemaTreeNode({
1416
515
  kind: "index",
1417
- id: `index-${tableName}-${name}`,
516
+ id: `index-${displayName}-${name}`,
1418
517
  label,
1419
518
  meta: {
1420
519
  columns: index.columns,
@@ -1435,8 +534,8 @@ function createSqlFamilyInstance(stack) {
1435
534
  }));
1436
535
  return new SchemaTreeNode({
1437
536
  kind: "entity",
1438
- id: `table-${tableName}`,
1439
- label: `table ${tableName}`,
537
+ id: `table-${displayName}`,
538
+ label: `table ${displayName}`,
1440
539
  ...Object.keys(tableMeta).length > 0 ? { meta: tableMeta } : {},
1441
540
  ...children.length > 0 ? { children } : {}
1442
541
  });
@@ -1451,8 +550,8 @@ function createSqlFamilyInstance(stack) {
1451
550
  };
1452
551
  }
1453
552
  /**
1454
- * Filters schema diff issues (from `collectSchemaDiffIssues`) through the
1455
- * contract's `defaultControlPolicy`. Issues whose outcome maps to a suppressed
553
+ * Filters the structural schema-diff issues (from `diffDatabaseSchema`) through
554
+ * the contract's `defaultControlPolicy`. Issues whose outcome maps to a suppressed
1456
555
  * category under the effective policy are removed. This mirrors the control-policy
1457
556
  * filtering applied by `verifySqlSchema` for table/column-level findings.
1458
557
  *
@@ -1674,8 +773,8 @@ function planFieldEventOperations(options) {
1674
773
  for (const tableName of tableNames) {
1675
774
  const priorTableRaw = priorTables?.[tableName];
1676
775
  const newTableRaw = newTables?.[tableName];
1677
- const priorTable = isStorageTable(priorTableRaw) ? priorTableRaw : void 0;
1678
- const newTable = isStorageTable(newTableRaw) ? newTableRaw : void 0;
776
+ const priorTable = StorageTable.is(priorTableRaw) ? priorTableRaw : void 0;
777
+ const newTable = StorageTable.is(newTableRaw) ? newTableRaw : void 0;
1679
778
  const fieldNames = unionSorted(priorTable ? Object.keys(priorTable.columns) : [], newTable ? Object.keys(newTable.columns) : []);
1680
779
  for (const fieldName of fieldNames) {
1681
780
  const priorField = priorTable?.columns[fieldName];
@@ -1892,6 +991,6 @@ const INIT_ADDITIVE_POLICY = Object.freeze({ allowedOperationClasses: Object.fre
1892
991
  //#region src/exports/control.ts
1893
992
  var control_default = new SqlFamilyDescriptor();
1894
993
  //#endregion
1895
- export { INIT_ADDITIVE_POLICY, assembleAuthoringContributions, contractToSchemaIR, controlPolicyForCall, createMigrationPlan, control_default as default, detectDestructiveChanges, extractCodecControlHooks, partitionCallsByControlPolicy, partitionIssuesByControlPolicy, planFieldEventOperations, plannerFailure, plannerSuccess, resolveValueSetValues, runnerFailure, runnerSuccess, temporalAuthoringPresets, timestampNowControlDescriptor };
994
+ export { INIT_ADDITIVE_POLICY, assembleAuthoringContributions, contractNamespaceToSchemaIR, contractToSchemaIR, controlPolicyForCall, createMigrationPlan, control_default as default, detectDestructiveChanges, extractCodecControlHooks, partitionCallsByControlPolicy, partitionIssuesByControlPolicy, planFieldEventOperations, plannerFailure, plannerSuccess, resolveValueSetValues, runnerFailure, runnerSuccess, temporalAuthoringPresets, timestampNowControlDescriptor };
1896
995
 
1897
996
  //# sourceMappingURL=control.mjs.map