@prisma-next/family-sql 0.3.0-dev.2 → 0.3.0-dev.21

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