@prisma-next/family-sql 0.3.0-dev.4 → 0.3.0-dev.6

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 (68) hide show
  1. package/dist/{exports/chunk-6P44BVZ4.js → chunk-6K3RPBDP.js} +3 -3
  2. package/dist/chunk-6K3RPBDP.js.map +1 -0
  3. package/dist/{exports/chunk-F252JMEU.js → chunk-BHEGVBY7.js} +1 -1
  4. package/dist/chunk-BHEGVBY7.js.map +1 -0
  5. package/dist/{exports/chunk-C3GKWCKA.js → chunk-SU7LN2UH.js} +1 -1
  6. package/dist/chunk-SU7LN2UH.js.map +1 -0
  7. package/dist/core/assembly.d.ts +25 -0
  8. package/dist/core/assembly.d.ts.map +1 -0
  9. package/dist/core/control-adapter.d.ts +42 -0
  10. package/dist/core/control-adapter.d.ts.map +1 -0
  11. package/dist/core/descriptor.d.ts +31 -0
  12. package/dist/core/descriptor.d.ts.map +1 -0
  13. package/dist/{exports/instance-DiZi2k_2.d.ts → core/instance.d.ts} +30 -15
  14. package/dist/core/instance.d.ts.map +1 -0
  15. package/dist/core/migrations/plan-helpers.d.ts +20 -0
  16. package/dist/core/migrations/plan-helpers.d.ts.map +1 -0
  17. package/dist/core/migrations/policies.d.ts +6 -0
  18. package/dist/core/migrations/policies.d.ts.map +1 -0
  19. package/dist/{exports/types-Bh7ftf0Q.d.ts → core/migrations/types.d.ts} +41 -36
  20. package/dist/core/migrations/types.d.ts.map +1 -0
  21. package/dist/core/runtime-descriptor.d.ts +19 -0
  22. package/dist/core/runtime-descriptor.d.ts.map +1 -0
  23. package/dist/core/runtime-instance.d.ts +54 -0
  24. package/dist/core/runtime-instance.d.ts.map +1 -0
  25. package/dist/core/schema-verify/verify-helpers.d.ts +50 -0
  26. package/dist/core/schema-verify/verify-helpers.d.ts.map +1 -0
  27. package/dist/core/schema-verify/verify-sql-schema.d.ts +45 -0
  28. package/dist/core/schema-verify/verify-sql-schema.d.ts.map +1 -0
  29. package/dist/core/verify.d.ts +39 -0
  30. package/dist/core/verify.d.ts.map +1 -0
  31. package/dist/exports/control-adapter.d.ts +2 -44
  32. package/dist/exports/control-adapter.d.ts.map +1 -0
  33. package/dist/exports/control.d.ts +8 -70
  34. package/dist/exports/control.d.ts.map +1 -0
  35. package/dist/exports/control.js +3 -3
  36. package/dist/exports/runtime.d.ts +3 -61
  37. package/dist/exports/runtime.d.ts.map +1 -0
  38. package/dist/exports/schema-verify.d.ts +8 -72
  39. package/dist/exports/schema-verify.d.ts.map +1 -0
  40. package/dist/exports/schema-verify.js +1 -1
  41. package/dist/exports/test-utils.d.ts +5 -31
  42. package/dist/exports/test-utils.d.ts.map +1 -0
  43. package/dist/exports/test-utils.js +3 -3
  44. package/dist/exports/verify.d.ts +2 -28
  45. package/dist/exports/verify.d.ts.map +1 -0
  46. package/dist/exports/verify.js +1 -1
  47. package/package.json +19 -18
  48. package/src/core/assembly.ts +117 -0
  49. package/src/core/control-adapter.ts +52 -0
  50. package/src/core/descriptor.ts +37 -0
  51. package/src/core/instance.ts +887 -0
  52. package/src/core/migrations/plan-helpers.ts +164 -0
  53. package/src/core/migrations/policies.ts +8 -0
  54. package/src/core/migrations/types.ts +380 -0
  55. package/src/core/runtime-descriptor.ts +45 -0
  56. package/src/core/runtime-instance.ts +144 -0
  57. package/src/core/schema-verify/verify-helpers.ts +514 -0
  58. package/src/core/schema-verify/verify-sql-schema.ts +584 -0
  59. package/src/core/verify.ts +177 -0
  60. package/src/exports/control-adapter.ts +1 -0
  61. package/src/exports/control.ts +56 -0
  62. package/src/exports/runtime.ts +7 -0
  63. package/src/exports/schema-verify.ts +11 -0
  64. package/src/exports/test-utils.ts +11 -0
  65. package/src/exports/verify.ts +1 -0
  66. package/dist/exports/chunk-6P44BVZ4.js.map +0 -1
  67. package/dist/exports/chunk-C3GKWCKA.js.map +0 -1
  68. package/dist/exports/chunk-F252JMEU.js.map +0 -1
