@prisma-next/family-sql 0.3.0-dev.4 → 0.3.0-dev.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -6
- package/dist/assembly-BVS641kd.mjs +106 -0
- package/dist/assembly-BVS641kd.mjs.map +1 -0
- package/dist/control-adapter.d.mts +60 -0
- package/dist/control-adapter.d.mts.map +1 -0
- package/dist/control-adapter.mjs +1 -0
- package/dist/control-instance-CWKSpACr.d.mts +292 -0
- package/dist/control-instance-CWKSpACr.d.mts.map +1 -0
- package/dist/control.d.mts +64 -0
- package/dist/control.d.mts.map +1 -0
- package/dist/control.mjs +534 -0
- package/dist/control.mjs.map +1 -0
- package/dist/runtime.d.mts +27 -0
- package/dist/runtime.d.mts.map +1 -0
- package/dist/runtime.mjs +38 -0
- package/dist/runtime.mjs.map +1 -0
- package/dist/schema-verify.d.mts +48 -0
- package/dist/schema-verify.d.mts.map +1 -0
- package/dist/schema-verify.mjs +4 -0
- package/dist/test-utils.d.mts +2 -0
- package/dist/test-utils.mjs +3 -0
- package/dist/verify-BfMETJcM.mjs +108 -0
- package/dist/verify-BfMETJcM.mjs.map +1 -0
- package/dist/verify-sql-schema-DMG0mz1g.mjs +997 -0
- package/dist/verify-sql-schema-DMG0mz1g.mjs.map +1 -0
- package/dist/verify-sql-schema-DhHnkpPa.d.mts +67 -0
- package/dist/verify-sql-schema-DhHnkpPa.d.mts.map +1 -0
- package/dist/{exports/verify.d.ts → verify.d.mts} +8 -5
- package/dist/verify.d.mts.map +1 -0
- package/dist/verify.mjs +3 -0
- package/package.json +38 -48
- package/src/core/assembly.ts +216 -0
- package/src/core/control-adapter.ts +67 -0
- package/src/core/control-descriptor.ts +37 -0
- package/src/core/control-instance.ts +750 -0
- package/src/core/migrations/plan-helpers.ts +164 -0
- package/src/core/migrations/policies.ts +8 -0
- package/src/core/migrations/types.ts +279 -0
- package/src/core/runtime-descriptor.ts +23 -0
- package/src/core/runtime-instance.ts +22 -0
- package/src/core/schema-verify/verify-helpers.ts +532 -0
- package/src/core/schema-verify/verify-sql-schema.ts +1102 -0
- package/src/core/verify.ts +168 -0
- package/src/exports/control-adapter.ts +1 -0
- package/src/exports/control.ts +59 -0
- package/src/exports/runtime.ts +3 -0
- package/src/exports/schema-verify.ts +19 -0
- package/src/exports/test-utils.ts +10 -0
- package/src/exports/verify.ts +1 -0
- package/dist/exports/chunk-6P44BVZ4.js +0 -580
- package/dist/exports/chunk-6P44BVZ4.js.map +0 -1
- package/dist/exports/chunk-C3GKWCKA.js +0 -96
- package/dist/exports/chunk-C3GKWCKA.js.map +0 -1
- package/dist/exports/chunk-F252JMEU.js +0 -772
- package/dist/exports/chunk-F252JMEU.js.map +0 -1
- package/dist/exports/control-adapter.d.ts +0 -44
- package/dist/exports/control-adapter.js +0 -1
- package/dist/exports/control-adapter.js.map +0 -1
- package/dist/exports/control.d.ts +0 -75
- package/dist/exports/control.js +0 -149
- package/dist/exports/control.js.map +0 -1
- package/dist/exports/instance-DiZi2k_2.d.ts +0 -127
- package/dist/exports/runtime.d.ts +0 -66
- package/dist/exports/runtime.js +0 -64
- package/dist/exports/runtime.js.map +0 -1
- package/dist/exports/schema-verify.d.ts +0 -75
- package/dist/exports/schema-verify.js +0 -11
- package/dist/exports/schema-verify.js.map +0 -1
- package/dist/exports/test-utils.d.ts +0 -33
- package/dist/exports/test-utils.js +0 -17
- package/dist/exports/test-utils.js.map +0 -1
- package/dist/exports/types-Bh7ftf0Q.d.ts +0 -275
- package/dist/exports/verify.js +0 -11
- package/dist/exports/verify.js.map +0 -1
|
@@ -0,0 +1,1102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure SQL schema verification function.
|
|
3
|
+
*
|
|
4
|
+
* This module provides a pure function that verifies a SqlSchemaIR against
|
|
5
|
+
* a SqlContract without requiring a database connection. It can be reused
|
|
6
|
+
* by migration planners and other tools that need to compare schema states.
|
|
7
|
+
*/
|
|
8
|
+
|
|
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';
|
|
12
|
+
import type {
|
|
13
|
+
OperationContext,
|
|
14
|
+
SchemaIssue,
|
|
15
|
+
SchemaVerificationNode,
|
|
16
|
+
VerifyDatabaseSchemaResult,
|
|
17
|
+
} from '@prisma-next/core-control-plane/types';
|
|
18
|
+
import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
|
|
19
|
+
import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
|
|
20
|
+
import { ifDefined } from '@prisma-next/utils/defined';
|
|
21
|
+
import { extractCodecControlHooks } from '../assembly';
|
|
22
|
+
import type { CodecControlHooks, ComponentDatabaseDependency } from '../migrations/types';
|
|
23
|
+
import {
|
|
24
|
+
arraysEqual,
|
|
25
|
+
computeCounts,
|
|
26
|
+
verifyDatabaseDependencies,
|
|
27
|
+
verifyForeignKeys,
|
|
28
|
+
verifyIndexes,
|
|
29
|
+
verifyPrimaryKey,
|
|
30
|
+
verifyUniqueConstraints,
|
|
31
|
+
} from './verify-helpers';
|
|
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
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Options for the pure schema verification function.
|
|
51
|
+
*/
|
|
52
|
+
export interface VerifySqlSchemaOptions {
|
|
53
|
+
/** The validated SQL contract to verify against */
|
|
54
|
+
readonly contract: SqlContract<SqlStorage>;
|
|
55
|
+
/** The schema IR from introspection (or another source) */
|
|
56
|
+
readonly schema: SqlSchemaIR;
|
|
57
|
+
/** Whether to run in strict mode (detects extra tables/columns) */
|
|
58
|
+
readonly strict: boolean;
|
|
59
|
+
/** Optional operation context for metadata */
|
|
60
|
+
readonly context?: OperationContext;
|
|
61
|
+
/** Type metadata registry for codec consistency warnings */
|
|
62
|
+
readonly typeMetadataRegistry: ReadonlyMap<string, { nativeType?: string }>;
|
|
63
|
+
/**
|
|
64
|
+
* Active framework components participating in this composition.
|
|
65
|
+
* All components must have matching familyId ('sql') and targetId.
|
|
66
|
+
*/
|
|
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;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Verifies that a SqlSchemaIR matches a SqlContract.
|
|
84
|
+
*
|
|
85
|
+
* This is a pure function that does NOT perform any database I/O.
|
|
86
|
+
* It takes an already-introspected schema IR and compares it against
|
|
87
|
+
* the contract requirements.
|
|
88
|
+
*
|
|
89
|
+
* @param options - Verification options
|
|
90
|
+
* @returns VerifyDatabaseSchemaResult with verification tree and issues
|
|
91
|
+
*/
|
|
92
|
+
export function verifySqlSchema(options: VerifySqlSchemaOptions): VerifyDatabaseSchemaResult {
|
|
93
|
+
const {
|
|
94
|
+
contract,
|
|
95
|
+
schema,
|
|
96
|
+
strict,
|
|
97
|
+
context,
|
|
98
|
+
typeMetadataRegistry,
|
|
99
|
+
normalizeDefault,
|
|
100
|
+
normalizeNativeType,
|
|
101
|
+
} = options;
|
|
102
|
+
const startTime = Date.now();
|
|
103
|
+
|
|
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
|
+
}
|
|
164
|
+
|
|
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;
|
|
252
|
+
const issues: SchemaIssue[] = [];
|
|
253
|
+
const rootChildren: SchemaVerificationNode[] = [];
|
|
254
|
+
const contractTables = contract.storage.tables;
|
|
255
|
+
const schemaTables = schema.tables;
|
|
256
|
+
|
|
257
|
+
for (const [tableName, contractTable] of Object.entries(contractTables)) {
|
|
258
|
+
const schemaTable = schemaTables[tableName];
|
|
259
|
+
const tablePath = `storage.tables.${tableName}`;
|
|
260
|
+
|
|
261
|
+
if (!schemaTable) {
|
|
262
|
+
issues.push({
|
|
263
|
+
kind: 'missing_table',
|
|
264
|
+
table: tableName,
|
|
265
|
+
message: `Table "${tableName}" is missing from database`,
|
|
266
|
+
});
|
|
267
|
+
rootChildren.push({
|
|
268
|
+
status: 'fail',
|
|
269
|
+
kind: 'table',
|
|
270
|
+
name: `table ${tableName}`,
|
|
271
|
+
contractPath: tablePath,
|
|
272
|
+
code: 'missing_table',
|
|
273
|
+
message: `Table "${tableName}" is missing`,
|
|
274
|
+
expected: undefined,
|
|
275
|
+
actual: undefined,
|
|
276
|
+
children: [],
|
|
277
|
+
});
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
|
|
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
|
+
}
|
|
295
|
+
|
|
296
|
+
if (strict) {
|
|
297
|
+
for (const tableName of Object.keys(schemaTables)) {
|
|
298
|
+
if (!contractTables[tableName]) {
|
|
299
|
+
issues.push({
|
|
300
|
+
kind: 'extra_table',
|
|
301
|
+
table: tableName,
|
|
302
|
+
message: `Extra table "${tableName}" found in database (not in contract)`,
|
|
303
|
+
});
|
|
304
|
+
rootChildren.push({
|
|
305
|
+
status: 'fail',
|
|
306
|
+
kind: 'table',
|
|
307
|
+
name: `table ${tableName}`,
|
|
308
|
+
contractPath: `storage.tables.${tableName}`,
|
|
309
|
+
code: 'extra_table',
|
|
310
|
+
message: `Extra table "${tableName}" found`,
|
|
311
|
+
expected: undefined,
|
|
312
|
+
actual: undefined,
|
|
313
|
+
children: [],
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return { issues, rootChildren };
|
|
320
|
+
}
|
|
321
|
+
|
|
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
|
+
}
|
|
371
|
+
|
|
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: [],
|
|
390
|
+
});
|
|
391
|
+
} else {
|
|
392
|
+
tableChildren.push({
|
|
393
|
+
status: 'pass',
|
|
394
|
+
kind: 'primaryKey',
|
|
395
|
+
name: `primary key: ${contractTable.primaryKey.columns.join(', ')}`,
|
|
396
|
+
contractPath: `${tablePath}.primaryKey`,
|
|
397
|
+
code: '',
|
|
398
|
+
message: '',
|
|
399
|
+
expected: undefined,
|
|
400
|
+
actual: undefined,
|
|
401
|
+
children: [],
|
|
402
|
+
});
|
|
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
|
+
}
|
|
422
|
+
|
|
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;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
columnNodes.push(
|
|
524
|
+
verifyColumn({
|
|
525
|
+
tableName,
|
|
526
|
+
columnName,
|
|
527
|
+
contractColumn,
|
|
528
|
+
schemaColumn,
|
|
529
|
+
columnPath,
|
|
530
|
+
issues,
|
|
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]) {
|
|
553
|
+
issues.push({
|
|
554
|
+
kind: 'extra_column',
|
|
555
|
+
table: tableName,
|
|
556
|
+
column: columnName,
|
|
557
|
+
message: `Extra column "${tableName}"."${columnName}" found in database (not in contract)`,
|
|
558
|
+
});
|
|
559
|
+
columnNodes.push({
|
|
560
|
+
status: 'fail',
|
|
561
|
+
kind: 'column',
|
|
562
|
+
name: `${columnName}: extra`,
|
|
563
|
+
contractPath: `${tablePath}.columns.${columnName}`,
|
|
564
|
+
code: 'extra_column',
|
|
565
|
+
message: `Extra column "${columnName}" found`,
|
|
566
|
+
expected: undefined,
|
|
567
|
+
actual: nativeType,
|
|
568
|
+
children: [],
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
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';
|
|
599
|
+
|
|
600
|
+
const contractNativeType = renderExpectedNativeType(contractColumn, codecHooks);
|
|
601
|
+
const schemaNativeType =
|
|
602
|
+
normalizeNativeType?.(schemaColumn.nativeType) ?? schemaColumn.nativeType;
|
|
603
|
+
|
|
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}"`,
|
|
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';
|
|
625
|
+
}
|
|
626
|
+
|
|
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
|
+
});
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
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';
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
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
|
+
}
|
|
804
|
+
|
|
805
|
+
function buildRootNode(rootChildren: SchemaVerificationNode[]): SchemaVerificationNode {
|
|
806
|
+
return {
|
|
807
|
+
status: aggregateChildState(rootChildren, 'pass').status,
|
|
808
|
+
kind: 'contract',
|
|
809
|
+
name: 'contract',
|
|
810
|
+
contractPath: '',
|
|
811
|
+
code: '',
|
|
812
|
+
message: '',
|
|
813
|
+
expected: undefined,
|
|
814
|
+
actual: undefined,
|
|
815
|
+
children: rootChildren,
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
|
|
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
|
+
}
|
|
827
|
+
|
|
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 = '';
|
|
839
|
+
|
|
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
|
+
}
|
|
856
|
+
|
|
857
|
+
return { status, failureMessages, firstCode };
|
|
858
|
+
}
|
|
859
|
+
|
|
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
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Type predicate to check if a component has database dependencies with an init array.
|
|
885
|
+
* The familyId check is redundant since TargetBoundComponentDescriptor<'sql', T> already
|
|
886
|
+
* guarantees familyId is 'sql' at the type level, so we don't need runtime checks for it.
|
|
887
|
+
*/
|
|
888
|
+
function hasDatabaseDependenciesInit<T extends string>(
|
|
889
|
+
component: TargetBoundComponentDescriptor<'sql', T>,
|
|
890
|
+
): component is TargetBoundComponentDescriptor<'sql', T> & {
|
|
891
|
+
readonly databaseDependencies: {
|
|
892
|
+
readonly init: readonly ComponentDatabaseDependency<T>[];
|
|
893
|
+
};
|
|
894
|
+
} {
|
|
895
|
+
if (!('databaseDependencies' in component)) {
|
|
896
|
+
return false;
|
|
897
|
+
}
|
|
898
|
+
const dbDeps = (component as Record<string, unknown>)['databaseDependencies'];
|
|
899
|
+
if (dbDeps === undefined || dbDeps === null || typeof dbDeps !== 'object') {
|
|
900
|
+
return false;
|
|
901
|
+
}
|
|
902
|
+
const depsRecord = dbDeps as Record<string, unknown>;
|
|
903
|
+
const init = depsRecord['init'];
|
|
904
|
+
if (init === undefined || !Array.isArray(init)) {
|
|
905
|
+
return false;
|
|
906
|
+
}
|
|
907
|
+
return true;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
function collectDependenciesFromFrameworkComponents<T extends string>(
|
|
911
|
+
components: ReadonlyArray<TargetBoundComponentDescriptor<'sql', T>>,
|
|
912
|
+
): ReadonlyArray<ComponentDatabaseDependency<T>> {
|
|
913
|
+
const dependencies: ComponentDatabaseDependency<T>[] = [];
|
|
914
|
+
for (const component of components) {
|
|
915
|
+
if (hasDatabaseDependenciesInit(component)) {
|
|
916
|
+
dependencies.push(...component.databaseDependencies.init);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
return dependencies;
|
|
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
|
+
}
|