@prisma-next/family-sql 0.3.0-dev.7 → 0.3.0-dev.71

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 (102) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +15 -6
  3. package/dist/assembly-BVS641kd.mjs +106 -0
  4. package/dist/assembly-BVS641kd.mjs.map +1 -0
  5. package/dist/control-adapter.d.mts +60 -0
  6. package/dist/control-adapter.d.mts.map +1 -0
  7. package/dist/control-adapter.mjs +1 -0
  8. package/dist/control-instance-62RsSxEp.d.mts +291 -0
  9. package/dist/control-instance-62RsSxEp.d.mts.map +1 -0
  10. package/dist/control.d.mts +106 -0
  11. package/dist/control.d.mts.map +1 -0
  12. package/dist/control.mjs +640 -0
  13. package/dist/control.mjs.map +1 -0
  14. package/dist/runtime.d.mts +27 -0
  15. package/dist/runtime.d.mts.map +1 -0
  16. package/dist/runtime.mjs +38 -0
  17. package/dist/runtime.mjs.map +1 -0
  18. package/dist/schema-verify.d.mts +48 -0
  19. package/dist/schema-verify.d.mts.map +1 -0
  20. package/dist/schema-verify.mjs +4 -0
  21. package/dist/test-utils.d.mts +2 -0
  22. package/dist/test-utils.mjs +3 -0
  23. package/dist/verify-BfMETJcM.mjs +108 -0
  24. package/dist/verify-BfMETJcM.mjs.map +1 -0
  25. package/dist/verify-sql-schema-CpAVEi8A.mjs +1058 -0
  26. package/dist/verify-sql-schema-CpAVEi8A.mjs.map +1 -0
  27. package/dist/verify-sql-schema-DhHnkpPa.d.mts +67 -0
  28. package/dist/verify-sql-schema-DhHnkpPa.d.mts.map +1 -0
  29. package/dist/verify.d.mts +31 -0
  30. package/dist/verify.d.mts.map +1 -0
  31. package/dist/verify.mjs +3 -0
  32. package/package.json +36 -47
  33. package/src/core/assembly.ts +158 -59
  34. package/src/core/control-adapter.ts +15 -0
  35. package/src/core/control-descriptor.ts +37 -0
  36. package/src/core/{instance.ts → control-instance.ts} +108 -241
  37. package/src/core/migrations/contract-to-schema-ir.ts +181 -0
  38. package/src/core/migrations/types.ts +63 -165
  39. package/src/core/runtime-descriptor.ts +19 -41
  40. package/src/core/runtime-instance.ts +11 -133
  41. package/src/core/schema-verify/verify-helpers.ts +187 -97
  42. package/src/core/schema-verify/verify-sql-schema.ts +910 -392
  43. package/src/core/verify.ts +4 -13
  44. package/src/exports/control.ts +15 -6
  45. package/src/exports/runtime.ts +2 -6
  46. package/src/exports/schema-verify.ts +10 -2
  47. package/src/exports/test-utils.ts +0 -1
  48. package/dist/chunk-6K3RPBDP.js +0 -580
  49. package/dist/chunk-6K3RPBDP.js.map +0 -1
  50. package/dist/chunk-BHEGVBY7.js +0 -772
  51. package/dist/chunk-BHEGVBY7.js.map +0 -1
  52. package/dist/chunk-SU7LN2UH.js +0 -96
  53. package/dist/chunk-SU7LN2UH.js.map +0 -1
  54. package/dist/core/assembly.d.ts +0 -25
  55. package/dist/core/assembly.d.ts.map +0 -1
  56. package/dist/core/control-adapter.d.ts +0 -42
  57. package/dist/core/control-adapter.d.ts.map +0 -1
  58. package/dist/core/descriptor.d.ts +0 -31
  59. package/dist/core/descriptor.d.ts.map +0 -1
  60. package/dist/core/instance.d.ts +0 -142
  61. package/dist/core/instance.d.ts.map +0 -1
  62. package/dist/core/migrations/plan-helpers.d.ts +0 -20
  63. package/dist/core/migrations/plan-helpers.d.ts.map +0 -1
  64. package/dist/core/migrations/policies.d.ts +0 -6
  65. package/dist/core/migrations/policies.d.ts.map +0 -1
  66. package/dist/core/migrations/types.d.ts +0 -280
  67. package/dist/core/migrations/types.d.ts.map +0 -1
  68. package/dist/core/runtime-descriptor.d.ts +0 -19
  69. package/dist/core/runtime-descriptor.d.ts.map +0 -1
  70. package/dist/core/runtime-instance.d.ts +0 -54
  71. package/dist/core/runtime-instance.d.ts.map +0 -1
  72. package/dist/core/schema-verify/verify-helpers.d.ts +0 -50
  73. package/dist/core/schema-verify/verify-helpers.d.ts.map +0 -1
  74. package/dist/core/schema-verify/verify-sql-schema.d.ts +0 -45
  75. package/dist/core/schema-verify/verify-sql-schema.d.ts.map +0 -1
  76. package/dist/core/verify.d.ts +0 -39
  77. package/dist/core/verify.d.ts.map +0 -1
  78. package/dist/exports/control-adapter.d.ts +0 -2
  79. package/dist/exports/control-adapter.d.ts.map +0 -1
  80. package/dist/exports/control-adapter.js +0 -1
  81. package/dist/exports/control-adapter.js.map +0 -1
  82. package/dist/exports/control.d.ts +0 -13
  83. package/dist/exports/control.d.ts.map +0 -1
  84. package/dist/exports/control.js +0 -149
  85. package/dist/exports/control.js.map +0 -1
  86. package/dist/exports/runtime.d.ts +0 -8
  87. package/dist/exports/runtime.d.ts.map +0 -1
  88. package/dist/exports/runtime.js +0 -64
  89. package/dist/exports/runtime.js.map +0 -1
  90. package/dist/exports/schema-verify.d.ts +0 -11
  91. package/dist/exports/schema-verify.d.ts.map +0 -1
  92. package/dist/exports/schema-verify.js +0 -11
  93. package/dist/exports/schema-verify.js.map +0 -1
  94. package/dist/exports/test-utils.d.ts +0 -7
  95. package/dist/exports/test-utils.d.ts.map +0 -1
  96. package/dist/exports/test-utils.js +0 -17
  97. package/dist/exports/test-utils.js.map +0 -1
  98. package/dist/exports/verify.d.ts +0 -2
  99. package/dist/exports/verify.d.ts.map +0 -1
  100. package/dist/exports/verify.js +0 -11
  101. package/dist/exports/verify.js.map +0 -1
  102. package/src/core/descriptor.ts +0 -37
@@ -7,6 +7,8 @@
7
7
  */
8
8
 