@@ -0,0 +1,887 @@
1
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';
2
+ import type { ContractIR } from '@prisma-next/contract/ir';
3
+ import type { OperationManifest } from '@prisma-next/contract/pack-manifest-types';
4
+ import type { ContractMarkerRecord, TypesImportSpec } from '@prisma-next/contract/types';
5
+ import { emit } from '@prisma-next/core-control-plane/emission';
6
+ import type { CoreSchemaView, SchemaTreeNode } from '@prisma-next/core-control-plane/schema-view';
7
+ import type {
8
+ ControlAdapterDescriptor,
9
+ ControlDriverInstance,
10
+ ControlExtensionDescriptor,
11
+ ControlFamilyInstance,
12
+ ControlTargetDescriptor,
13
+ EmitContractResult,
14
+ OperationContext,
15
+ SignDatabaseResult,
16
+ VerifyDatabaseResult,
17
+ VerifyDatabaseSchemaResult,
18
+ } from '@prisma-next/core-control-plane/types';
19
+ import type { OperationRegistry } from '@prisma-next/operations';
20
+ import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
21
+ import { sqlTargetFamilyHook } from '@prisma-next/sql-contract-emitter';
22
+ import { validateContract } from '@prisma-next/sql-contract-ts/contract';
23
+ import type { SqlOperationSignature } from '@prisma-next/sql-operations';
24
+ import {
25
+ ensureSchemaStatement,
26
+ ensureTableStatement,
27
+ writeContractMarker,
28
+ } from '@prisma-next/sql-runtime';
29
+ import type { SqlSchemaIR, SqlTableIR } from '@prisma-next/sql-schema-ir/types';
30
+ import { ifDefined } from '@prisma-next/utils/defined';
31
+ import {
32
+ assembleOperationRegistry,
33
+ extractCodecTypeImports,
34
+ extractExtensionIds,
35
+ extractOperationTypeImports,
36
+ } from './assembly';
37
+ import type { SqlControlAdapter } from './control-adapter';
38
+ import type { SqlControlTargetDescriptor } from './migrations/types';
39
+ import { verifySqlSchema } from './schema-verify/verify-sql-schema';
40
+ import { collectSupportedCodecTypeIds, readMarker } from './verify';
41
+
42
+ /**
43
+ * Converts an OperationManifest (descriptor declarative data) to a SqlOperationSignature.
44
+ * This is SQL-family-specific conversion logic used by instance creation and test utilities.
45
+ */
46
+ export function convertOperationManifest(manifest: OperationManifest): SqlOperationSignature {
47
+ return {
48
+ forTypeId: manifest.for,
49
+ method: manifest.method,
50
+ args: manifest.args.map((arg: OperationManifest['args'][number]) => {
51
+ if (arg.kind === 'typeId') {
52
+ if (!arg.type) {
53
+ throw new Error('typeId arg must have type property');
54
+ }
55
+ return { kind: 'typeId' as const, type: arg.type };
56
+ }
57
+ if (arg.kind === 'param') {
58
+ return { kind: 'param' as const };
59
+ }
60
+ if (arg.kind === 'literal') {
61
+ return { kind: 'literal' as const };
62
+ }
63
+ throw new Error(`Invalid arg kind: ${(arg as { kind: unknown }).kind}`);
64
+ }),
65
+ returns: (() => {
66
+ if (manifest.returns.kind === 'typeId') {
67
+ return { kind: 'typeId' as const, type: manifest.returns.type };
68
+ }
69
+ if (manifest.returns.kind === 'builtin') {
70
+ return {
71
+ kind: 'builtin' as const,
72
+ type: manifest.returns.type as 'number' | 'boolean' | 'string',
73
+ };
74
+ }
75
+ throw new Error(`Invalid return kind: ${(manifest.returns as { kind: unknown }).kind}`);
76
+ })(),
77
+ lowering: {
78
+ targetFamily: 'sql',
79
+ strategy: manifest.lowering.strategy,
80
+ template: manifest.lowering.template,
81
+ },
82
+ ...(manifest.capabilities ? { capabilities: manifest.capabilities } : {}),
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Extracts codec type IDs used in contract storage tables.
88
+ * Uses type guards to safely access SQL-specific structure without importing SQL types.
89
+ */
90
+ function extractCodecTypeIdsFromContract(contract: unknown): readonly string[] {
91
+ const typeIds = new Set<string>();
92
+
93
+ // Type guard for SQL contract structure
94
+ if (
95
+ typeof contract === 'object' &&
96
+ contract !== null &&
97
+ 'storage' in contract &&
98
+ typeof contract.storage === 'object' &&
99
+ contract.storage !== null &&
100
+ 'tables' in contract.storage
101
+ ) {
102
+ const storage = contract.storage as { tables?: Record<string, unknown> };
103
+ if (storage.tables && typeof storage.tables === 'object') {
104
+ for (const table of Object.values(storage.tables)) {
105
+ if (
106
+ typeof table === 'object' &&
107
+ table !== null &&
108
+ 'columns' in table &&
109
+ typeof table.columns === 'object' &&
110
+ table.columns !== null
111
+ ) {
112
+ const columns = table.columns as Record<string, { codecId: string } | undefined>;
113
+ for (const column of Object.values(columns)) {
114
+ if (
115
+ column &&
116
+ typeof column === 'object' &&
117
+ 'codecId' in column &&
118
+ typeof column.codecId === 'string'
119
+ ) {
120
+ typeIds.add(column.codecId);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ return Array.from(typeIds).sort();
129
+ }
130
+
131
+ /**
132
+ * Creates a VerifyDatabaseResult object with common structure.
133
+ */
134
+ function createVerifyResult(options: {
135
+ ok: boolean;
136
+ code?: string;
137
+ summary: string;
138
+ contractCoreHash: string;
139
+ contractProfileHash?: string;
140
+ marker?: ContractMarkerRecord;
141
+ expectedTargetId: string;
142
+ actualTargetId?: string;
143
+ missingCodecs?: readonly string[];
144
+ codecCoverageSkipped?: boolean;
145
+ configPath?: string;
146
+ contractPath: string;
147
+ totalTime: number;
148
+ }): VerifyDatabaseResult {
149
+ const contract: { coreHash: string; profileHash?: string } = {
150
+ coreHash: options.contractCoreHash,
151
+ };
152
+ if (options.contractProfileHash) {
153
+ contract.profileHash = options.contractProfileHash;
154
+ }
155
+
156
+ const target: { expected: string; actual?: string } = {
157
+ expected: options.expectedTargetId,
158
+ };
159
+ if (options.actualTargetId) {
160
+ target.actual = options.actualTargetId;
161
+ }
162
+
163
+ const meta: { contractPath: string; configPath?: string } = {
164
+ contractPath: options.contractPath,
165
+ };
166
+ if (options.configPath) {
167
+ meta.configPath = options.configPath;
168
+ }
169
+
170
+ const result: VerifyDatabaseResult = {
171
+ ok: options.ok,
172
+ summary: options.summary,
173
+ contract,
174
+ target,
175
+ meta,
176
+ timings: {
177
+ total: options.totalTime,
178
+ },
179
+ };
180
+
181
+ if (options.code) {
182
+ (result as { code?: string }).code = options.code;
183
+ }
184
+
185
+ if (options.marker) {
186
+ (result as { marker?: { coreHash: string; profileHash: string } }).marker = {
187
+ coreHash: options.marker.coreHash,
188
+ profileHash: options.marker.profileHash,
189
+ };
190
+ }
191
+
192
+ if (options.missingCodecs) {
193
+ (result as { missingCodecs?: readonly string[] }).missingCodecs = options.missingCodecs;
194
+ }
195
+
196
+ if (options.codecCoverageSkipped) {
197
+ (result as { codecCoverageSkipped?: boolean }).codecCoverageSkipped =
198
+ options.codecCoverageSkipped;
199
+ }
200
+
201
+ return result;
202
+ }
203
+
204
+ /**
205
+ * Type metadata for SQL storage types.
206
+ * Maps contract storage type IDs to native database types.
207
+ */
208
+ interface SqlTypeMetadata {
209
+ readonly typeId: string;
210
+ readonly familyId: 'sql';
211
+ readonly targetId: string;
212
+ readonly nativeType?: string;
213
+ }
214
+
215
+ /**
216
+ * Registry mapping type IDs to their metadata.
217
+ * Keyed by contract storage type ID (e.g., 'pg/int4@1').
218
+ */
219
+ type SqlTypeMetadataRegistry = Map<string, SqlTypeMetadata>;
220
+
221
+ /**
222
+ * State fields for SQL family instance that hold assembly data.
223
+ */
224
+ interface SqlFamilyInstanceState {
225
+ readonly operationRegistry: OperationRegistry;
226
+ readonly codecTypeImports: ReadonlyArray<TypesImportSpec>;
227
+ readonly operationTypeImports: ReadonlyArray<TypesImportSpec>;
228
+ readonly extensionIds: ReadonlyArray<string>;
229
+ readonly typeMetadataRegistry: SqlTypeMetadataRegistry;
230
+ }
231
+
232
+ /**
233
+ * Options for schema verification.
234
+ */
235
+ export interface SchemaVerifyOptions {
236
+ readonly driver: ControlDriverInstance<'sql', string>;
237
+ readonly contractIR: unknown;
238
+ readonly strict: boolean;
239
+ readonly context?: OperationContext;
240
+ /**
241
+ * Active framework components participating in this composition.
242
+ * All components must have matching familyId ('sql') and targetId.
243
+ */
244
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
245
+ }
246
+
247
+ /**
248
+ * SQL control family instance interface.
249
+ * Extends ControlFamilyInstance with SQL-specific domain actions.
250
+ */
251
+ export interface SqlControlFamilyInstance
252
+ extends ControlFamilyInstance<'sql'>,
253
+ SqlFamilyInstanceState {
254
+ /**
255
+ * Validates a contract JSON and returns a validated ContractIR (without mappings).
256
+ * Mappings are runtime-only and should not be part of ContractIR.
257
+ */
258
+ validateContractIR(contractJson: unknown): ContractIR;
259
+
260
+ /**
261
+ * Verifies the database marker against the contract.
262
+ * Compares target, coreHash, and profileHash.
263
+ */
264
+ verify(options: {
265
+ readonly driver: ControlDriverInstance<'sql', string>;
266
+ readonly contractIR: unknown;
267
+ readonly expectedTargetId: string;
268
+ readonly contractPath: string;
269
+ readonly configPath?: string;
270
+ }): Promise<VerifyDatabaseResult>;
271
+
272
+ /**
273
+ * Verifies the database schema against the contract.
274
+ * Compares contract requirements against live database schema.
275
+ */
276
+ schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult>;
277
+
278
+ /**
279
+ * Signs the database with the contract marker.
280
+ * Writes or updates the contract marker if schema verification passes.
281
+ * This operation is idempotent - if the marker already matches, no changes are made.
282
+ */
283
+ sign(options: {
284
+ readonly driver: ControlDriverInstance<'sql', string>;
285
+ readonly contractIR: unknown;
286
+ readonly contractPath: string;
287
+ readonly configPath?: string;
288
+ }): Promise<SignDatabaseResult>;
289
+
290
+ /**
291
+ * Introspects the database schema and returns a family-specific schema IR.
292
+ *
293
+ * This is a read-only operation that returns a snapshot of the live database schema.
294
+ * The method is family-owned and delegates to target/adapter-specific introspectors
295
+ * to perform the actual schema introspection.
296
+ *
297
+ * @param options - Introspection options
298
+ * @param options.driver - Control plane driver for database connection
299
+ * @param options.contractIR - Optional contract IR for contract-guided introspection.
300
+ * When provided, families may use it for filtering, optimization, or validation
301
+ * during introspection. The contract IR does not change the meaning of "what exists"
302
+ * in the database - it only guides how introspection is performed.
303
+ * @returns Promise resolving to the family-specific Schema IR (e.g., `SqlSchemaIR` for SQL).
304
+ * The IR represents the complete schema snapshot at the time of introspection.
305
+ */
306
+ introspect(options: {
307
+ readonly driver: ControlDriverInstance<'sql', string>;
308
+ readonly contractIR?: unknown;
309
+ }): Promise<SqlSchemaIR>;
310
+
311
+ /**
312
+ * Projects a SQL Schema IR into a core schema view for CLI visualization.
313
+ * Converts SqlSchemaIR (tables, columns, indexes, extensions) into a tree structure.
314
+ */
315
+ toSchemaView(schema: SqlSchemaIR): CoreSchemaView;
316
+
317
+ /**
318
+ * Emits contract JSON and DTS as strings.
319
+ * Uses the instance's preassembled state (operation registry, type imports, extension IDs).
320
+ * Handles stripping mappings and validation internally.
321
+ */
322
+ emitContract(options: { readonly contractIR: ContractIR | unknown }): Promise<EmitContractResult>;
323
+ }
324
+
325
+ /**
326
+ * SQL family instance type.
327
+ * Maintains backward compatibility with FamilyInstance while implementing SqlControlFamilyInstance.
328
+ */
329
+ export type SqlFamilyInstance = SqlControlFamilyInstance;
330
+
331
+ interface CreateSqlFamilyInstanceOptions<TTargetId extends string, TTargetDetails> {
332
+ readonly target: SqlControlTargetDescriptor<TTargetId, TTargetDetails>;
333
+ readonly adapter: ControlAdapterDescriptor<'sql', string, SqlControlAdapter>;
334
+ readonly extensionPacks: readonly ControlExtensionDescriptor<'sql', string>[];
335
+ }
336
+
337
+ /**
338
+ * Builds a SQL type metadata registry from extension pack manifests.
339
+ * Collects type metadata from target, adapter, and extension pack manifests.
340
+ *
341
+ * @param options - Descriptors for target, adapter, and extensions
342
+ * @returns Registry mapping type IDs to their metadata, filtered by targetId
343
+ */
344
+ function buildSqlTypeMetadataRegistry(options: {
345
+ readonly target: ControlTargetDescriptor<'sql', string>;
346
+ readonly adapter: ControlAdapterDescriptor<'sql', string>;
347
+ readonly extensionPacks: readonly ControlExtensionDescriptor<'sql', string>[];
348
+ }): SqlTypeMetadataRegistry {
349
+ const { target, adapter, extensionPacks: extensions } = options;
350
+ const registry = new Map<string, SqlTypeMetadata>();
351
+
352
+ // Get targetId from adapter (they should match)
353
+ const targetId = adapter.targetId;
354
+
355
+ // Collect descriptors to iterate over
356
+ const descriptors = [target, adapter, ...extensions];
357
+
358
+ // Iterate over each descriptor's types
359
+ for (const descriptor of descriptors) {
360
+ const types = descriptor.types;
361
+ const storageTypes = types?.storage;
362
+
363
+ if (!storageTypes) {
364
+ continue;
365
+ }
366
+
367
+ // Filter for SQL family and matching targetId
368
+ for (const storageType of storageTypes) {
369
+ if (storageType.familyId === 'sql' && storageType.targetId === targetId) {
370
+ // Use existing entry if present, otherwise create new one
371
+ // Later entries (extensions) can override earlier ones (adapter/target)
372
+ registry.set(storageType.typeId, {
373
+ typeId: storageType.typeId,
374
+ familyId: 'sql',
375
+ targetId: storageType.targetId,
376
+ ...(storageType.nativeType !== undefined ? { nativeType: storageType.nativeType } : {}),
377
+ });
378
+ }
379
+ }
380
+ }
381
+
382
+ return registry;
383
+ }
384
+
385
+ /**
386
+ * Creates a SQL family instance for control-plane operations.
387
+ */
388
+ export function createSqlFamilyInstance<TTargetId extends string, TTargetDetails>(
389
+ options: CreateSqlFamilyInstanceOptions<TTargetId, TTargetDetails>,
390
+ ): SqlFamilyInstance {
391
+ const { target, adapter, extensionPacks: extensions = [] } = options;
392
+
393
+ // Build descriptors array for assembly
394
+ // Assembly functions only use manifest and id, so we can pass Control*Descriptor types directly
395
+ const descriptors = [target, adapter, ...extensions];
396
+
397
+ // Assemble operation registry, type imports, and extension IDs
398
+ const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest);
399
+ const codecTypeImports = extractCodecTypeImports(descriptors);
400
+ const operationTypeImports = extractOperationTypeImports(descriptors);
401
+ const extensionIds = extractExtensionIds(adapter, target, extensions);
402
+
403
+ // Build type metadata registry from manifests
404
+ const typeMetadataRegistry = buildSqlTypeMetadataRegistry({
405
+ target,
406
+ adapter,
407
+ extensionPacks: extensions,
408
+ });
409
+
410
+ /**
411
+ * Strips mappings from a contract (mappings are runtime-only).
412
+ */
413
+ function stripMappings(contract: unknown): unknown {
414
+ // Type guard to check if contract has mappings
415
+ if (typeof contract === 'object' && contract !== null && 'mappings' in contract) {
416
+ const { mappings: _mappings, ...contractIR } = contract as {
417
+ mappings?: unknown;
418
+ [key: string]: unknown;
419
+ };
420
+ return contractIR;
421
+ }
422
+ return contract;
423
+ }
424
+
425
+ return {
426
+ familyId: 'sql',
427
+ operationRegistry,
428
+ codecTypeImports,
429
+ operationTypeImports,
430
+ extensionIds,
431
+ typeMetadataRegistry,
432
+
433
+ validateContractIR(contractJson: unknown): ContractIR {
434
+ // Validate the contract (this normalizes and validates structure/logic)
435
+ const validated = validateContract<SqlContract<SqlStorage>>(contractJson);
436
+ // Strip mappings before returning ContractIR (mappings are runtime-only)
437
+ // The validated contract has all required ContractIR properties
438
+ const { mappings: _mappings, ...contractIR } = validated;
439
+ return contractIR as ContractIR;
440
+ },
441
+
442
+ async verify(verifyOptions: {
443
+ readonly driver: ControlDriverInstance<'sql', string>;
444
+ readonly contractIR: unknown;
445
+ readonly expectedTargetId: string;
446
+ readonly contractPath: string;
447
+ readonly configPath?: string;
448
+ }): Promise<VerifyDatabaseResult> {
449
+ const { driver, contractIR, expectedTargetId, contractPath, configPath } = verifyOptions;
450
+ const startTime = Date.now();
451
+
452
+ // Type guard to ensure contract has required properties
453
+ if (
454
+ typeof contractIR !== 'object' ||
455
+ contractIR === null ||
456
+ !('coreHash' in contractIR) ||
457
+ !('target' in contractIR) ||
458
+ typeof contractIR.coreHash !== 'string' ||
459
+ typeof contractIR.target !== 'string'
460
+ ) {
461
+ throw new Error('Contract is missing required fields: coreHash or target');
462
+ }
463
+
464
+ // Extract contract hashes and target
465
+ const contractCoreHash = contractIR.coreHash;
466
+ const contractProfileHash =
467
+ 'profileHash' in contractIR && typeof contractIR.profileHash === 'string'
468
+ ? contractIR.profileHash
469
+ : undefined;
470
+ const contractTarget = contractIR.target;
471
+
472
+ // Read marker from database
473
+ const marker = await readMarker(driver);
474
+
475
+ // Compute codec coverage (optional)
476
+ let missingCodecs: readonly string[] | undefined;
477
+ let codecCoverageSkipped = false;
478
+ const supportedTypeIds = collectSupportedCodecTypeIds<'sql', string>([
479
+ adapter,
480
+ target,
481
+ ...extensions,
482
+ ]);
483
+ if (supportedTypeIds.length === 0) {
484
+ // Helper is present but returns empty (MVP behavior)
485
+ // Coverage check is skipped - missingCodecs remains undefined
486
+ codecCoverageSkipped = true;
487
+ } else {
488
+ const supportedSet = new Set(supportedTypeIds);
489
+ const usedTypeIds = extractCodecTypeIdsFromContract(contractIR);
490
+ const missing = usedTypeIds.filter((id) => !supportedSet.has(id));
491
+ if (missing.length > 0) {
492
+ missingCodecs = missing;
493
+ }
494
+ }
495
+
496
+ // Check marker presence
497
+ if (!marker) {
498
+ const totalTime = Date.now() - startTime;
499
+ return createVerifyResult({
500
+ ok: false,
501
+ code: 'PN-RTM-3001',
502
+ summary: 'Marker missing',
503
+ contractCoreHash,
504
+ expectedTargetId,
505
+ contractPath,
506
+ totalTime,
507
+ ...(contractProfileHash ? { contractProfileHash } : {}),
508
+ ...(missingCodecs ? { missingCodecs } : {}),
509
+ ...(codecCoverageSkipped ? { codecCoverageSkipped } : {}),
510
+ ...(configPath ? { configPath } : {}),
511
+ });
512
+ }
513
+
514
+ // Compare target
515
+ if (contractTarget !== expectedTargetId) {
516
+ const totalTime = Date.now() - startTime;
517
+ return createVerifyResult({
518
+ ok: false,
519
+ code: 'PN-RTM-3003',
520
+ summary: 'Target mismatch',
521
+ contractCoreHash,
522
+ marker,
523
+ expectedTargetId,
524
+ actualTargetId: contractTarget,
525
+ contractPath,
526
+ totalTime,
527
+ ...(contractProfileHash ? { contractProfileHash } : {}),
528
+ ...(missingCodecs ? { missingCodecs } : {}),
529
+ ...(codecCoverageSkipped ? { codecCoverageSkipped } : {}),
530
+ ...(configPath ? { configPath } : {}),
531
+ });
532
+ }
533
+
534
+ // Compare hashes
535
+ if (marker.coreHash !== contractCoreHash) {
536
+ const totalTime = Date.now() - startTime;
537
+ return createVerifyResult({
538
+ ok: false,
539
+ code: 'PN-RTM-3002',
540
+ summary: 'Hash mismatch',
541
+ contractCoreHash,
542
+ marker,
543
+ expectedTargetId,
544
+ contractPath,
545
+ totalTime,
546
+ ...(contractProfileHash ? { contractProfileHash } : {}),
547
+ ...(missingCodecs ? { missingCodecs } : {}),
548
+ ...(codecCoverageSkipped ? { codecCoverageSkipped } : {}),
549
+ ...(configPath ? { configPath } : {}),
550
+ });
551
+ }
552
+
553
+ // Compare profile hash if present
554
+ if (contractProfileHash && marker.profileHash !== contractProfileHash) {
555
+ const totalTime = Date.now() - startTime;
556
+ return createVerifyResult({
557
+ ok: false,
558
+ code: 'PN-RTM-3002',
559
+ summary: 'Hash mismatch',
560
+ contractCoreHash,
561
+ contractProfileHash,
562
+ marker,
563
+ expectedTargetId,
564
+ contractPath,
565
+ totalTime,
566
+ ...(missingCodecs ? { missingCodecs } : {}),
567
+ ...(codecCoverageSkipped ? { codecCoverageSkipped } : {}),
568
+ ...(configPath ? { configPath } : {}),
569
+ });
570
+ }
571
+
572
+ // Success - all checks passed
573
+ const totalTime = Date.now() - startTime;
574
+ return createVerifyResult({
575
+ ok: true,
576
+ summary: 'Database matches contract',
577
+ contractCoreHash,
578
+ marker,
579
+ expectedTargetId,
580
+ contractPath,
581
+ totalTime,
582
+ ...(contractProfileHash ? { contractProfileHash } : {}),
583
+ ...(missingCodecs ? { missingCodecs } : {}),
584
+ ...(codecCoverageSkipped ? { codecCoverageSkipped } : {}),
585
+ ...(configPath ? { configPath } : {}),
586
+ });
587
+ },
588
+
589
+ async schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult> {
590
+ const { driver, contractIR, strict, context, frameworkComponents } = options;
591
+
592
+ // Validate contractIR as SqlContract<SqlStorage>
593
+ const contract = validateContract<SqlContract<SqlStorage>>(contractIR);
594
+
595
+ // Introspect live schema (DB I/O)
596
+ const controlAdapter = adapter.create();
597
+ const schemaIR = await controlAdapter.introspect(driver, contractIR);
598
+
599
+ // Pure verification (no I/O) - delegates to extracted pure function
600
+ return verifySqlSchema({
601
+ contract,
602
+ schema: schemaIR,
603
+ strict,
604
+ ...ifDefined('context', context),
605
+ typeMetadataRegistry,
606
+ frameworkComponents,
607
+ });
608
+ },
609
+ async sign(options: {
610
+ readonly driver: ControlDriverInstance<'sql', string>;
611
+ readonly contractIR: unknown;
612
+ readonly contractPath: string;
613
+ readonly configPath?: string;
614
+ }): Promise<SignDatabaseResult> {
615
+ const { driver, contractIR, contractPath, configPath } = options;
616
+ const startTime = Date.now();
617
+
618
+ // Validate contractIR as SqlContract<SqlStorage>
619
+ const contract = validateContract<SqlContract<SqlStorage>>(contractIR);
620
+
621
+ // Extract contract hashes and target
622
+ const contractCoreHash = contract.coreHash;
623
+ const contractProfileHash =
624
+ 'profileHash' in contract && typeof contract.profileHash === 'string'
625
+ ? contract.profileHash
626
+ : contractCoreHash;
627
+ const contractTarget = contract.target;
628
+
629
+ // Ensure marker schema and table exist
630
+ await driver.query(ensureSchemaStatement.sql, ensureSchemaStatement.params);
631
+ await driver.query(ensureTableStatement.sql, ensureTableStatement.params);
632
+
633
+ // Read existing marker
634
+ const existingMarker = await readMarker(driver);
635
+
636
+ // Determine if we need to write/update marker
637
+ let markerCreated = false;
638
+ let markerUpdated = false;
639
+ let previousHashes: { coreHash?: string; profileHash?: string } | undefined;
640
+
641
+ if (!existingMarker) {
642
+ // No marker exists - insert new one
643
+ const write = writeContractMarker({
644
+ coreHash: contractCoreHash,
645
+ profileHash: contractProfileHash,
646
+ contractJson: contractIR,
647
+ canonicalVersion: 1,
648
+ });
649
+ await driver.query(write.insert.sql, write.insert.params);
650
+ markerCreated = true;
651
+ } else {
652
+ // Marker exists - check if hashes differ
653
+ const existingCoreHash = existingMarker.coreHash;
654
+ const existingProfileHash = existingMarker.profileHash;
655
+
656
+ // Compare hashes (use strict equality to ensure exact match)
657
+ const coreHashMatches = existingCoreHash === contractCoreHash;
658
+ const profileHashMatches = existingProfileHash === contractProfileHash;
659
+
660
+ if (!coreHashMatches || !profileHashMatches) {
661
+ // Hashes differ - update marker and capture previous hashes for output
662
+ previousHashes = {
663
+ coreHash: existingCoreHash,
664
+ profileHash: existingProfileHash,
665
+ };
666
+ const write = writeContractMarker({
667
+ coreHash: contractCoreHash,
668
+ profileHash: contractProfileHash,
669
+ contractJson: contractIR,
670
+ canonicalVersion: existingMarker.canonicalVersion ?? 1,
671
+ });
672
+ await driver.query(write.update.sql, write.update.params);
673
+ markerUpdated = true;
674
+ }
675
+ // If hashes match, no-op (idempotent) - previousHashes remains undefined
676
+ }
677
+
678
+ // Build summary message
679
+ let summary: string;
680
+ if (markerCreated) {
681
+ summary = 'Database signed (marker created)';
682
+ } else if (markerUpdated) {
683
+ summary = `Database signed (marker updated from ${previousHashes?.coreHash ?? 'unknown'})`;
684
+ } else {
685
+ summary = 'Database already signed with this contract';
686
+ }
687
+
688
+ const totalTime = Date.now() - startTime;
689
+
690
+ return {
691
+ ok: true,
692
+ summary,
693
+ contract: {
694
+ coreHash: contractCoreHash,
695
+ profileHash: contractProfileHash,
696
+ },
697
+ target: {
698
+ expected: contractTarget,
699
+ actual: contractTarget,
700
+ },
701
+ marker: {
702
+ created: markerCreated,
703
+ updated: markerUpdated,
704
+ ...(previousHashes ? { previous: previousHashes } : {}),
705
+ },
706
+ meta: {
707
+ contractPath,
708
+ ...(configPath ? { configPath } : {}),
709
+ },
710
+ timings: {
711
+ total: totalTime,
712
+ },
713
+ };
714
+ },
715
+ async readMarker(options: {
716
+ readonly driver: ControlDriverInstance<'sql', string>;
717
+ }): Promise<ContractMarkerRecord | null> {
718
+ return readMarker(options.driver);
719
+ },
720
+ async introspect(options: {
721
+ readonly driver: ControlDriverInstance<'sql', string>;
722
+ readonly contractIR?: unknown;
723
+ }): Promise<SqlSchemaIR> {
724
+ const { driver, contractIR } = options;
725
+
726
+ const controlAdapter = adapter.create();
727
+ return controlAdapter.introspect(driver, contractIR);
728
+ },
729
+
730
+ toSchemaView(schema: SqlSchemaIR): CoreSchemaView {
731
+ const rootLabel = 'contract';
732
+
733
+ // Build table nodes
734
+ const tableNodes: readonly SchemaTreeNode[] = Object.entries(schema.tables).map(
735
+ ([tableName, table]: [string, SqlTableIR]) => {
736
+ const children: SchemaTreeNode[] = [];
737
+
738
+ // Add column nodes grouped under "columns"
739
+ const columnNodes: SchemaTreeNode[] = [];
740
+ for (const [columnName, column] of Object.entries(table.columns)) {
741
+ const nullableText = column.nullable ? '(nullable)' : '(not nullable)';
742
+ // Always display nativeType for introspection (database state)
743
+ const typeDisplay = column.nativeType;
744
+ const label = `${columnName}: ${typeDisplay} ${nullableText}`;
745
+ columnNodes.push({
746
+ kind: 'field',
747
+ id: `column-${tableName}-${columnName}`,
748
+ label,
749
+ meta: {
750
+ nativeType: column.nativeType,
751
+ nullable: column.nullable,
752
+ },
753
+ });
754
+ }
755
+
756
+ // Add "columns" grouping node if there are columns
757
+ if (columnNodes.length > 0) {
758
+ children.push({
759
+ kind: 'collection',
760
+ id: `columns-${tableName}`,
761
+ label: 'columns',
762
+ children: columnNodes,
763
+ });
764
+ }
765
+
766
+ // Add primary key node if present
767
+ if (table.primaryKey) {
768
+ const pkColumns = table.primaryKey.columns.join(', ');
769
+ children.push({
770
+ kind: 'index',
771
+ id: `primary-key-${tableName}`,
772
+ label: `primary key: ${pkColumns}`,
773
+ meta: {
774
+ columns: table.primaryKey.columns,
775
+ ...(table.primaryKey.name ? { name: table.primaryKey.name } : {}),
776
+ },
777
+ });
778
+ }
779
+
780
+ // Add unique constraint nodes
781
+ for (const unique of table.uniques) {
782
+ const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_unique`;
783
+ const label = `unique ${name}`;
784
+ children.push({
785
+ kind: 'index',
786
+ id: `unique-${tableName}-${name}`,
787
+ label,
788
+ meta: {
789
+ columns: unique.columns,
790
+ unique: true,
791
+ },
792
+ });
793
+ }
794
+
795
+ // Add index nodes
796
+ for (const index of table.indexes) {
797
+ const name = index.name ?? `${tableName}_${index.columns.join('_')}_idx`;
798
+ const label = index.unique ? `unique index ${name}` : `index ${name}`;
799
+ children.push({
800
+ kind: 'index',
801
+ id: `index-${tableName}-${name}`,
802
+ label,
803
+ meta: {
804
+ columns: index.columns,
805
+ unique: index.unique,
806
+ },
807
+ });
808
+ }
809
+
810
+ // Build table meta
811
+ const tableMeta: Record<string, unknown> = {};
812
+ if (table.primaryKey) {
813
+ tableMeta['primaryKey'] = table.primaryKey.columns;
814
+ if (table.primaryKey.name) {
815
+ tableMeta['primaryKeyName'] = table.primaryKey.name;
816
+ }
817
+ }
818
+ if (table.foreignKeys.length > 0) {
819
+ tableMeta['foreignKeys'] = table.foreignKeys.map((fk) => ({
820
+ columns: fk.columns,
821
+ referencedTable: fk.referencedTable,
822
+ referencedColumns: fk.referencedColumns,
823
+ ...(fk.name ? { name: fk.name } : {}),
824
+ }));
825
+ }
826
+
827
+ const node: SchemaTreeNode = {
828
+ kind: 'entity',
829
+ id: `table-${tableName}`,
830
+ label: `table ${tableName}`,
831
+ ...(Object.keys(tableMeta).length > 0 ? { meta: tableMeta } : {}),
832
+ ...(children.length > 0 ? { children: children as readonly SchemaTreeNode[] } : {}),
833
+ };
834
+ return node;
835
+ },
836
+ );
837
+
838
+ // Add extension nodes (format: "extensionName extension is enabled")
839
+ const extensionNodes: readonly SchemaTreeNode[] = schema.extensions.map((extName) => ({
840
+ kind: 'extension',
841
+ id: `extension-${extName}`,
842
+ label: `${extName} extension is enabled`,
843
+ }));
844
+
845
+ // Combine all children
846
+ const rootChildren = [...tableNodes, ...extensionNodes];
847
+
848
+ const rootNode: SchemaTreeNode = {
849
+ kind: 'root',
850
+ id: 'sql-schema',
851
+ label: rootLabel,
852
+ ...(rootChildren.length > 0 ? { children: rootChildren } : {}),
853
+ };
854
+
855
+ return {
856
+ root: rootNode,
857
+ };
858
+ },
859
+
860
+ async emitContract({ contractIR }): Promise<EmitContractResult> {
861
+ // Strip mappings if present (mappings are runtime-only)
862
+ const contractWithoutMappings = stripMappings(contractIR);
863
+
864
+ // Validate and normalize the contract
865
+ const validatedIR = this.validateContractIR(contractWithoutMappings);
866
+
867
+ const result = await emit(
868
+ validatedIR,
869
+ {
870
+ outputDir: '',
871
+ operationRegistry,
872
+ codecTypeImports,
873
+ operationTypeImports,
874
+ extensionIds,
875
+ },
876
+ sqlTargetFamilyHook,
877
+ );
878
+
879
+ return {
880
+ contractJson: result.contractJson,
881
+ contractDts: result.contractDts,
882
+ coreHash: result.coreHash,
883
+ profileHash: result.profileHash,
884
+ };
885
+ },
886
+ };
887
+ }