9
9
  import type { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';
10
+ import type { ColumnDefault } from '@prisma-next/contract/types';
11
+ import { isTaggedBigInt } from '@prisma-next/contract/types';
10
12
  import type {
11
13
  OperationContext,
12
14
  SchemaIssue,
@@ -16,8 +18,10 @@ import type {
16
18
  import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
17
19
  import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
18
20
  import { ifDefined } from '@prisma-next/utils/defined';
19
- import type { ComponentDatabaseDependency } from '../migrations/types';
21
+ import { extractCodecControlHooks } from '../assembly';
22
+ import type { CodecControlHooks, ComponentDatabaseDependency } from '../migrations/types';
20
23
  import {
24
+ arraysEqual,
21
25
  computeCounts,
22
26
  verifyDatabaseDependencies,
23
27
  verifyForeignKeys,
@@ -26,6 +30,22 @@ import {
26
30
  verifyUniqueConstraints,
27
31
  } from './verify-helpers';
28
32
 
33
+ /**
34
+ * Function type for normalizing raw database default expressions into ColumnDefault.
35
+ * Target-specific implementations handle database dialect differences.
36
+ */
37
+ export type DefaultNormalizer = (
38
+ rawDefault: string,
39
+ nativeType: string,
40
+ ) => ColumnDefault | undefined;
41
+
42
+ /**
43
+ * Function type for normalizing schema native types to canonical form for comparison.
44
+ * Target-specific implementations handle dialect-specific type name variations
45
+ * (e.g., Postgres 'varchar' → 'character varying', 'timestamptz' normalization).
46
+ */
47
+ export type NativeTypeNormalizer = (nativeType: string) => string;
48
+
29
49
  /**
30
50
  * Options for the pure schema verification function.
31
51
  */
@@ -45,6 +65,18 @@ export interface VerifySqlSchemaOptions {
45
65
  * All components must have matching familyId ('sql') and targetId.
46
66
  */
47
67
  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
68
+ /**
69
+ * Optional target-specific normalizer for raw database default expressions.
70
+ * When provided, schema defaults (raw strings) are normalized before comparison
71
+ * with contract defaults (ColumnDefault objects).
72
+ */
73
+ readonly normalizeDefault?: DefaultNormalizer;
74
+ /**
75
+ * Optional target-specific normalizer for schema native type names.
76
+ * When provided, schema native types are normalized before comparison
77
+ * with contract native types (e.g., Postgres 'varchar' → 'character varying').
78
+ */
79
+ readonly normalizeNativeType?: NativeTypeNormalizer;
48
80
  }
49
81
 
50
82
  /**
@@ -58,22 +90,167 @@ export interface VerifySqlSchemaOptions {
58
90
  * @returns VerifyDatabaseSchemaResult with verification tree and issues
59
91
  */
60
92
  export function verifySqlSchema(options: VerifySqlSchemaOptions): VerifyDatabaseSchemaResult {
61
- const { contract, schema, strict, context, typeMetadataRegistry } = options;
93
+ const {
94
+ contract,
95
+ schema,
96
+ strict,
97
+ context,
98
+ typeMetadataRegistry,
99
+ normalizeDefault,
100
+ normalizeNativeType,
101
+ } = options;
62
102
  const startTime = Date.now();
63
103
 
64
- // Extract contract hashes and target
65
- const contractCoreHash = contract.coreHash;
66
- const contractProfileHash =
67
- 'profileHash' in contract && typeof contract.profileHash === 'string'
68
- ? contract.profileHash
69
- : undefined;
70
- const contractTarget = contract.target;
104
+ // Extract codec control hooks once at entry point for reuse
105
+ const codecHooks = extractCodecControlHooks(options.frameworkComponents);
106
+
107
+ const { contractStorageHash, contractProfileHash, contractTarget } =
108
+ extractContractMetadata(contract);
109
+ const { issues, rootChildren } = verifySchemaTables({
110
+ contract,
111
+ schema,
112
+ strict,
113
+ typeMetadataRegistry,
114
+ codecHooks,
115
+ ...ifDefined('normalizeDefault', normalizeDefault),
116
+ ...ifDefined('normalizeNativeType', normalizeNativeType),
117
+ });
118
+
119
+ validateFrameworkComponentsForExtensions(contract, options.frameworkComponents);
120
+
121
+ // Verify storage type instances via codec control hooks (pure, deterministic)
122
+ const storageTypes = contract.storage.types ?? {};
123
+ const storageTypeEntries = Object.entries(storageTypes);
124
+ if (storageTypeEntries.length > 0) {
125
+ const typeNodes: SchemaVerificationNode[] = [];
126
+ for (const [typeName, typeInstance] of storageTypeEntries) {
127
+ const hook = codecHooks.get(typeInstance.codecId);
128
+ const typeIssues = hook?.verifyType
129
+ ? hook.verifyType({ typeName, typeInstance, schema })
130
+ : [];
131
+ if (typeIssues.length > 0) {
132
+ issues.push(...typeIssues);
133
+ }
134
+ const typeStatus = typeIssues.length > 0 ? 'fail' : 'pass';
135
+ const typeCode = typeIssues.length > 0 ? (typeIssues[0]?.kind ?? '') : '';
136
+ typeNodes.push({
137
+ status: typeStatus,
138
+ kind: 'storageType',
139
+ name: `type ${typeName}`,
140
+ contractPath: `storage.types.${typeName}`,
141
+ code: typeCode,
142
+ message:
143
+ typeIssues.length > 0
144
+ ? `${typeIssues.length} issue${typeIssues.length === 1 ? '' : 's'}`
145
+ : '',
146
+ expected: undefined,
147
+ actual: undefined,
148
+ children: [],
149
+ });
150
+ }
151
+ const typesStatus = typeNodes.some((n) => n.status === 'fail') ? 'fail' : 'pass';
152
+ rootChildren.push({
153
+ status: typesStatus,
154
+ kind: 'storageTypes',
155
+ name: 'types',
156
+ contractPath: 'storage.types',
157
+ code: typesStatus === 'fail' ? 'type_mismatch' : '',
158
+ message: '',
159
+ expected: undefined,
160
+ actual: undefined,
161
+ children: typeNodes,
162
+ });
163
+ }
71
164
 
72
- // Compare contract vs schema IR
165
+ const databaseDependencies = collectDependenciesFromFrameworkComponents(
166
+ options.frameworkComponents,
167
+ );
168
+ const dependencyStatuses = verifyDatabaseDependencies(databaseDependencies, schema, issues);
169
+ rootChildren.push(...dependencyStatuses);
170
+
171
+ const root = buildRootNode(rootChildren);
172
+
173
+ // Compute counts
174
+ const counts = computeCounts(root);
175
+
176
+ // Set ok flag
177
+ const ok = counts.fail === 0;
178
+
179
+ // Set code
180
+ const code = ok ? undefined : 'PN-SCHEMA-0001';
181
+
182
+ // Set summary
183
+ const summary = ok
184
+ ? 'Database schema satisfies contract'
185
+ : `Database schema does not satisfy contract (${counts.fail} failure${counts.fail === 1 ? '' : 's'})`;
186
+
187
+ const totalTime = Date.now() - startTime;
188
+
189
+ return {
190
+ ok,
191
+ ...ifDefined('code', code),
192
+ summary,
193
+ contract: {
194
+ storageHash: contractStorageHash,
195
+ ...ifDefined('profileHash', contractProfileHash),
196
+ },
197
+ target: {
198
+ expected: contractTarget,
199
+ actual: contractTarget,
200
+ },
201
+ schema: {
202
+ issues,
203
+ root,
204
+ counts,
205
+ },
206
+ meta: {
207
+ strict,
208
+ ...ifDefined('contractPath', context?.contractPath),
209
+ ...ifDefined('configPath', context?.configPath),
210
+ },
211
+ timings: {
212
+ total: totalTime,
213
+ },
214
+ };
215
+ }
216
+
217
+ type VerificationStatus = 'pass' | 'warn' | 'fail';
218
+
219
+ function extractContractMetadata(contract: SqlContract<SqlStorage>): {
220
+ contractStorageHash: SqlContract<SqlStorage>['storageHash'];
221
+ contractProfileHash?: SqlContract<SqlStorage>['profileHash'];
222
+ contractTarget: SqlContract<SqlStorage>['target'];
223
+ } {
224
+ return {
225
+ contractStorageHash: contract.storageHash,
226
+ contractProfileHash:
227
+ 'profileHash' in contract && typeof contract.profileHash === 'string'
228
+ ? contract.profileHash
229
+ : undefined,
230
+ contractTarget: contract.target,
231
+ };
232
+ }
233
+
234
+ function verifySchemaTables(options: {
235
+ contract: SqlContract<SqlStorage>;
236
+ schema: SqlSchemaIR;
237
+ strict: boolean;
238
+ typeMetadataRegistry: ReadonlyMap<string, { nativeType?: string }>;
239
+ codecHooks: Map<string, CodecControlHooks>;
240
+ normalizeDefault?: DefaultNormalizer;
241
+ normalizeNativeType?: NativeTypeNormalizer;
242
+ }): { issues: SchemaIssue[]; rootChildren: SchemaVerificationNode[] } {
243
+ const {
244
+ contract,
245
+ schema,
246
+ strict,
247
+ typeMetadataRegistry,
248
+ codecHooks,
249
+ normalizeDefault,
250
+ normalizeNativeType,
251
+ } = options;
73
252
  const issues: SchemaIssue[] = [];
74
253
  const rootChildren: SchemaVerificationNode[] = [];
75
-
76
- // Compare tables
77
254
  const contractTables = contract.storage.tables;
78
255
  const schemaTables = schema.tables;
79
256
 
@@ -82,7 +259,6 @@ export function verifySqlSchema(options: VerifySqlSchemaOptions): VerifyDatabase
82
259
  const tablePath = `storage.tables.${tableName}`;
83
260
 
84
261
  if (!schemaTable) {
85
- // Missing table
86
262
  issues.push({
87
263
  kind: 'missing_table',
88
264
  table: tableName,
@@ -102,394 +278,533 @@ export function verifySqlSchema(options: VerifySqlSchemaOptions): VerifyDatabase
102
278
  continue;
103
279
  }
104
280
 
105
- // Table exists - compare columns, constraints, etc.
106
- const tableChildren: SchemaVerificationNode[] = [];
107
- const columnNodes: SchemaVerificationNode[] = [];
108
-
109
- // Compare columns
110
- for (const [columnName, contractColumn] of Object.entries(contractTable.columns)) {
111
- const schemaColumn = schemaTable.columns[columnName];
112
- const columnPath = `${tablePath}.columns.${columnName}`;
281
+ const tableChildren = verifyTableChildren({
282
+ contractTable,
283
+ schemaTable,
284
+ tableName,
285
+ tablePath,
286
+ issues,
287
+ strict,
288
+ typeMetadataRegistry,
289
+ codecHooks,
290
+ ...ifDefined('normalizeDefault', normalizeDefault),
291
+ ...ifDefined('normalizeNativeType', normalizeNativeType),
292
+ });
293
+ rootChildren.push(buildTableNode(tableName, tablePath, tableChildren));
294
+ }
113
295
 
114
- if (!schemaColumn) {
115
- // Missing column
296
+ if (strict) {
297
+ for (const tableName of Object.keys(schemaTables)) {
298
+ if (!contractTables[tableName]) {
116
299
  issues.push({
117
- kind: 'missing_column',
300
+ kind: 'extra_table',
118
301
  table: tableName,
119
- column: columnName,
120
- message: `Column "${tableName}"."${columnName}" is missing from database`,
302
+ message: `Extra table "${tableName}" found in database (not in contract)`,
121
303
  });
122
- columnNodes.push({
304
+ rootChildren.push({
123
305
  status: 'fail',
124
- kind: 'column',
125
- name: `${columnName}: missing`,
126
- contractPath: columnPath,
127
- code: 'missing_column',
128
- message: `Column "${columnName}" is missing`,
306
+ kind: 'table',
307
+ name: `table ${tableName}`,
308
+ contractPath: `storage.tables.${tableName}`,
309
+ code: 'extra_table',
310
+ message: `Extra table "${tableName}" found`,
129
311
  expected: undefined,
130
312
  actual: undefined,
131
313
  children: [],
132
314
  });
133
- continue;
134
- }
135
-
136
- // Column exists - compare type and nullability
137
- const columnChildren: SchemaVerificationNode[] = [];
138
- let columnStatus: 'pass' | 'warn' | 'fail' = 'pass';
139
-
140
- // Compare type using nativeType directly
141
- // Both contractColumn.nativeType and schemaColumn.nativeType are required by their types
142
- const contractNativeType = contractColumn.nativeType;
143
- const schemaNativeType = schemaColumn.nativeType;
144
-
145
- if (contractNativeType !== schemaNativeType) {
146
- // Compare native types directly
147
- issues.push({
148
- kind: 'type_mismatch',
149
- table: tableName,
150
- column: columnName,
151
- expected: contractNativeType,
152
- actual: schemaNativeType,
153
- message: `Column "${tableName}"."${columnName}" has type mismatch: expected "${contractNativeType}", got "${schemaNativeType}"`,
154
- });
155
- columnChildren.push({
156
- status: 'fail',
157
- kind: 'type',
158
- name: 'type',
159
- contractPath: `${columnPath}.nativeType`,
160
- code: 'type_mismatch',
161
- message: `Type mismatch: expected ${contractNativeType}, got ${schemaNativeType}`,
162
- expected: contractNativeType,
163
- actual: schemaNativeType,
164
- children: [],
165
- });
166
- columnStatus = 'fail';
167
315
  }
316
+ }
317
+ }
168
318
 
169
- // Optionally validate that codecId (if present) and nativeType agree with registry
170
- if (contractColumn.codecId) {
171
- const typeMetadata = typeMetadataRegistry.get(contractColumn.codecId);
172
- if (!typeMetadata) {
173
- // Warning: codecId not found in registry
174
- columnChildren.push({
175
- status: 'warn',
176
- kind: 'type',
177
- name: 'type_metadata_missing',
178
- contractPath: `${columnPath}.codecId`,
179
- code: 'type_metadata_missing',
180
- message: `codecId "${contractColumn.codecId}" not found in type metadata registry`,
181
- expected: contractColumn.codecId,
182
- actual: undefined,
183
- children: [],
184
- });
185
- } else if (typeMetadata.nativeType && typeMetadata.nativeType !== contractNativeType) {
186
- // Warning: codecId and nativeType don't agree with registry
187
- columnChildren.push({
188
- status: 'warn',
189
- kind: 'type',
190
- name: 'type_consistency',
191
- contractPath: `${columnPath}.codecId`,
192
- code: 'type_consistency_warning',
193
- message: `codecId "${contractColumn.codecId}" maps to nativeType "${typeMetadata.nativeType}" in registry, but contract has "${contractNativeType}"`,
194
- expected: typeMetadata.nativeType,
195
- actual: contractNativeType,
196
- children: [],
197
- });
198
- }
199
- }
319
+ return { issues, rootChildren };
320
+ }
200
321
 
201
- // Compare nullability
202
- if (contractColumn.nullable !== schemaColumn.nullable) {
203
- issues.push({
204
- kind: 'nullability_mismatch',
205
- table: tableName,
206
- column: columnName,
207
- expected: String(contractColumn.nullable),
208
- actual: String(schemaColumn.nullable),
209
- message: `Column "${tableName}"."${columnName}" has nullability mismatch: expected ${contractColumn.nullable ? 'nullable' : 'not null'}, got ${schemaColumn.nullable ? 'nullable' : 'not null'}`,
210
- });
211
- columnChildren.push({
212
- status: 'fail',
213
- kind: 'nullability',
214
- name: 'nullability',
215
- contractPath: `${columnPath}.nullable`,
216
- code: 'nullability_mismatch',
217
- message: `Nullability mismatch: expected ${contractColumn.nullable ? 'nullable' : 'not null'}, got ${schemaColumn.nullable ? 'nullable' : 'not null'}`,
218
- expected: contractColumn.nullable,
219
- actual: schemaColumn.nullable,
220
- children: [],
221
- });
222
- columnStatus = 'fail';
223
- }
322
+ function verifyTableChildren(options: {
323
+ contractTable: SqlContract<SqlStorage>['storage']['tables'][string];
324
+ schemaTable: SqlSchemaIR['tables'][string];
325
+ tableName: string;
326
+ tablePath: string;
327
+ issues: SchemaIssue[];
328
+ strict: boolean;
329
+ typeMetadataRegistry: ReadonlyMap<string, { nativeType?: string }>;
330
+ codecHooks: Map<string, CodecControlHooks>;
331
+ normalizeDefault?: DefaultNormalizer;
332
+ normalizeNativeType?: NativeTypeNormalizer;
333
+ }): SchemaVerificationNode[] {
334
+ const {
335
+ contractTable,
336
+ schemaTable,
337
+ tableName,
338
+ tablePath,
339
+ issues,
340
+ strict,
341
+ typeMetadataRegistry,
342
+ codecHooks,
343
+ normalizeDefault,
344
+ normalizeNativeType,
345
+ } = options;
346
+ const tableChildren: SchemaVerificationNode[] = [];
347
+ const columnNodes = collectContractColumnNodes({
348
+ contractTable,
349
+ schemaTable,
350
+ tableName,
351
+ tablePath,
352
+ issues,
353
+ typeMetadataRegistry,
354
+ codecHooks,
355
+ ...ifDefined('normalizeDefault', normalizeDefault),
356
+ ...ifDefined('normalizeNativeType', normalizeNativeType),
357
+ });
358
+ if (columnNodes.length > 0) {
359
+ tableChildren.push(buildColumnsNode(tablePath, columnNodes));
360
+ }
361
+ if (strict) {
362
+ appendExtraColumnNodes({
363
+ contractTable,
364
+ schemaTable,
365
+ tableName,
366
+ tablePath,
367
+ issues,
368
+ columnNodes,
369
+ });
370
+ }
224
371
 
225
- // Compute column status from children (fail > warn > pass)
226
- const computedColumnStatus = columnChildren.some((c) => c.status === 'fail')
227
- ? 'fail'
228
- : columnChildren.some((c) => c.status === 'warn')
229
- ? 'warn'
230
- : 'pass';
231
- // Use computed status if we have children, otherwise use the manually set status
232
- const finalColumnStatus = columnChildren.length > 0 ? computedColumnStatus : columnStatus;
233
-
234
- // Build column node
235
- const nullableText = contractColumn.nullable ? 'nullable' : 'not nullable';
236
- const columnTypeDisplay = contractColumn.codecId
237
- ? `${contractNativeType} (${contractColumn.codecId})`
238
- : contractNativeType;
239
- // Collect failure messages from children to create a summary message
240
- const failureMessages = columnChildren
241
- .filter((child) => child.status === 'fail' && child.message)
242
- .map((child) => child.message)
243
- .filter((msg): msg is string => typeof msg === 'string' && msg.length > 0);
244
- const columnMessage =
245
- finalColumnStatus === 'fail' && failureMessages.length > 0
246
- ? failureMessages.join('; ')
247
- : '';
248
- // Extract code from first child if status indicates an issue
249
- const columnCode =
250
- (finalColumnStatus === 'fail' || finalColumnStatus === 'warn') && columnChildren[0]
251
- ? columnChildren[0].code
252
- : '';
253
- columnNodes.push({
254
- status: finalColumnStatus,
255
- kind: 'column',
256
- name: `${columnName}: ${columnTypeDisplay} (${nullableText})`,
257
- contractPath: columnPath,
258
- code: columnCode,
259
- message: columnMessage,
260
- expected: undefined,
261
- actual: undefined,
262
- children: columnChildren,
372
+ if (contractTable.primaryKey) {
373
+ const pkStatus = verifyPrimaryKey(
374
+ contractTable.primaryKey,
375
+ schemaTable.primaryKey,
376
+ tableName,
377
+ issues,
378
+ );
379
+ if (pkStatus === 'fail') {
380
+ tableChildren.push({
381
+ status: 'fail',
382
+ kind: 'primaryKey',
383
+ name: `primary key: ${contractTable.primaryKey.columns.join(', ')}`,
384
+ contractPath: `${tablePath}.primaryKey`,
385
+ code: 'primary_key_mismatch',
386
+ message: 'Primary key mismatch',
387
+ expected: contractTable.primaryKey,
388
+ actual: schemaTable.primaryKey,
389
+ children: [],
263
390
  });
264
- }
265
-
266
- // Group columns under a "columns" header if we have any columns
267
- if (columnNodes.length > 0) {
268
- const columnsStatus = columnNodes.some((c) => c.status === 'fail')
269
- ? 'fail'
270
- : columnNodes.some((c) => c.status === 'warn')
271
- ? 'warn'
272
- : 'pass';
391
+ } else {
273
392
  tableChildren.push({
274
- status: columnsStatus,
275
- kind: 'columns',
276
- name: 'columns',
277
- contractPath: `${tablePath}.columns`,
393
+ status: 'pass',
394
+ kind: 'primaryKey',
395
+ name: `primary key: ${contractTable.primaryKey.columns.join(', ')}`,
396
+ contractPath: `${tablePath}.primaryKey`,
278
397
  code: '',
279
398
  message: '',
280
399
  expected: undefined,
281
400
  actual: undefined,
282
- children: columnNodes,
401
+ children: [],
283
402
  });
284
403
  }
404
+ } else if (schemaTable.primaryKey && strict) {
405
+ issues.push({
406
+ kind: 'extra_primary_key',
407
+ table: tableName,
408
+ message: 'Extra primary key found in database (not in contract)',
409
+ });
410
+ tableChildren.push({
411
+ status: 'fail',
412
+ kind: 'primaryKey',
413
+ name: `primary key: ${schemaTable.primaryKey.columns.join(', ')}`,
414
+ contractPath: `${tablePath}.primaryKey`,
415
+ code: 'extra_primary_key',
416
+ message: 'Extra primary key found',
417
+ expected: undefined,
418
+ actual: schemaTable.primaryKey,
419
+ children: [],
420
+ });
421
+ }
285
422
 
286
- // Check for extra columns in strict mode
287
- if (strict) {
288
- for (const [columnName, { nativeType }] of Object.entries(schemaTable.columns)) {
289
- if (!contractTable.columns[columnName]) {
290
- issues.push({
291
- kind: 'extra_column',
292
- table: tableName,
293
- column: columnName,
294
- message: `Extra column "${tableName}"."${columnName}" found in database (not in contract)`,
295
- });
296
- columnNodes.push({
297
- status: 'fail',
298
- kind: 'column',
299
- name: `${columnName}: extra`,
300
- contractPath: `${tablePath}.columns.${columnName}`,
301
- code: 'extra_column',
302
- message: `Extra column "${columnName}" found`,
303
- expected: undefined,
304
- actual: nativeType,
305
- children: [],
306
- });
307
- }
308
- }
423
+ // Verify FK constraints only for FKs with constraint: true
424
+ const constraintFks = contractTable.foreignKeys.filter((fk) => fk.constraint === true);
425
+ if (constraintFks.length > 0) {
426
+ const fkStatuses = verifyForeignKeys(
427
+ constraintFks,
428
+ schemaTable.foreignKeys,
429
+ tableName,
430
+ tablePath,
431
+ issues,
432
+ strict,
433
+ );
434
+ tableChildren.push(...fkStatuses);
435
+ }
436
+
437
+ const uniqueStatuses = verifyUniqueConstraints(
438
+ contractTable.uniques,
439
+ schemaTable.uniques,
440
+ schemaTable.indexes,
441
+ tableName,
442
+ tablePath,
443
+ issues,
444
+ strict,
445
+ );
446
+ tableChildren.push(...uniqueStatuses);
447
+
448
+ // Combine user-declared indexes with FK-backing indexes (from FKs with index: true)
449
+ // so the verifier treats FK-backing indexes as expected, not "extra".
450
+ // Deduplicate: skip FK-backing indexes already covered by a user-declared index.
451
+ const fkBackingIndexes = contractTable.foreignKeys
452
+ .filter(
453
+ (fk) =>
454
+ fk.index === true &&
455
+ !contractTable.indexes.some((idx) => arraysEqual(idx.columns, fk.columns)),
456
+ )
457
+ .map((fk) => ({ columns: fk.columns }));
458
+ const allExpectedIndexes = [...contractTable.indexes, ...fkBackingIndexes];
459
+
460
+ const indexStatuses = verifyIndexes(
461
+ allExpectedIndexes,
462
+ schemaTable.indexes,
463
+ schemaTable.uniques,
464
+ tableName,
465
+ tablePath,
466
+ issues,
467
+ strict,
468
+ );
469
+ tableChildren.push(...indexStatuses);
470
+
471
+ return tableChildren;
472
+ }
473
+
474
+ function collectContractColumnNodes(options: {
475
+ contractTable: SqlContract<SqlStorage>['storage']['tables'][string];
476
+ schemaTable: SqlSchemaIR['tables'][string];
477
+ tableName: string;
478
+ tablePath: string;
479
+ issues: SchemaIssue[];
480
+ typeMetadataRegistry: ReadonlyMap<string, { nativeType?: string }>;
481
+ codecHooks: Map<string, CodecControlHooks>;
482
+ normalizeDefault?: DefaultNormalizer;
483
+ normalizeNativeType?: NativeTypeNormalizer;
484
+ }): SchemaVerificationNode[] {
485
+ const {
486
+ contractTable,
487
+ schemaTable,
488
+ tableName,
489
+ tablePath,
490
+ issues,
491
+ typeMetadataRegistry,
492
+ codecHooks,
493
+ normalizeDefault,
494
+ normalizeNativeType,
495
+ } = options;
496
+ const columnNodes: SchemaVerificationNode[] = [];
497
+
498
+ for (const [columnName, contractColumn] of Object.entries(contractTable.columns)) {
499
+ const schemaColumn = schemaTable.columns[columnName];
500
+ const columnPath = `${tablePath}.columns.${columnName}`;
501
+
502
+ if (!schemaColumn) {
503
+ issues.push({
504
+ kind: 'missing_column',
505
+ table: tableName,
506
+ column: columnName,
507
+ message: `Column "${tableName}"."${columnName}" is missing from database`,
508
+ });
509
+ columnNodes.push({
510
+ status: 'fail',
511
+ kind: 'column',
512
+ name: `${columnName}: missing`,
513
+ contractPath: columnPath,
514
+ code: 'missing_column',
515
+ message: `Column "${columnName}" is missing`,
516
+ expected: undefined,
517
+ actual: undefined,
518
+ children: [],
519
+ });
520
+ continue;
309
521
  }
310
522
 
311
- // Compare primary key
312
- if (contractTable.primaryKey) {
313
- const pkStatus = verifyPrimaryKey(
314
- contractTable.primaryKey,
315
- schemaTable.primaryKey,
523
+ columnNodes.push(
524
+ verifyColumn({
316
525
  tableName,
526
+ columnName,
527
+ contractColumn,
528
+ schemaColumn,
529
+ columnPath,
317
530
  issues,
318
- );
319
- if (pkStatus === 'fail') {
320
- tableChildren.push({
321
- status: 'fail',
322
- kind: 'primaryKey',
323
- name: `primary key: ${contractTable.primaryKey.columns.join(', ')}`,
324
- contractPath: `${tablePath}.primaryKey`,
325
- code: 'primary_key_mismatch',
326
- message: 'Primary key mismatch',
327
- expected: contractTable.primaryKey,
328
- actual: schemaTable.primaryKey,
329
- children: [],
330
- });
331
- } else {
332
- tableChildren.push({
333
- status: 'pass',
334
- kind: 'primaryKey',
335
- name: `primary key: ${contractTable.primaryKey.columns.join(', ')}`,
336
- contractPath: `${tablePath}.primaryKey`,
337
- code: '',
338
- message: '',
339
- expected: undefined,
340
- actual: undefined,
341
- children: [],
342
- });
343
- }
344
- } else if (schemaTable.primaryKey && strict) {
345
- // Extra primary key in strict mode
531
+ typeMetadataRegistry,
532
+ codecHooks,
533
+ ...ifDefined('normalizeDefault', normalizeDefault),
534
+ ...ifDefined('normalizeNativeType', normalizeNativeType),
535
+ }),
536
+ );
537
+ }
538
+
539
+ return columnNodes;
540
+ }
541
+
542
+ function appendExtraColumnNodes(options: {
543
+ contractTable: SqlContract<SqlStorage>['storage']['tables'][string];
544
+ schemaTable: SqlSchemaIR['tables'][string];
545
+ tableName: string;
546
+ tablePath: string;
547
+ issues: SchemaIssue[];
548
+ columnNodes: SchemaVerificationNode[];
549
+ }): void {
550
+ const { contractTable, schemaTable, tableName, tablePath, issues, columnNodes } = options;
551
+ for (const [columnName, { nativeType }] of Object.entries(schemaTable.columns)) {
552
+ if (!contractTable.columns[columnName]) {
346
553
  issues.push({
347
- kind: 'extra_primary_key',
554
+ kind: 'extra_column',
348
555
  table: tableName,
349
- message: 'Extra primary key found in database (not in contract)',
556
+ column: columnName,
557
+ message: `Extra column "${tableName}"."${columnName}" found in database (not in contract)`,
350
558
  });
351
- tableChildren.push({
559
+ columnNodes.push({
352
560
  status: 'fail',
353
- kind: 'primaryKey',
354
- name: `primary key: ${schemaTable.primaryKey.columns.join(', ')}`,
355
- contractPath: `${tablePath}.primaryKey`,
356
- code: 'extra_primary_key',
357
- message: 'Extra primary key found',
561
+ kind: 'column',
562
+ name: `${columnName}: extra`,
563
+ contractPath: `${tablePath}.columns.${columnName}`,
564
+ code: 'extra_column',
565
+ message: `Extra column "${columnName}" found`,
358
566
  expected: undefined,
359
- actual: schemaTable.primaryKey,
567
+ actual: nativeType,
360
568
  children: [],
361
569
  });
362
570
  }
571
+ }
572
+ }
363
573
 
364
- // Compare foreign keys
365
- const fkStatuses = verifyForeignKeys(
366
- contractTable.foreignKeys,
367
- schemaTable.foreignKeys,
368
- tableName,
369
- tablePath,
370
- issues,
371
- strict,
372
- );
373
- tableChildren.push(...fkStatuses);
574
+ function verifyColumn(options: {
575
+ tableName: string;
576
+ columnName: string;
577
+ contractColumn: SqlContract<SqlStorage>['storage']['tables'][string]['columns'][string];
578
+ schemaColumn: SqlSchemaIR['tables'][string]['columns'][string];
579
+ columnPath: string;
580
+ issues: SchemaIssue[];
581
+ typeMetadataRegistry: ReadonlyMap<string, { nativeType?: string }>;
582
+ codecHooks: Map<string, CodecControlHooks>;
583
+ normalizeDefault?: DefaultNormalizer;
584
+ normalizeNativeType?: NativeTypeNormalizer;
585
+ }): SchemaVerificationNode {
586
+ const {
587
+ tableName,
588
+ columnName,
589
+ contractColumn,
590
+ schemaColumn,
591
+ columnPath,
592
+ issues,
593
+ codecHooks,
594
+ normalizeDefault,
595
+ normalizeNativeType,
596
+ } = options;
597
+ const columnChildren: SchemaVerificationNode[] = [];
598
+ let columnStatus: VerificationStatus = 'pass';
374
599
 
375
- // Compare unique constraints
376
- const uniqueStatuses = verifyUniqueConstraints(
377
- contractTable.uniques,
378
- schemaTable.uniques,
379
- tableName,
380
- tablePath,
381
- issues,
382
- strict,
383
- );
384
- tableChildren.push(...uniqueStatuses);
600
+ const contractNativeType = renderExpectedNativeType(contractColumn, codecHooks);
601
+ const schemaNativeType =
602
+ normalizeNativeType?.(schemaColumn.nativeType) ?? schemaColumn.nativeType;
385
603
 
386
- // Compare indexes
387
- const indexStatuses = verifyIndexes(
388
- contractTable.indexes,
389
- schemaTable.indexes,
390
- tableName,
391
- tablePath,
392
- issues,
393
- strict,
394
- );
395
- tableChildren.push(...indexStatuses);
396
-
397
- // Build table node
398
- const tableStatus = tableChildren.some((c) => c.status === 'fail')
399
- ? 'fail'
400
- : tableChildren.some((c) => c.status === 'warn')
401
- ? 'warn'
402
- : 'pass';
403
- // Collect failure messages from children to create a summary message
404
- const tableFailureMessages = tableChildren
405
- .filter((child) => child.status === 'fail' && child.message)
406
- .map((child) => child.message)
407
- .filter((msg): msg is string => typeof msg === 'string' && msg.length > 0);
408
- const tableMessage =
409
- tableStatus === 'fail' && tableFailureMessages.length > 0
410
- ? `${tableFailureMessages.length} issue${tableFailureMessages.length === 1 ? '' : 's'}`
411
- : '';
412
- const tableCode =
413
- tableStatus === 'fail' && tableChildren.length > 0 && tableChildren[0]
414
- ? tableChildren[0].code
415
- : '';
416
- rootChildren.push({
417
- status: tableStatus,
418
- kind: 'table',
419
- name: `table ${tableName}`,
420
- contractPath: tablePath,
421
- code: tableCode,
422
- message: tableMessage,
423
- expected: undefined,
424
- actual: undefined,
425
- children: tableChildren,
604
+ if (contractNativeType !== schemaNativeType) {
605
+ issues.push({
606
+ kind: 'type_mismatch',
607
+ table: tableName,
608
+ column: columnName,
609
+ expected: contractNativeType,
610
+ actual: schemaNativeType,
611
+ message: `Column "${tableName}"."${columnName}" has type mismatch: expected "${contractNativeType}", got "${schemaNativeType}"`,
426
612
  });
613
+ columnChildren.push({
614
+ status: 'fail',
615
+ kind: 'type',
616
+ name: 'type',
617
+ contractPath: `${columnPath}.nativeType`,
618
+ code: 'type_mismatch',
619
+ message: `Type mismatch: expected ${contractNativeType}, got ${schemaNativeType}`,
620
+ expected: contractNativeType,
621
+ actual: schemaNativeType,
622
+ children: [],
623
+ });
624
+ columnStatus = 'fail';
427
625
  }
428
626
 
429
- // Check for extra tables in strict mode
430
- if (strict) {
431
- for (const tableName of Object.keys(schemaTables)) {
432
- if (!contractTables[tableName]) {
433
- issues.push({
434
- kind: 'extra_table',
435
- table: tableName,
436
- message: `Extra table "${tableName}" found in database (not in contract)`,
437
- });
438
- rootChildren.push({
439
- status: 'fail',
440
- kind: 'table',
441
- name: `table ${tableName}`,
442
- contractPath: `storage.tables.${tableName}`,
443
- code: 'extra_table',
444
- message: `Extra table "${tableName}" found`,
445
- expected: undefined,
446
- actual: undefined,
447
- children: [],
448
- });
449
- }
627
+ if (contractColumn.codecId) {
628
+ const typeMetadata = options.typeMetadataRegistry.get(contractColumn.codecId);
629
+ if (!typeMetadata) {
630
+ columnChildren.push({
631
+ status: 'warn',
632
+ kind: 'type',
633
+ name: 'type_metadata_missing',
634
+ contractPath: `${columnPath}.codecId`,
635
+ code: 'type_metadata_missing',
636
+ message: `codecId "${contractColumn.codecId}" not found in type metadata registry`,
637
+ expected: contractColumn.codecId,
638
+ actual: undefined,
639
+ children: [],
640
+ });
641
+ } else if (typeMetadata.nativeType && typeMetadata.nativeType !== contractColumn.nativeType) {
642
+ columnChildren.push({
643
+ status: 'warn',
644
+ kind: 'type',
645
+ name: 'type_consistency',
646
+ contractPath: `${columnPath}.codecId`,
647
+ code: 'type_consistency_warning',
648
+ message: `codecId "${contractColumn.codecId}" maps to nativeType "${typeMetadata.nativeType}" in registry, but contract has "${contractColumn.nativeType}"`,
649
+ expected: typeMetadata.nativeType,
650
+ actual: contractColumn.nativeType,
651
+ children: [],
652
+ });
450
653
  }
451
654
  }
452
655
 
453
- // Validate that all extension packs declared in the contract are present in frameworkComponents
454
- // This is a configuration integrity check - if the contract was emitted with an extension,
455
- // that extension must be provided in the current configuration.
456
- // Note: contract.extensionPacks includes adapter.id and target.id (from extractExtensionIds),
457
- // so we check for matches as extension, adapter, or target components.
458
- const contractExtensionPacks = contract.extensionPacks ?? {};
459
- for (const extensionNamespace of Object.keys(contractExtensionPacks)) {
460
- const hasComponent = options.frameworkComponents.some(
461
- (component) =>
462
- component.id === extensionNamespace &&
463
- (component.kind === 'extension' ||
464
- component.kind === 'adapter' ||
465
- component.kind === 'target'),
466
- );
467
- if (!hasComponent) {
468
- throw new Error(
469
- `Extension pack '${extensionNamespace}' is declared in the contract but not found in framework components. ` +
470
- 'This indicates a configuration mismatch - the contract was emitted with this extension pack, ' +
471
- 'but it is not provided in the current configuration.',
472
- );
656
+ if (contractColumn.nullable !== schemaColumn.nullable) {
657
+ issues.push({
658
+ kind: 'nullability_mismatch',
659
+ table: tableName,
660
+ column: columnName,
661
+ expected: String(contractColumn.nullable),
662
+ actual: String(schemaColumn.nullable),
663
+ message: `Column "${tableName}"."${columnName}" has nullability mismatch: expected ${contractColumn.nullable ? 'nullable' : 'not null'}, got ${schemaColumn.nullable ? 'nullable' : 'not null'}`,
664
+ });
665
+ columnChildren.push({
666
+ status: 'fail',
667
+ kind: 'nullability',
668
+ name: 'nullability',
669
+ contractPath: `${columnPath}.nullable`,
670
+ code: 'nullability_mismatch',
671
+ message: `Nullability mismatch: expected ${contractColumn.nullable ? 'nullable' : 'not null'}, got ${schemaColumn.nullable ? 'nullable' : 'not null'}`,
672
+ expected: contractColumn.nullable,
673
+ actual: schemaColumn.nullable,
674
+ children: [],
675
+ });
676
+ columnStatus = 'fail';
677
+ }
678
+
679
+ if (contractColumn.default) {
680
+ if (!schemaColumn.default) {
681
+ const defaultDescription = describeColumnDefault(contractColumn.default);
682
+ issues.push({
683
+ kind: 'default_missing',
684
+ table: tableName,
685
+ column: columnName,
686
+ expected: defaultDescription,
687
+ message: `Column "${tableName}"."${columnName}" should have default ${defaultDescription} but database has no default`,
688
+ });
689
+ columnChildren.push({
690
+ status: 'fail',
691
+ kind: 'default',
692
+ name: 'default',
693
+ contractPath: `${columnPath}.default`,
694
+ code: 'default_missing',
695
+ message: `Default missing: expected ${defaultDescription}`,
696
+ expected: defaultDescription,
697
+ actual: undefined,
698
+ children: [],
699
+ });
700
+ columnStatus = 'fail';
701
+ } else if (
702
+ !columnDefaultsEqual(
703
+ contractColumn.default,
704
+ schemaColumn.default,
705
+ normalizeDefault,
706
+ schemaNativeType,
707
+ )
708
+ ) {
709
+ const expectedDescription = describeColumnDefault(contractColumn.default);
710
+ // schemaColumn.default is now a raw string, describe it as-is
711
+ const actualDescription = schemaColumn.default;
712
+ issues.push({
713
+ kind: 'default_mismatch',
714
+ table: tableName,
715
+ column: columnName,
716
+ expected: expectedDescription,
717
+ actual: actualDescription,
718
+ message: `Column "${tableName}"."${columnName}" has default mismatch: expected ${expectedDescription}, got ${actualDescription}`,
719
+ });
720
+ columnChildren.push({
721
+ status: 'fail',
722
+ kind: 'default',
723
+ name: 'default',
724
+ contractPath: `${columnPath}.default`,
725
+ code: 'default_mismatch',
726
+ message: `Default mismatch: expected ${expectedDescription}, got ${actualDescription}`,
727
+ expected: expectedDescription,
728
+ actual: actualDescription,
729
+ children: [],
730
+ });
731
+ columnStatus = 'fail';
473
732
  }
474
733
  }
475
734
 
476
- // Compare component-owned database dependencies (pure, deterministic)
477
- // Per ADR 154: We do NOT infer dependencies from contract extension packs.
478
- // Dependencies are only collected from frameworkComponents provided by the CLI.
479
- const databaseDependencies = collectDependenciesFromFrameworkComponents(
480
- options.frameworkComponents,
481
- );
482
- const dependencyStatuses = verifyDatabaseDependencies(databaseDependencies, schema, issues);
483
- rootChildren.push(...dependencyStatuses);
735
+ // Single-pass aggregation for better performance
736
+ const aggregated = aggregateChildState(columnChildren, columnStatus);
737
+ const nullableText = contractColumn.nullable ? 'nullable' : 'not nullable';
738
+ const columnTypeDisplay = contractColumn.codecId
739
+ ? `${contractNativeType} (${contractColumn.codecId})`
740
+ : contractNativeType;
741
+ const columnMessage = aggregated.failureMessages.join('; ');
742
+
743
+ return {
744
+ status: aggregated.status,
745
+ kind: 'column',
746
+ name: `${columnName}: ${columnTypeDisplay} (${nullableText})`,
747
+ contractPath: columnPath,
748
+ code: aggregated.firstCode,
749
+ message: columnMessage,
750
+ expected: undefined,
751
+ actual: undefined,
752
+ children: columnChildren,
753
+ };
754
+ }
755
+
756
+ function buildColumnsNode(
757
+ tablePath: string,
758
+ columnNodes: SchemaVerificationNode[],
759
+ ): SchemaVerificationNode {
760
+ return {
761
+ status: aggregateChildState(columnNodes, 'pass').status,
762
+ kind: 'columns',
763
+ name: 'columns',
764
+ contractPath: `${tablePath}.columns`,
765
+ code: '',
766
+ message: '',
767
+ expected: undefined,
768
+ actual: undefined,
769
+ children: columnNodes,
770
+ };
771
+ }
772
+
773
+ function buildTableNode(
774
+ tableName: string,
775
+ tablePath: string,
776
+ tableChildren: SchemaVerificationNode[],
777
+ ): SchemaVerificationNode {
778
+ const tableStatus = aggregateChildState(tableChildren, 'pass').status;
779
+ const tableFailureMessages = tableChildren
780
+ .filter((child) => child.status === 'fail' && child.message)
781
+ .map((child) => child.message)
782
+ .filter((msg): msg is string => typeof msg === 'string' && msg.length > 0);
783
+ const tableMessage =
784
+ tableStatus === 'fail' && tableFailureMessages.length > 0
785
+ ? `${tableFailureMessages.length} issue${tableFailureMessages.length === 1 ? '' : 's'}`
786
+ : '';
787
+ const tableCode =
788
+ tableStatus === 'fail' && tableChildren.length > 0 && tableChildren[0]
789
+ ? tableChildren[0].code
790
+ : '';
791
+
792
+ return {
793
+ status: tableStatus,
794
+ kind: 'table',
795
+ name: `table ${tableName}`,
796
+ contractPath: tablePath,
797
+ code: tableCode,
798
+ message: tableMessage,
799
+ expected: undefined,
800
+ actual: undefined,
801
+ children: tableChildren,
802
+ };
803
+ }
484
804
 
485
- // Build root node
486
- const rootStatus = rootChildren.some((c) => c.status === 'fail')
487
- ? 'fail'
488
- : rootChildren.some((c) => c.status === 'warn')
489
- ? 'warn'
490
- : 'pass';
491
- const root: SchemaVerificationNode = {
492
- status: rootStatus,
805
+ function buildRootNode(rootChildren: SchemaVerificationNode[]): SchemaVerificationNode {
806
+ return {
807
+ status: aggregateChildState(rootChildren, 'pass').status,
493
808
  kind: 'contract',
494
809
  name: 'contract',
495
810
  contractPath: '',
@@ -499,49 +814,70 @@ export function verifySqlSchema(options: VerifySqlSchemaOptions): VerifyDatabase
499
814
  actual: undefined,
500
815
  children: rootChildren,
501
816
  };
817
+ }
502
818
 
503
- // Compute counts
504
- const counts = computeCounts(root);
505
-
506
- // Set ok flag
507
- const ok = counts.fail === 0;
819
+ /**
820
+ * Aggregated state from child nodes, computed in a single pass.
821
+ */
822
+ interface AggregatedChildState {
823
+ readonly status: VerificationStatus;
824
+ readonly failureMessages: readonly string[];
825
+ readonly firstCode: string;
826
+ }
508
827
 
509
- // Set code
510
- const code = ok ? undefined : 'PN-SCHEMA-0001';
828
+ /**
829
+ * Aggregates status, failure messages, and code from children in a single pass.
830
+ * This is more efficient than calling separate functions that each iterate the array.
831
+ */
832
+ function aggregateChildState(
833
+ children: SchemaVerificationNode[],
834
+ fallback: VerificationStatus,
835
+ ): AggregatedChildState {
836
+ let status: VerificationStatus = fallback;
837
+ const failureMessages: string[] = [];
838
+ let firstCode = '';
511
839
 
512
- // Set summary
513
- const summary = ok
514
- ? 'Database schema satisfies contract'
515
- : `Database schema does not satisfy contract (${counts.fail} failure${counts.fail === 1 ? '' : 's'})`;
840
+ for (const child of children) {
841
+ if (child.status === 'fail') {
842
+ status = 'fail';
843
+ if (!firstCode) {
844
+ firstCode = child.code;
845
+ }
846
+ if (child.message && typeof child.message === 'string' && child.message.length > 0) {
847
+ failureMessages.push(child.message);
848
+ }
849
+ } else if (child.status === 'warn' && status !== 'fail') {
850
+ status = 'warn';
851
+ if (!firstCode) {
852
+ firstCode = child.code;
853
+ }
854
+ }
855
+ }
516
856
 
517
- const totalTime = Date.now() - startTime;
857
+ return { status, failureMessages, firstCode };
858
+ }
518
859
 
519
- return {
520
- ok,
521
- ...ifDefined('code', code),
522
- summary,
523
- contract: {
524
- coreHash: contractCoreHash,
525
- ...ifDefined('profileHash', contractProfileHash),
526
- },
527
- target: {
528
- expected: contractTarget,
529
- actual: contractTarget,
530
- },
531
- schema: {
532
- issues,
533
- root,
534
- counts,
535
- },
536
- meta: {
537
- strict,
538
- ...ifDefined('contractPath', context?.contractPath),
539
- ...ifDefined('configPath', context?.configPath),
540
- },
541
- timings: {
542
- total: totalTime,
543
- },
544
- };
860
+ function validateFrameworkComponentsForExtensions(
861
+ contract: SqlContract<SqlStorage>,
862
+ frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>,
863
+ ): void {
864
+ const contractExtensionPacks = contract.extensionPacks ?? {};
865
+ for (const extensionNamespace of Object.keys(contractExtensionPacks)) {
866
+ const hasComponent = frameworkComponents.some(
867
+ (component) =>
868
+ component.id === extensionNamespace &&
869
+ (component.kind === 'extension' ||
870
+ component.kind === 'adapter' ||
871
+ component.kind === 'target'),
872
+ );
873
+ if (!hasComponent) {
874
+ throw new Error(
875
+ `Extension pack '${extensionNamespace}' is declared in the contract but not found in framework components. ` +
876
+ 'This indicates a configuration mismatch - the contract was emitted with this extension pack, ' +
877
+ 'but it is not provided in the current configuration.',
878
+ );
879
+ }
880
+ }
545
881
  }
546
882
 
547
883
  /**
@@ -582,3 +918,185 @@ function collectDependenciesFromFrameworkComponents<T extends string>(
582
918
  }
583
919
  return dependencies;
584
920
  }
921
+
922
+ /**
923
+ * Renders the expected native type for a contract column, expanding parameterized types
924
+ * using codec control hooks when available.
925
+ *
926
+ * This function delegates to the `expandNativeType` hook if the codec provides one,
927
+ * ensuring that the SQL family layer remains dialect-agnostic while allowing
928
+ * target-specific adapters (like Postgres) to provide their own expansion logic.
929
+ */
930
+ function renderExpectedNativeType(
931
+ contractColumn: SqlContract<SqlStorage>['storage']['tables'][string]['columns'][string],
932
+ codecHooks: Map<string, CodecControlHooks>,
933
+ ): string {
934
+ const { codecId, nativeType, typeParams } = contractColumn;
935
+
936
+ // If no typeParams or codecId, return the base native type
937
+ if (!typeParams || !codecId) {
938
+ return nativeType;
939
+ }
940
+
941
+ // Try to use the codec's expandNativeType hook if available
942
+ const hooks = codecHooks.get(codecId);
943
+ if (hooks?.expandNativeType) {
944
+ return hooks.expandNativeType({ nativeType, codecId, typeParams });
945
+ }
946
+
947
+ // Fallback: return base native type if no hook is available
948
+ return nativeType;
949
+ }
950
+
951
+ /**
952
+ * Describes a column default for display purposes.
953
+ */
954
+ function describeColumnDefault(columnDefault: ColumnDefault): string {
955
+ switch (columnDefault.kind) {
956
+ case 'literal':
957
+ return `literal(${formatLiteralValue(columnDefault.value)})`;
958
+ case 'function':
959
+ return columnDefault.expression;
960
+ }
961
+ }
962
+
963
+ /**
964
+ * Compares a contract ColumnDefault against a schema raw default string for semantic equality.
965
+ *
966
+ * When a normalizer is provided, the raw schema default is first normalized to a ColumnDefault
967
+ * before comparison. Without a normalizer, falls back to direct string comparison against
968
+ * the contract expression.
969
+ *
970
+ * @param contractDefault - The expected default from the contract (normalized ColumnDefault)
971
+ * @param schemaDefault - The raw default expression from the database (string)
972
+ * @param normalizer - Optional target-specific normalizer to convert raw defaults
973
+ * @param nativeType - The column's native type, passed to normalizer for context
974
+ */
975
+ function columnDefaultsEqual(
976
+ contractDefault: ColumnDefault,
977
+ schemaDefault: string,
978
+ normalizer?: DefaultNormalizer,
979
+ nativeType?: string,
980
+ ): boolean {
981
+ // If no normalizer provided, fall back to direct string comparison
982
+ if (!normalizer) {
983
+ if (contractDefault.kind === 'function') {
984
+ return contractDefault.expression === schemaDefault;
985
+ }
986
+ const normalizedValue = normalizeLiteralValue(contractDefault.value, nativeType);
987
+ if (typeof normalizedValue === 'string') {
988
+ return normalizedValue === schemaDefault || `'${normalizedValue}'` === schemaDefault;
989
+ }
990
+ return String(normalizedValue) === schemaDefault;
991
+ }
992
+
993
+ // Normalize the raw schema default using target-specific logic
994
+ const normalizedSchema = normalizer(schemaDefault, nativeType ?? '');
995
+ if (!normalizedSchema) {
996
+ // Normalizer couldn't parse the expression - treat as mismatch
997
+ return false;
998
+ }
999
+
1000
+ // Compare normalized defaults
1001
+ if (contractDefault.kind !== normalizedSchema.kind) {
1002
+ return false;
1003
+ }
1004
+ if (contractDefault.kind === 'literal' && normalizedSchema.kind === 'literal') {
1005
+ const contractValue = normalizeLiteralValue(contractDefault.value, nativeType);
1006
+ const schemaValue = normalizeLiteralValue(normalizedSchema.value, nativeType);
1007
+ return literalValuesEqual(contractValue, schemaValue);
1008
+ }
1009
+ if (contractDefault.kind === 'function' && normalizedSchema.kind === 'function') {
1010
+ // Normalize function expressions for comparison (case-insensitive, whitespace-tolerant)
1011
+ const normalizeExpr = (expr: string) => expr.toLowerCase().replace(/\s+/g, '');
1012
+ return normalizeExpr(contractDefault.expression) === normalizeExpr(normalizedSchema.expression);
1013
+ }
1014
+ return false;
1015
+ }
1016
+
1017
+ function isTemporalNativeType(nativeType?: string): boolean {
1018
+ if (!nativeType) return false;
1019
+ const normalized = nativeType.toLowerCase();
1020
+ return normalized.includes('timestamp') || normalized === 'date';
1021
+ }
1022
+
1023
+ function isBigIntNativeType(nativeType?: string): boolean {
1024
+ if (!nativeType) return false;
1025
+ const normalized = nativeType.toLowerCase();
1026
+ return normalized === 'bigint' || normalized === 'int8';
1027
+ }
1028
+
1029
+ function normalizeLiteralValue(value: unknown, nativeType?: string): unknown {
1030
+ if (value instanceof Date) {
1031
+ return value.toISOString();
1032
+ }
1033
+ if (isTaggedBigInt(value) && isBigIntNativeType(nativeType)) {
1034
+ return value.value;
1035
+ }
1036
+ if (typeof value === 'bigint') {
1037
+ return value.toString();
1038
+ }
1039
+ if (typeof value === 'string' && isTemporalNativeType(nativeType)) {
1040
+ const parsed = new Date(value);
1041
+ if (!Number.isNaN(parsed.getTime())) {
1042
+ return parsed.toISOString();
1043
+ }
1044
+ }
1045
+ return value;
1046
+ }
1047
+
1048
+ /**
1049
+ * Recursively sorts object keys for deterministic JSON comparison.
1050
+ * Postgres jsonb may canonicalize key order, so two semantically equal
1051
+ * objects can have different key insertion order.
1052
+ */
1053
+ function stableStringify(value: unknown): string {
1054
+ return JSON.stringify(value, (_key, val) => {
1055
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
1056
+ const sorted: Record<string, unknown> = {};
1057
+ for (const k of Object.keys(val as Record<string, unknown>).sort()) {
1058
+ sorted[k] = (val as Record<string, unknown>)[k];
1059
+ }
1060
+ return sorted;
1061
+ }
1062
+ return val;
1063
+ });
1064
+ }
1065
+
1066
+ function literalValuesEqual(a: unknown, b: unknown): boolean {
1067
+ if (a === b) return true;
1068
+ if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
1069
+ return stableStringify(a) === stableStringify(b);
1070
+ }
1071
+ if (typeof a === 'object' && a !== null && typeof b === 'string') {
1072
+ try {
1073
+ return stableStringify(a) === stableStringify(JSON.parse(b));
1074
+ } catch {
1075
+ return false;
1076
+ }
1077
+ }
1078
+ if (typeof a === 'string' && typeof b === 'object' && b !== null) {
1079
+ try {
1080
+ return stableStringify(JSON.parse(a)) === stableStringify(b);
1081
+ } catch {
1082
+ return false;
1083
+ }
1084
+ }
1085
+ return false;
1086
+ }
1087
+
1088
+ function formatLiteralValue(value: unknown): string {
1089
+ if (value instanceof Date) {
1090
+ return value.toISOString();
1091
+ }
1092
+ if (isTaggedBigInt(value)) {
1093
+ return value.value;
1094
+ }
1095
+ if (typeof value === 'bigint') {
1096
+ return value.toString();
1097
+ }
1098
+ if (typeof value === 'string') {
1099
+ return value;
1100
+ }
1101
+ return JSON.stringify(value);
1102
+ }