@prisma-next/family-sql 0.1.0-dev.2 → 0.1.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.
@@ -1,1354 +1,11 @@
1
1
  import {
2
- collectSupportedCodecTypeIds,
3
- readMarker
4
- } from "./chunk-3HYKCN35.js";
2
+ createSqlFamilyInstance
3
+ } from "./chunk-LECWNGKN.js";
4
+ import "./chunk-C3GKWCKA.js";
5
+ import "./chunk-54XYY6SU.js";
5
6
 
6
7
  // src/core/descriptor.ts
7
- import { sqlTargetFamilyHook as sqlTargetFamilyHook2 } from "@prisma-next/sql-contract-emitter";
8
-
9
- // src/core/instance.ts
10
- import { emit } from "@prisma-next/core-control-plane/emission";
11
8
  import { sqlTargetFamilyHook } from "@prisma-next/sql-contract-emitter";
12
- import { validateContract } from "@prisma-next/sql-contract-ts/contract";
13
- import {
14
- ensureSchemaStatement,
15
- ensureTableStatement,
16
- writeContractMarker
17
- } from "@prisma-next/sql-runtime";
18
-
19
- // src/core/assembly.ts
20
- import { createOperationRegistry } from "@prisma-next/operations";
21
- function assembleOperationRegistry(descriptors, convertOperationManifest2) {
22
- const registry = createOperationRegistry();
23
- for (const descriptor of descriptors) {
24
- const operations = descriptor.manifest.operations ?? [];
25
- for (const operationManifest of operations) {
26
- const signature = convertOperationManifest2(operationManifest);
27
- registry.register(signature);
28
- }
29
- }
30
- return registry;
31
- }
32
- function extractCodecTypeImports(descriptors) {
33
- const imports = [];
34
- for (const descriptor of descriptors) {
35
- const codecTypes = descriptor.manifest.types?.codecTypes;
36
- if (codecTypes?.import) {
37
- imports.push(codecTypes.import);
38
- }
39
- }
40
- return imports;
41
- }
42
- function extractOperationTypeImports(descriptors) {
43
- const imports = [];
44
- for (const descriptor of descriptors) {
45
- const operationTypes = descriptor.manifest.types?.operationTypes;
46
- if (operationTypes?.import) {
47
- imports.push(operationTypes.import);
48
- }
49
- }
50
- return imports;
51
- }
52
- function extractExtensionIds(adapter, target, extensions) {
53
- const ids = [];
54
- const seen = /* @__PURE__ */ new Set();
55
- if (!seen.has(adapter.id)) {
56
- ids.push(adapter.id);
57
- seen.add(adapter.id);
58
- }
59
- if (!seen.has(target.id)) {
60
- ids.push(target.id);
61
- seen.add(target.id);
62
- }
63
- for (const ext of extensions) {
64
- if (!seen.has(ext.id)) {
65
- ids.push(ext.id);
66
- seen.add(ext.id);
67
- }
68
- }
69
- return ids;
70
- }
71
-
72
- // src/core/instance.ts
73
- function convertOperationManifest(manifest) {
74
- return {
75
- forTypeId: manifest.for,
76
- method: manifest.method,
77
- args: manifest.args.map((arg) => {
78
- if (arg.kind === "typeId") {
79
- if (!arg.type) {
80
- throw new Error("typeId arg must have type property");
81
- }
82
- return { kind: "typeId", type: arg.type };
83
- }
84
- if (arg.kind === "param") {
85
- return { kind: "param" };
86
- }
87
- if (arg.kind === "literal") {
88
- return { kind: "literal" };
89
- }
90
- throw new Error(`Invalid arg kind: ${arg.kind}`);
91
- }),
92
- returns: (() => {
93
- if (manifest.returns.kind === "typeId") {
94
- return { kind: "typeId", type: manifest.returns.type };
95
- }
96
- if (manifest.returns.kind === "builtin") {
97
- return {
98
- kind: "builtin",
99
- type: manifest.returns.type
100
- };
101
- }
102
- throw new Error(`Invalid return kind: ${manifest.returns.kind}`);
103
- })(),
104
- lowering: {
105
- targetFamily: "sql",
106
- strategy: manifest.lowering.strategy,
107
- template: manifest.lowering.template
108
- },
109
- ...manifest.capabilities ? { capabilities: manifest.capabilities } : {}
110
- };
111
- }
112
- function extractCodecTypeIdsFromContract(contract) {
113
- const typeIds = /* @__PURE__ */ new Set();
114
- if (typeof contract === "object" && contract !== null && "storage" in contract && typeof contract.storage === "object" && contract.storage !== null && "tables" in contract.storage) {
115
- const storage = contract.storage;
116
- if (storage.tables && typeof storage.tables === "object") {
117
- for (const table of Object.values(storage.tables)) {
118
- if (typeof table === "object" && table !== null && "columns" in table && typeof table.columns === "object" && table.columns !== null) {
119
- const columns = table.columns;
120
- for (const column of Object.values(columns)) {
121
- if (column && typeof column === "object" && "codecId" in column && typeof column.codecId === "string") {
122
- typeIds.add(column.codecId);
123
- }
124
- }
125
- }
126
- }
127
- }
128
- }
129
- return Array.from(typeIds).sort();
130
- }
131
- function arraysEqual(a, b) {
132
- if (a.length !== b.length) {
133
- return false;
134
- }
135
- for (let i = 0; i < a.length; i++) {
136
- if (a[i] !== b[i]) {
137
- return false;
138
- }
139
- }
140
- return true;
141
- }
142
- function comparePrimaryKey(contractPK, schemaPK, tableName, issues) {
143
- if (!schemaPK) {
144
- issues.push({
145
- kind: "primary_key_mismatch",
146
- table: tableName,
147
- expected: contractPK.columns.join(", "),
148
- message: `Table "${tableName}" is missing primary key`
149
- });
150
- return "fail";
151
- }
152
- if (!arraysEqual(contractPK.columns, schemaPK.columns)) {
153
- issues.push({
154
- kind: "primary_key_mismatch",
155
- table: tableName,
156
- expected: contractPK.columns.join(", "),
157
- actual: schemaPK.columns.join(", "),
158
- message: `Table "${tableName}" has primary key mismatch: expected columns [${contractPK.columns.join(", ")}], got [${schemaPK.columns.join(", ")}]`
159
- });
160
- return "fail";
161
- }
162
- if (contractPK.name && schemaPK.name && contractPK.name !== schemaPK.name) {
163
- issues.push({
164
- kind: "primary_key_mismatch",
165
- table: tableName,
166
- indexOrConstraint: contractPK.name,
167
- expected: contractPK.name,
168
- actual: schemaPK.name,
169
- message: `Table "${tableName}" has primary key name mismatch: expected "${contractPK.name}", got "${schemaPK.name}"`
170
- });
171
- return "fail";
172
- }
173
- return "pass";
174
- }
175
- function compareForeignKeys(contractFKs, schemaFKs, tableName, tablePath, issues, strict) {
176
- const nodes = [];
177
- for (const contractFK of contractFKs) {
178
- const fkPath = `${tablePath}.foreignKeys[${contractFK.columns.join(",")}]`;
179
- const matchingFK = schemaFKs.find((fk) => {
180
- return arraysEqual(fk.columns, contractFK.columns) && fk.referencedTable === contractFK.references.table && arraysEqual(fk.referencedColumns, contractFK.references.columns);
181
- });
182
- if (!matchingFK) {
183
- issues.push({
184
- kind: "foreign_key_mismatch",
185
- table: tableName,
186
- expected: `${contractFK.columns.join(", ")} -> ${contractFK.references.table}(${contractFK.references.columns.join(", ")})`,
187
- message: `Table "${tableName}" is missing foreign key: ${contractFK.columns.join(", ")} -> ${contractFK.references.table}(${contractFK.references.columns.join(", ")})`
188
- });
189
- nodes.push({
190
- status: "fail",
191
- kind: "foreignKey",
192
- name: `foreignKey(${contractFK.columns.join(", ")})`,
193
- contractPath: fkPath,
194
- code: "foreign_key_mismatch",
195
- message: "Foreign key missing",
196
- expected: contractFK,
197
- actual: void 0,
198
- children: []
199
- });
200
- } else {
201
- if (contractFK.name && matchingFK.name && contractFK.name !== matchingFK.name) {
202
- issues.push({
203
- kind: "foreign_key_mismatch",
204
- table: tableName,
205
- indexOrConstraint: contractFK.name,
206
- expected: contractFK.name,
207
- actual: matchingFK.name,
208
- message: `Table "${tableName}" has foreign key name mismatch: expected "${contractFK.name}", got "${matchingFK.name}"`
209
- });
210
- nodes.push({
211
- status: "fail",
212
- kind: "foreignKey",
213
- name: `foreignKey(${contractFK.columns.join(", ")})`,
214
- contractPath: fkPath,
215
- code: "foreign_key_mismatch",
216
- message: "Foreign key name mismatch",
217
- expected: contractFK.name,
218
- actual: matchingFK.name,
219
- children: []
220
- });
221
- } else {
222
- nodes.push({
223
- status: "pass",
224
- kind: "foreignKey",
225
- name: `foreignKey(${contractFK.columns.join(", ")})`,
226
- contractPath: fkPath,
227
- code: "",
228
- message: "",
229
- expected: void 0,
230
- actual: void 0,
231
- children: []
232
- });
233
- }
234
- }
235
- }
236
- if (strict) {
237
- for (const schemaFK of schemaFKs) {
238
- const matchingFK = contractFKs.find((fk) => {
239
- return arraysEqual(fk.columns, schemaFK.columns) && fk.references.table === schemaFK.referencedTable && arraysEqual(fk.references.columns, schemaFK.referencedColumns);
240
- });
241
- if (!matchingFK) {
242
- issues.push({
243
- kind: "foreign_key_mismatch",
244
- table: tableName,
245
- message: `Extra foreign key found in database (not in contract): ${schemaFK.columns.join(", ")} -> ${schemaFK.referencedTable}(${schemaFK.referencedColumns.join(", ")})`
246
- });
247
- nodes.push({
248
- status: "fail",
249
- kind: "foreignKey",
250
- name: `foreignKey(${schemaFK.columns.join(", ")})`,
251
- contractPath: `${tablePath}.foreignKeys[${schemaFK.columns.join(",")}]`,
252
- code: "extra_foreign_key",
253
- message: "Extra foreign key found",
254
- expected: void 0,
255
- actual: schemaFK,
256
- children: []
257
- });
258
- }
259
- }
260
- }
261
- return nodes;
262
- }
263
- function compareUniqueConstraints(contractUniques, schemaUniques, tableName, tablePath, issues, strict) {
264
- const nodes = [];
265
- for (const contractUnique of contractUniques) {
266
- const uniquePath = `${tablePath}.uniques[${contractUnique.columns.join(",")}]`;
267
- const matchingUnique = schemaUniques.find(
268
- (u) => arraysEqual(u.columns, contractUnique.columns)
269
- );
270
- if (!matchingUnique) {
271
- issues.push({
272
- kind: "unique_constraint_mismatch",
273
- table: tableName,
274
- expected: contractUnique.columns.join(", "),
275
- message: `Table "${tableName}" is missing unique constraint: ${contractUnique.columns.join(", ")}`
276
- });
277
- nodes.push({
278
- status: "fail",
279
- kind: "unique",
280
- name: `unique(${contractUnique.columns.join(", ")})`,
281
- contractPath: uniquePath,
282
- code: "unique_constraint_mismatch",
283
- message: "Unique constraint missing",
284
- expected: contractUnique,
285
- actual: void 0,
286
- children: []
287
- });
288
- } else {
289
- if (contractUnique.name && matchingUnique.name && contractUnique.name !== matchingUnique.name) {
290
- issues.push({
291
- kind: "unique_constraint_mismatch",
292
- table: tableName,
293
- indexOrConstraint: contractUnique.name,
294
- expected: contractUnique.name,
295
- actual: matchingUnique.name,
296
- message: `Table "${tableName}" has unique constraint name mismatch: expected "${contractUnique.name}", got "${matchingUnique.name}"`
297
- });
298
- nodes.push({
299
- status: "fail",
300
- kind: "unique",
301
- name: `unique(${contractUnique.columns.join(", ")})`,
302
- contractPath: uniquePath,
303
- code: "unique_constraint_mismatch",
304
- message: "Unique constraint name mismatch",
305
- expected: contractUnique.name,
306
- actual: matchingUnique.name,
307
- children: []
308
- });
309
- } else {
310
- nodes.push({
311
- status: "pass",
312
- kind: "unique",
313
- name: `unique(${contractUnique.columns.join(", ")})`,
314
- contractPath: uniquePath,
315
- code: "",
316
- message: "",
317
- expected: void 0,
318
- actual: void 0,
319
- children: []
320
- });
321
- }
322
- }
323
- }
324
- if (strict) {
325
- for (const schemaUnique of schemaUniques) {
326
- const matchingUnique = contractUniques.find(
327
- (u) => arraysEqual(u.columns, schemaUnique.columns)
328
- );
329
- if (!matchingUnique) {
330
- issues.push({
331
- kind: "unique_constraint_mismatch",
332
- table: tableName,
333
- message: `Extra unique constraint found in database (not in contract): ${schemaUnique.columns.join(", ")}`
334
- });
335
- nodes.push({
336
- status: "fail",
337
- kind: "unique",
338
- name: `unique(${schemaUnique.columns.join(", ")})`,
339
- contractPath: `${tablePath}.uniques[${schemaUnique.columns.join(",")}]`,
340
- code: "extra_unique_constraint",
341
- message: "Extra unique constraint found",
342
- expected: void 0,
343
- actual: schemaUnique,
344
- children: []
345
- });
346
- }
347
- }
348
- }
349
- return nodes;
350
- }
351
- function compareIndexes(contractIndexes, schemaIndexes, tableName, tablePath, issues, strict) {
352
- const nodes = [];
353
- for (const contractIndex of contractIndexes) {
354
- const indexPath = `${tablePath}.indexes[${contractIndex.columns.join(",")}]`;
355
- const matchingIndex = schemaIndexes.find(
356
- (idx) => arraysEqual(idx.columns, contractIndex.columns) && idx.unique === false
357
- );
358
- if (!matchingIndex) {
359
- issues.push({
360
- kind: "index_mismatch",
361
- table: tableName,
362
- expected: contractIndex.columns.join(", "),
363
- message: `Table "${tableName}" is missing index: ${contractIndex.columns.join(", ")}`
364
- });
365
- nodes.push({
366
- status: "fail",
367
- kind: "index",
368
- name: `index(${contractIndex.columns.join(", ")})`,
369
- contractPath: indexPath,
370
- code: "index_mismatch",
371
- message: "Index missing",
372
- expected: contractIndex,
373
- actual: void 0,
374
- children: []
375
- });
376
- } else {
377
- if (contractIndex.name && matchingIndex.name && contractIndex.name !== matchingIndex.name) {
378
- issues.push({
379
- kind: "index_mismatch",
380
- table: tableName,
381
- indexOrConstraint: contractIndex.name,
382
- expected: contractIndex.name,
383
- actual: matchingIndex.name,
384
- message: `Table "${tableName}" has index name mismatch: expected "${contractIndex.name}", got "${matchingIndex.name}"`
385
- });
386
- nodes.push({
387
- status: "fail",
388
- kind: "index",
389
- name: `index(${contractIndex.columns.join(", ")})`,
390
- contractPath: indexPath,
391
- code: "index_mismatch",
392
- message: "Index name mismatch",
393
- expected: contractIndex.name,
394
- actual: matchingIndex.name,
395
- children: []
396
- });
397
- } else {
398
- nodes.push({
399
- status: "pass",
400
- kind: "index",
401
- name: `index(${contractIndex.columns.join(", ")})`,
402
- contractPath: indexPath,
403
- code: "",
404
- message: "",
405
- expected: void 0,
406
- actual: void 0,
407
- children: []
408
- });
409
- }
410
- }
411
- }
412
- if (strict) {
413
- for (const schemaIndex of schemaIndexes) {
414
- if (schemaIndex.unique) {
415
- continue;
416
- }
417
- const matchingIndex = contractIndexes.find(
418
- (idx) => arraysEqual(idx.columns, schemaIndex.columns)
419
- );
420
- if (!matchingIndex) {
421
- issues.push({
422
- kind: "index_mismatch",
423
- table: tableName,
424
- message: `Extra index found in database (not in contract): ${schemaIndex.columns.join(", ")}`
425
- });
426
- nodes.push({
427
- status: "fail",
428
- kind: "index",
429
- name: `index(${schemaIndex.columns.join(", ")})`,
430
- contractPath: `${tablePath}.indexes[${schemaIndex.columns.join(",")}]`,
431
- code: "extra_index",
432
- message: "Extra index found",
433
- expected: void 0,
434
- actual: schemaIndex,
435
- children: []
436
- });
437
- }
438
- }
439
- }
440
- return nodes;
441
- }
442
- function compareExtensions(contractExtensions, schemaExtensions, contractTarget, issues, _strict) {
443
- const nodes = [];
444
- if (!contractExtensions) {
445
- return nodes;
446
- }
447
- const contractExtensionNames = Object.keys(contractExtensions).filter(
448
- (name) => name !== contractTarget
449
- );
450
- for (const extName of contractExtensionNames) {
451
- const extPath = `extensions.${extName}`;
452
- const normalizedExtName = extName.toLowerCase().replace(/^pg/, "");
453
- const matchingExt = schemaExtensions.find((e) => {
454
- const normalizedE = e.toLowerCase();
455
- if (normalizedE === normalizedExtName || normalizedE === extName.toLowerCase()) {
456
- return true;
457
- }
458
- if (normalizedE.includes(normalizedExtName) || normalizedExtName.includes(normalizedE)) {
459
- return true;
460
- }
461
- return false;
462
- });
463
- const extensionLabels = {
464
- pg: "database is postgres",
465
- pgvector: "vector extension is enabled",
466
- vector: "vector extension is enabled"
467
- };
468
- const extensionLabel = extensionLabels[extName] ?? `extension "${extName}" is enabled`;
469
- if (!matchingExt) {
470
- issues.push({
471
- kind: "extension_missing",
472
- table: "",
473
- message: `Extension "${extName}" is missing from database`
474
- });
475
- nodes.push({
476
- status: "fail",
477
- kind: "extension",
478
- name: extensionLabel,
479
- contractPath: extPath,
480
- code: "extension_missing",
481
- message: `Extension "${extName}" is missing`,
482
- expected: void 0,
483
- actual: void 0,
484
- children: []
485
- });
486
- } else {
487
- nodes.push({
488
- status: "pass",
489
- kind: "extension",
490
- name: extensionLabel,
491
- contractPath: extPath,
492
- code: "",
493
- message: "",
494
- expected: void 0,
495
- actual: void 0,
496
- children: []
497
- });
498
- }
499
- }
500
- return nodes;
501
- }
502
- function computeCounts(node) {
503
- let pass = 0;
504
- let warn = 0;
505
- let fail = 0;
506
- function traverse(n) {
507
- if (n.status === "pass") {
508
- pass++;
509
- } else if (n.status === "warn") {
510
- warn++;
511
- } else if (n.status === "fail") {
512
- fail++;
513
- }
514
- if (n.children) {
515
- for (const child of n.children) {
516
- traverse(child);
517
- }
518
- }
519
- }
520
- traverse(node);
521
- return {
522
- pass,
523
- warn,
524
- fail,
525
- totalNodes: pass + warn + fail
526
- };
527
- }
528
- function createVerifyResult(options) {
529
- const contract = {
530
- coreHash: options.contractCoreHash
531
- };
532
- if (options.contractProfileHash) {
533
- contract.profileHash = options.contractProfileHash;
534
- }
535
- const target = {
536
- expected: options.expectedTargetId
537
- };
538
- if (options.actualTargetId) {
539
- target.actual = options.actualTargetId;
540
- }
541
- const meta = {
542
- contractPath: options.contractPath
543
- };
544
- if (options.configPath) {
545
- meta.configPath = options.configPath;
546
- }
547
- const result = {
548
- ok: options.ok,
549
- summary: options.summary,
550
- contract,
551
- target,
552
- meta,
553
- timings: {
554
- total: options.totalTime
555
- }
556
- };
557
- if (options.code) {
558
- result.code = options.code;
559
- }
560
- if (options.marker) {
561
- result.marker = {
562
- coreHash: options.marker.coreHash,
563
- profileHash: options.marker.profileHash
564
- };
565
- }
566
- if (options.missingCodecs) {
567
- result.missingCodecs = options.missingCodecs;
568
- }
569
- if (options.codecCoverageSkipped) {
570
- result.codecCoverageSkipped = options.codecCoverageSkipped;
571
- }
572
- return result;
573
- }
574
- function buildSqlTypeMetadataRegistry(options) {
575
- const { target, adapter, extensions } = options;
576
- const registry = /* @__PURE__ */ new Map();
577
- const targetId = adapter.targetId;
578
- const descriptors = [target, adapter, ...extensions];
579
- for (const descriptor of descriptors) {
580
- const manifest = descriptor.manifest;
581
- const storageTypes = manifest.types?.storage;
582
- if (!storageTypes) {
583
- continue;
584
- }
585
- for (const storageType of storageTypes) {
586
- if (storageType.familyId === "sql" && storageType.targetId === targetId) {
587
- registry.set(storageType.typeId, {
588
- typeId: storageType.typeId,
589
- familyId: "sql",
590
- targetId: storageType.targetId,
591
- ...storageType.nativeType !== void 0 ? { nativeType: storageType.nativeType } : {}
592
- });
593
- }
594
- }
595
- }
596
- return registry;
597
- }
598
- function createSqlFamilyInstance(options) {
599
- const { target, adapter, extensions } = options;
600
- const descriptors = [target, adapter, ...extensions];
601
- const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest);
602
- const codecTypeImports = extractCodecTypeImports(descriptors);
603
- const operationTypeImports = extractOperationTypeImports(descriptors);
604
- const extensionIds = extractExtensionIds(adapter, target, extensions);
605
- const typeMetadataRegistry = buildSqlTypeMetadataRegistry({ target, adapter, extensions });
606
- function stripMappings(contract) {
607
- if (typeof contract === "object" && contract !== null && "mappings" in contract) {
608
- const { mappings: _mappings, ...contractIR } = contract;
609
- return contractIR;
610
- }
611
- return contract;
612
- }
613
- return {
614
- familyId: "sql",
615
- operationRegistry,
616
- codecTypeImports,
617
- operationTypeImports,
618
- extensionIds,
619
- typeMetadataRegistry,
620
- validateContractIR(contractJson) {
621
- const validated = validateContract(contractJson);
622
- const { mappings: _mappings, ...contractIR } = validated;
623
- return contractIR;
624
- },
625
- async verify(verifyOptions) {
626
- const { driver, contractIR, expectedTargetId, contractPath, configPath } = verifyOptions;
627
- const startTime = Date.now();
628
- if (typeof contractIR !== "object" || contractIR === null || !("coreHash" in contractIR) || !("target" in contractIR) || typeof contractIR.coreHash !== "string" || typeof contractIR.target !== "string") {
629
- throw new Error("Contract is missing required fields: coreHash or target");
630
- }
631
- const contractCoreHash = contractIR.coreHash;
632
- const contractProfileHash = "profileHash" in contractIR && typeof contractIR.profileHash === "string" ? contractIR.profileHash : void 0;
633
- const contractTarget = contractIR.target;
634
- const marker = await readMarker(driver);
635
- let missingCodecs;
636
- let codecCoverageSkipped = false;
637
- const supportedTypeIds = collectSupportedCodecTypeIds([
638
- adapter,
639
- target,
640
- ...extensions
641
- ]);
642
- if (supportedTypeIds.length === 0) {
643
- codecCoverageSkipped = true;
644
- } else {
645
- const supportedSet = new Set(supportedTypeIds);
646
- const usedTypeIds = extractCodecTypeIdsFromContract(contractIR);
647
- const missing = usedTypeIds.filter((id) => !supportedSet.has(id));
648
- if (missing.length > 0) {
649
- missingCodecs = missing;
650
- }
651
- }
652
- if (!marker) {
653
- const totalTime2 = Date.now() - startTime;
654
- return createVerifyResult({
655
- ok: false,
656
- code: "PN-RTM-3001",
657
- summary: "Marker missing",
658
- contractCoreHash,
659
- expectedTargetId,
660
- contractPath,
661
- totalTime: totalTime2,
662
- ...contractProfileHash ? { contractProfileHash } : {},
663
- ...missingCodecs ? { missingCodecs } : {},
664
- ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
665
- ...configPath ? { configPath } : {}
666
- });
667
- }
668
- if (contractTarget !== expectedTargetId) {
669
- const totalTime2 = Date.now() - startTime;
670
- return createVerifyResult({
671
- ok: false,
672
- code: "PN-RTM-3003",
673
- summary: "Target mismatch",
674
- contractCoreHash,
675
- marker,
676
- expectedTargetId,
677
- actualTargetId: contractTarget,
678
- contractPath,
679
- totalTime: totalTime2,
680
- ...contractProfileHash ? { contractProfileHash } : {},
681
- ...missingCodecs ? { missingCodecs } : {},
682
- ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
683
- ...configPath ? { configPath } : {}
684
- });
685
- }
686
- if (marker.coreHash !== contractCoreHash) {
687
- const totalTime2 = Date.now() - startTime;
688
- return createVerifyResult({
689
- ok: false,
690
- code: "PN-RTM-3002",
691
- summary: "Hash mismatch",
692
- contractCoreHash,
693
- marker,
694
- expectedTargetId,
695
- contractPath,
696
- totalTime: totalTime2,
697
- ...contractProfileHash ? { contractProfileHash } : {},
698
- ...missingCodecs ? { missingCodecs } : {},
699
- ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
700
- ...configPath ? { configPath } : {}
701
- });
702
- }
703
- if (contractProfileHash && marker.profileHash !== contractProfileHash) {
704
- const totalTime2 = Date.now() - startTime;
705
- return createVerifyResult({
706
- ok: false,
707
- code: "PN-RTM-3002",
708
- summary: "Hash mismatch",
709
- contractCoreHash,
710
- contractProfileHash,
711
- marker,
712
- expectedTargetId,
713
- contractPath,
714
- totalTime: totalTime2,
715
- ...missingCodecs ? { missingCodecs } : {},
716
- ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
717
- ...configPath ? { configPath } : {}
718
- });
719
- }
720
- const totalTime = Date.now() - startTime;
721
- return createVerifyResult({
722
- ok: true,
723
- summary: "Database matches contract",
724
- contractCoreHash,
725
- marker,
726
- expectedTargetId,
727
- contractPath,
728
- totalTime,
729
- ...contractProfileHash ? { contractProfileHash } : {},
730
- ...missingCodecs ? { missingCodecs } : {},
731
- ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
732
- ...configPath ? { configPath } : {}
733
- });
734
- },
735
- async schemaVerify(options2) {
736
- const { driver, contractIR, strict, contractPath, configPath } = options2;
737
- const startTime = Date.now();
738
- const contract = validateContract(contractIR);
739
- const contractCoreHash = contract.coreHash;
740
- const contractProfileHash = "profileHash" in contract && typeof contract.profileHash === "string" ? contract.profileHash : void 0;
741
- const contractTarget = contract.target;
742
- const controlAdapter = adapter.create();
743
- const schemaIR = await controlAdapter.introspect(
744
- driver,
745
- contractIR
746
- );
747
- const issues = [];
748
- const rootChildren = [];
749
- const contractTables = contract.storage.tables;
750
- const schemaTables = schemaIR.tables;
751
- for (const [tableName, contractTable] of Object.entries(contractTables)) {
752
- const schemaTable = schemaTables[tableName];
753
- const tablePath = `storage.tables.${tableName}`;
754
- if (!schemaTable) {
755
- issues.push({
756
- kind: "missing_table",
757
- table: tableName,
758
- message: `Table "${tableName}" is missing from database`
759
- });
760
- rootChildren.push({
761
- status: "fail",
762
- kind: "table",
763
- name: `table ${tableName}`,
764
- contractPath: tablePath,
765
- code: "missing_table",
766
- message: `Table "${tableName}" is missing`,
767
- expected: void 0,
768
- actual: void 0,
769
- children: []
770
- });
771
- continue;
772
- }
773
- const tableChildren = [];
774
- const columnNodes = [];
775
- for (const [columnName, contractColumn] of Object.entries(contractTable.columns)) {
776
- const schemaColumn = schemaTable.columns[columnName];
777
- const columnPath = `${tablePath}.columns.${columnName}`;
778
- if (!schemaColumn) {
779
- issues.push({
780
- kind: "missing_column",
781
- table: tableName,
782
- column: columnName,
783
- message: `Column "${tableName}"."${columnName}" is missing from database`
784
- });
785
- columnNodes.push({
786
- status: "fail",
787
- kind: "column",
788
- name: `${columnName}: missing`,
789
- contractPath: columnPath,
790
- code: "missing_column",
791
- message: `Column "${columnName}" is missing`,
792
- expected: void 0,
793
- actual: void 0,
794
- children: []
795
- });
796
- continue;
797
- }
798
- const columnChildren = [];
799
- let columnStatus = "pass";
800
- const contractNativeType = contractColumn.nativeType;
801
- const schemaNativeType = schemaColumn.nativeType;
802
- if (!contractNativeType) {
803
- issues.push({
804
- kind: "type_mismatch",
805
- table: tableName,
806
- column: columnName,
807
- expected: "nativeType required",
808
- actual: schemaNativeType || "unknown",
809
- message: `Column "${tableName}"."${columnName}" is missing nativeType in contract`
810
- });
811
- columnChildren.push({
812
- status: "fail",
813
- kind: "type",
814
- name: "type",
815
- contractPath: `${columnPath}.nativeType`,
816
- code: "type_mismatch",
817
- message: "Contract column is missing nativeType",
818
- expected: "nativeType required",
819
- actual: schemaNativeType || "unknown",
820
- children: []
821
- });
822
- columnStatus = "fail";
823
- } else if (!schemaNativeType) {
824
- issues.push({
825
- kind: "type_mismatch",
826
- table: tableName,
827
- column: columnName,
828
- expected: contractNativeType,
829
- actual: "unknown",
830
- message: `Column "${tableName}"."${columnName}" has type mismatch: schema column has no nativeType`
831
- });
832
- columnChildren.push({
833
- status: "fail",
834
- kind: "type",
835
- name: "type",
836
- contractPath: `${columnPath}.nativeType`,
837
- code: "type_mismatch",
838
- message: "Schema column has no nativeType",
839
- expected: contractNativeType,
840
- actual: "unknown",
841
- children: []
842
- });
843
- columnStatus = "fail";
844
- } else if (contractNativeType !== schemaNativeType) {
845
- issues.push({
846
- kind: "type_mismatch",
847
- table: tableName,
848
- column: columnName,
849
- expected: contractNativeType,
850
- actual: schemaNativeType,
851
- message: `Column "${tableName}"."${columnName}" has type mismatch: expected "${contractNativeType}", got "${schemaNativeType}"`
852
- });
853
- columnChildren.push({
854
- status: "fail",
855
- kind: "type",
856
- name: "type",
857
- contractPath: `${columnPath}.nativeType`,
858
- code: "type_mismatch",
859
- message: `Type mismatch: expected ${contractNativeType}, got ${schemaNativeType}`,
860
- expected: contractNativeType,
861
- actual: schemaNativeType,
862
- children: []
863
- });
864
- columnStatus = "fail";
865
- }
866
- if (contractColumn.codecId) {
867
- const typeMetadata = typeMetadataRegistry.get(contractColumn.codecId);
868
- if (!typeMetadata) {
869
- columnChildren.push({
870
- status: "warn",
871
- kind: "type",
872
- name: "type_metadata_missing",
873
- contractPath: `${columnPath}.codecId`,
874
- code: "type_metadata_missing",
875
- message: `codecId "${contractColumn.codecId}" not found in type metadata registry`,
876
- expected: contractColumn.codecId,
877
- actual: void 0,
878
- children: []
879
- });
880
- } else if (typeMetadata.nativeType && typeMetadata.nativeType !== contractNativeType) {
881
- columnChildren.push({
882
- status: "warn",
883
- kind: "type",
884
- name: "type_consistency",
885
- contractPath: `${columnPath}.codecId`,
886
- code: "type_consistency_warning",
887
- message: `codecId "${contractColumn.codecId}" maps to nativeType "${typeMetadata.nativeType}" in registry, but contract has "${contractNativeType}"`,
888
- expected: typeMetadata.nativeType,
889
- actual: contractNativeType,
890
- children: []
891
- });
892
- }
893
- }
894
- if (contractColumn.nullable !== schemaColumn.nullable) {
895
- issues.push({
896
- kind: "nullability_mismatch",
897
- table: tableName,
898
- column: columnName,
899
- expected: String(contractColumn.nullable),
900
- actual: String(schemaColumn.nullable),
901
- message: `Column "${tableName}"."${columnName}" has nullability mismatch: expected ${contractColumn.nullable ? "nullable" : "not null"}, got ${schemaColumn.nullable ? "nullable" : "not null"}`
902
- });
903
- columnChildren.push({
904
- status: "fail",
905
- kind: "nullability",
906
- name: "nullability",
907
- contractPath: `${columnPath}.nullable`,
908
- code: "nullability_mismatch",
909
- message: `Nullability mismatch: expected ${contractColumn.nullable ? "nullable" : "not null"}, got ${schemaColumn.nullable ? "nullable" : "not null"}`,
910
- expected: contractColumn.nullable,
911
- actual: schemaColumn.nullable,
912
- children: []
913
- });
914
- columnStatus = "fail";
915
- }
916
- const computedColumnStatus = columnChildren.some((c) => c.status === "fail") ? "fail" : columnChildren.some((c) => c.status === "warn") ? "warn" : "pass";
917
- const finalColumnStatus = columnChildren.length > 0 ? computedColumnStatus : columnStatus;
918
- const nullableText = contractColumn.nullable ? "nullable" : "not nullable";
919
- const columnTypeDisplay = contractColumn.codecId ? `${contractNativeType} (${contractColumn.codecId})` : contractNativeType;
920
- const failureMessages = columnChildren.filter((child) => child.status === "fail" && child.message).map((child) => child.message).filter((msg) => typeof msg === "string" && msg.length > 0);
921
- const columnMessage = finalColumnStatus === "fail" && failureMessages.length > 0 ? failureMessages.join("; ") : "";
922
- const columnCode = finalColumnStatus === "fail" && columnChildren.length > 0 && columnChildren[0] ? columnChildren[0].code : finalColumnStatus === "warn" && columnChildren.length > 0 && columnChildren[0] ? columnChildren[0].code : "";
923
- columnNodes.push({
924
- status: finalColumnStatus,
925
- kind: "column",
926
- name: `${columnName}: ${columnTypeDisplay} (${nullableText})`,
927
- contractPath: columnPath,
928
- code: columnCode,
929
- message: columnMessage,
930
- expected: void 0,
931
- actual: void 0,
932
- children: columnChildren
933
- });
934
- }
935
- if (columnNodes.length > 0) {
936
- const columnsStatus = columnNodes.some((c) => c.status === "fail") ? "fail" : columnNodes.some((c) => c.status === "warn") ? "warn" : "pass";
937
- tableChildren.push({
938
- status: columnsStatus,
939
- kind: "columns",
940
- name: "columns",
941
- contractPath: `${tablePath}.columns`,
942
- code: "",
943
- message: "",
944
- expected: void 0,
945
- actual: void 0,
946
- children: columnNodes
947
- });
948
- }
949
- if (strict) {
950
- for (const [columnName, schemaColumn] of Object.entries(schemaTable.columns)) {
951
- if (!contractTable.columns[columnName]) {
952
- issues.push({
953
- kind: "missing_column",
954
- table: tableName,
955
- column: columnName,
956
- message: `Extra column "${tableName}"."${columnName}" found in database (not in contract)`
957
- });
958
- columnNodes.push({
959
- status: "fail",
960
- kind: "column",
961
- name: `${columnName}: extra`,
962
- contractPath: `${tablePath}.columns.${columnName}`,
963
- code: "extra_column",
964
- message: `Extra column "${columnName}" found`,
965
- expected: void 0,
966
- actual: schemaColumn.nativeType,
967
- children: []
968
- });
969
- }
970
- }
971
- }
972
- if (contractTable.primaryKey) {
973
- const pkStatus = comparePrimaryKey(
974
- contractTable.primaryKey,
975
- schemaTable.primaryKey,
976
- tableName,
977
- issues
978
- );
979
- if (pkStatus === "fail") {
980
- tableChildren.push({
981
- status: "fail",
982
- kind: "primaryKey",
983
- name: `primary key: ${contractTable.primaryKey.columns.join(", ")}`,
984
- contractPath: `${tablePath}.primaryKey`,
985
- code: "primary_key_mismatch",
986
- message: "Primary key mismatch",
987
- expected: contractTable.primaryKey,
988
- actual: schemaTable.primaryKey,
989
- children: []
990
- });
991
- } else {
992
- tableChildren.push({
993
- status: "pass",
994
- kind: "primaryKey",
995
- name: `primary key: ${contractTable.primaryKey.columns.join(", ")}`,
996
- contractPath: `${tablePath}.primaryKey`,
997
- code: "",
998
- message: "",
999
- expected: void 0,
1000
- actual: void 0,
1001
- children: []
1002
- });
1003
- }
1004
- } else if (schemaTable.primaryKey && strict) {
1005
- issues.push({
1006
- kind: "primary_key_mismatch",
1007
- table: tableName,
1008
- message: "Extra primary key found in database (not in contract)"
1009
- });
1010
- tableChildren.push({
1011
- status: "fail",
1012
- kind: "primaryKey",
1013
- name: `primary key: ${schemaTable.primaryKey.columns.join(", ")}`,
1014
- contractPath: `${tablePath}.primaryKey`,
1015
- code: "extra_primary_key",
1016
- message: "Extra primary key found",
1017
- expected: void 0,
1018
- actual: schemaTable.primaryKey,
1019
- children: []
1020
- });
1021
- }
1022
- const fkStatuses = compareForeignKeys(
1023
- contractTable.foreignKeys,
1024
- schemaTable.foreignKeys,
1025
- tableName,
1026
- tablePath,
1027
- issues,
1028
- strict
1029
- );
1030
- tableChildren.push(...fkStatuses);
1031
- const uniqueStatuses = compareUniqueConstraints(
1032
- contractTable.uniques,
1033
- schemaTable.uniques,
1034
- tableName,
1035
- tablePath,
1036
- issues,
1037
- strict
1038
- );
1039
- tableChildren.push(...uniqueStatuses);
1040
- const indexStatuses = compareIndexes(
1041
- contractTable.indexes,
1042
- schemaTable.indexes,
1043
- tableName,
1044
- tablePath,
1045
- issues,
1046
- strict
1047
- );
1048
- tableChildren.push(...indexStatuses);
1049
- const tableStatus = tableChildren.some((c) => c.status === "fail") ? "fail" : tableChildren.some((c) => c.status === "warn") ? "warn" : "pass";
1050
- const tableFailureMessages = tableChildren.filter((child) => child.status === "fail" && child.message).map((child) => child.message).filter((msg) => typeof msg === "string" && msg.length > 0);
1051
- const tableMessage = tableStatus === "fail" && tableFailureMessages.length > 0 ? `${tableFailureMessages.length} issue${tableFailureMessages.length === 1 ? "" : "s"}` : "";
1052
- const tableCode = tableStatus === "fail" && tableChildren.length > 0 && tableChildren[0] ? tableChildren[0].code : "";
1053
- rootChildren.push({
1054
- status: tableStatus,
1055
- kind: "table",
1056
- name: `table ${tableName}`,
1057
- contractPath: tablePath,
1058
- code: tableCode,
1059
- message: tableMessage,
1060
- expected: void 0,
1061
- actual: void 0,
1062
- children: tableChildren
1063
- });
1064
- }
1065
- if (strict) {
1066
- for (const tableName of Object.keys(schemaTables)) {
1067
- if (!contractTables[tableName]) {
1068
- issues.push({
1069
- kind: "missing_table",
1070
- table: tableName,
1071
- message: `Extra table "${tableName}" found in database (not in contract)`
1072
- });
1073
- rootChildren.push({
1074
- status: "fail",
1075
- kind: "table",
1076
- name: `table ${tableName}`,
1077
- contractPath: `storage.tables.${tableName}`,
1078
- code: "extra_table",
1079
- message: `Extra table "${tableName}" found`,
1080
- expected: void 0,
1081
- actual: void 0,
1082
- children: []
1083
- });
1084
- }
1085
- }
1086
- }
1087
- const extensionStatuses = compareExtensions(
1088
- contract.extensions,
1089
- schemaIR.extensions,
1090
- contractTarget,
1091
- issues,
1092
- strict
1093
- );
1094
- rootChildren.push(...extensionStatuses);
1095
- const rootStatus = rootChildren.some((c) => c.status === "fail") ? "fail" : rootChildren.some((c) => c.status === "warn") ? "warn" : "pass";
1096
- const root = {
1097
- status: rootStatus,
1098
- kind: "contract",
1099
- name: "contract",
1100
- contractPath: "",
1101
- code: "",
1102
- message: "",
1103
- expected: void 0,
1104
- actual: void 0,
1105
- children: rootChildren
1106
- };
1107
- const counts = computeCounts(root);
1108
- const ok = counts.fail === 0;
1109
- const code = ok ? void 0 : "PN-SCHEMA-0001";
1110
- const summary = ok ? "Database schema satisfies contract" : `Database schema does not satisfy contract (${counts.fail} failure${counts.fail === 1 ? "" : "s"})`;
1111
- const totalTime = Date.now() - startTime;
1112
- return {
1113
- ok,
1114
- ...code ? { code } : {},
1115
- summary,
1116
- contract: {
1117
- coreHash: contractCoreHash,
1118
- ...contractProfileHash ? { profileHash: contractProfileHash } : {}
1119
- },
1120
- target: {
1121
- expected: contractTarget,
1122
- actual: contractTarget
1123
- },
1124
- schema: {
1125
- issues,
1126
- root,
1127
- counts
1128
- },
1129
- meta: {
1130
- contractPath,
1131
- strict,
1132
- ...configPath ? { configPath } : {}
1133
- },
1134
- timings: {
1135
- total: totalTime
1136
- }
1137
- };
1138
- },
1139
- async sign(options2) {
1140
- const { driver, contractIR, contractPath, configPath } = options2;
1141
- const startTime = Date.now();
1142
- const contract = validateContract(contractIR);
1143
- const contractCoreHash = contract.coreHash;
1144
- const contractProfileHash = "profileHash" in contract && typeof contract.profileHash === "string" ? contract.profileHash : contractCoreHash;
1145
- const contractTarget = contract.target;
1146
- await driver.query(ensureSchemaStatement.sql, ensureSchemaStatement.params);
1147
- await driver.query(ensureTableStatement.sql, ensureTableStatement.params);
1148
- const existingMarker = await readMarker(driver);
1149
- let markerCreated = false;
1150
- let markerUpdated = false;
1151
- let previousHashes;
1152
- if (!existingMarker) {
1153
- const write = writeContractMarker({
1154
- coreHash: contractCoreHash,
1155
- profileHash: contractProfileHash,
1156
- contractJson: contractIR,
1157
- canonicalVersion: 1
1158
- });
1159
- await driver.query(write.insert.sql, write.insert.params);
1160
- markerCreated = true;
1161
- } else {
1162
- const existingCoreHash = existingMarker.coreHash;
1163
- const existingProfileHash = existingMarker.profileHash;
1164
- const coreHashMatches = existingCoreHash === contractCoreHash;
1165
- const profileHashMatches = existingProfileHash === contractProfileHash;
1166
- if (!coreHashMatches || !profileHashMatches) {
1167
- previousHashes = {
1168
- coreHash: existingCoreHash,
1169
- profileHash: existingProfileHash
1170
- };
1171
- const write = writeContractMarker({
1172
- coreHash: contractCoreHash,
1173
- profileHash: contractProfileHash,
1174
- contractJson: contractIR,
1175
- canonicalVersion: existingMarker.canonicalVersion ?? 1
1176
- });
1177
- await driver.query(write.update.sql, write.update.params);
1178
- markerUpdated = true;
1179
- }
1180
- }
1181
- let summary;
1182
- if (markerCreated) {
1183
- summary = "Database signed (marker created)";
1184
- } else if (markerUpdated) {
1185
- summary = `Database signed (marker updated from ${previousHashes?.coreHash ?? "unknown"})`;
1186
- } else {
1187
- summary = "Database already signed with this contract";
1188
- }
1189
- const totalTime = Date.now() - startTime;
1190
- return {
1191
- ok: true,
1192
- summary,
1193
- contract: {
1194
- coreHash: contractCoreHash,
1195
- profileHash: contractProfileHash
1196
- },
1197
- target: {
1198
- expected: contractTarget,
1199
- actual: contractTarget
1200
- },
1201
- marker: {
1202
- created: markerCreated,
1203
- updated: markerUpdated,
1204
- ...previousHashes ? { previous: previousHashes } : {}
1205
- },
1206
- meta: {
1207
- contractPath,
1208
- ...configPath ? { configPath } : {}
1209
- },
1210
- timings: {
1211
- total: totalTime
1212
- }
1213
- };
1214
- },
1215
- async introspect(options2) {
1216
- const { driver, contractIR } = options2;
1217
- const controlAdapter = adapter.create();
1218
- return controlAdapter.introspect(driver, contractIR);
1219
- },
1220
- toSchemaView(schema) {
1221
- const rootLabel = "contract";
1222
- const tableNodes = Object.entries(schema.tables).map(
1223
- ([tableName, table]) => {
1224
- const children = [];
1225
- const columnNodes = [];
1226
- for (const [columnName, column] of Object.entries(table.columns)) {
1227
- const nullableText = column.nullable ? "(nullable)" : "(not nullable)";
1228
- const typeDisplay = column.nativeType;
1229
- const label = `${columnName}: ${typeDisplay} ${nullableText}`;
1230
- columnNodes.push({
1231
- kind: "field",
1232
- id: `column-${tableName}-${columnName}`,
1233
- label,
1234
- meta: {
1235
- nativeType: column.nativeType,
1236
- nullable: column.nullable
1237
- }
1238
- });
1239
- }
1240
- if (columnNodes.length > 0) {
1241
- children.push({
1242
- kind: "collection",
1243
- id: `columns-${tableName}`,
1244
- label: "columns",
1245
- children: columnNodes
1246
- });
1247
- }
1248
- if (table.primaryKey) {
1249
- const pkColumns = table.primaryKey.columns.join(", ");
1250
- children.push({
1251
- kind: "index",
1252
- id: `primary-key-${tableName}`,
1253
- label: `primary key: ${pkColumns}`,
1254
- meta: {
1255
- columns: table.primaryKey.columns,
1256
- ...table.primaryKey.name ? { name: table.primaryKey.name } : {}
1257
- }
1258
- });
1259
- }
1260
- for (const unique of table.uniques) {
1261
- const name = unique.name ?? `${tableName}_${unique.columns.join("_")}_unique`;
1262
- const label = `unique ${name}`;
1263
- children.push({
1264
- kind: "index",
1265
- id: `unique-${tableName}-${name}`,
1266
- label,
1267
- meta: {
1268
- columns: unique.columns,
1269
- unique: true
1270
- }
1271
- });
1272
- }
1273
- for (const index of table.indexes) {
1274
- const name = index.name ?? `${tableName}_${index.columns.join("_")}_idx`;
1275
- const label = index.unique ? `unique index ${name}` : `index ${name}`;
1276
- children.push({
1277
- kind: "index",
1278
- id: `index-${tableName}-${name}`,
1279
- label,
1280
- meta: {
1281
- columns: index.columns,
1282
- unique: index.unique
1283
- }
1284
- });
1285
- }
1286
- const tableMeta = {};
1287
- if (table.primaryKey) {
1288
- tableMeta["primaryKey"] = table.primaryKey.columns;
1289
- if (table.primaryKey.name) {
1290
- tableMeta["primaryKeyName"] = table.primaryKey.name;
1291
- }
1292
- }
1293
- if (table.foreignKeys.length > 0) {
1294
- tableMeta["foreignKeys"] = table.foreignKeys.map((fk) => ({
1295
- columns: fk.columns,
1296
- referencedTable: fk.referencedTable,
1297
- referencedColumns: fk.referencedColumns,
1298
- ...fk.name ? { name: fk.name } : {}
1299
- }));
1300
- }
1301
- const node = {
1302
- kind: "entity",
1303
- id: `table-${tableName}`,
1304
- label: `table ${tableName}`,
1305
- ...Object.keys(tableMeta).length > 0 ? { meta: tableMeta } : {},
1306
- ...children.length > 0 ? { children } : {}
1307
- };
1308
- return node;
1309
- }
1310
- );
1311
- const extensionNodes = schema.extensions.map((extName) => ({
1312
- kind: "extension",
1313
- id: `extension-${extName}`,
1314
- label: `${extName} extension is enabled`
1315
- }));
1316
- const rootChildren = [...tableNodes, ...extensionNodes];
1317
- const rootNode = {
1318
- kind: "root",
1319
- id: "sql-schema",
1320
- label: rootLabel,
1321
- ...rootChildren.length > 0 ? { children: rootChildren } : {}
1322
- };
1323
- return {
1324
- root: rootNode
1325
- };
1326
- },
1327
- async emitContract({ contractIR }) {
1328
- const contractWithoutMappings = stripMappings(contractIR);
1329
- const validatedIR = this.validateContractIR(contractWithoutMappings);
1330
- const result = await emit(
1331
- validatedIR,
1332
- {
1333
- outputDir: "",
1334
- operationRegistry,
1335
- codecTypeImports,
1336
- operationTypeImports,
1337
- extensionIds
1338
- },
1339
- sqlTargetFamilyHook
1340
- );
1341
- return {
1342
- contractJson: result.contractJson,
1343
- contractDts: result.contractDts,
1344
- coreHash: result.coreHash,
1345
- profileHash: result.profileHash
1346
- };
1347
- }
1348
- };
1349
- }
1350
-
1351
- // src/core/descriptor.ts
1352
9
  var sqlFamilyManifest = {
1353
10
  id: "sql",
1354
11
  version: "0.0.1"
@@ -1358,7 +15,7 @@ var SqlFamilyDescriptor = class {
1358
15
  id = "sql";
1359
16
  familyId = "sql";
1360
17
  manifest = sqlFamilyManifest;
1361
- hook = sqlTargetFamilyHook2;
18
+ hook = sqlTargetFamilyHook;
1362
19
  create(options) {
1363
20
  return createSqlFamilyInstance({
1364
21
  target: options.target,
@@ -1368,9 +25,129 @@ var SqlFamilyDescriptor = class {
1368
25
  }
1369
26
  };
1370
27
 
28
+ // src/core/migrations/plan-helpers.ts
29
+ import { notOk, ok } from "@prisma-next/utils/result";
30
+ var readOnlyEmptyObject = Object.freeze({});
31
+ function cloneRecord(value) {
32
+ if (value === readOnlyEmptyObject) {
33
+ return value;
34
+ }
35
+ return Object.freeze({ ...value });
36
+ }
37
+ function freezeSteps(steps) {
38
+ if (steps.length === 0) {
39
+ return Object.freeze([]);
40
+ }
41
+ return Object.freeze(
42
+ steps.map(
43
+ (step) => Object.freeze({
44
+ description: step.description,
45
+ sql: step.sql,
46
+ ...step.meta ? { meta: cloneRecord(step.meta) } : {}
47
+ })
48
+ )
49
+ );
50
+ }
51
+ function freezeDetailsValue(value) {
52
+ if (value === null || value === void 0) {
53
+ return value;
54
+ }
55
+ if (typeof value !== "object") {
56
+ return value;
57
+ }
58
+ if (Array.isArray(value)) {
59
+ return Object.freeze([...value]);
60
+ }
61
+ return Object.freeze({ ...value });
62
+ }
63
+ function freezeTargetDetails(target) {
64
+ return Object.freeze({
65
+ id: target.id,
66
+ ...target.details !== void 0 ? { details: freezeDetailsValue(target.details) } : {}
67
+ });
68
+ }
69
+ function freezeOperation(operation) {
70
+ return Object.freeze({
71
+ id: operation.id,
72
+ label: operation.label,
73
+ ...operation.summary ? { summary: operation.summary } : {},
74
+ operationClass: operation.operationClass,
75
+ target: freezeTargetDetails(operation.target),
76
+ precheck: freezeSteps(operation.precheck),
77
+ execute: freezeSteps(operation.execute),
78
+ postcheck: freezeSteps(operation.postcheck),
79
+ ...operation.meta ? { meta: cloneRecord(operation.meta) } : {}
80
+ });
81
+ }
82
+ function freezeOperations(operations) {
83
+ if (operations.length === 0) {
84
+ return Object.freeze([]);
85
+ }
86
+ return Object.freeze(operations.map((operation) => freezeOperation(operation)));
87
+ }
88
+ function createMigrationPlan(options) {
89
+ return Object.freeze({
90
+ targetId: options.targetId,
91
+ ...options.origin !== void 0 ? { origin: options.origin ? Object.freeze({ ...options.origin }) : null } : {},
92
+ destination: Object.freeze({ ...options.destination }),
93
+ operations: freezeOperations(options.operations),
94
+ ...options.meta ? { meta: cloneRecord(options.meta) } : {}
95
+ });
96
+ }
97
+ function plannerSuccess(plan) {
98
+ return Object.freeze({
99
+ kind: "success",
100
+ plan
101
+ });
102
+ }
103
+ function plannerFailure(conflicts) {
104
+ return Object.freeze({
105
+ kind: "failure",
106
+ conflicts: Object.freeze(
107
+ conflicts.map(
108
+ (conflict) => Object.freeze({
109
+ kind: conflict.kind,
110
+ summary: conflict.summary,
111
+ ...conflict.why ? { why: conflict.why } : {},
112
+ ...conflict.location ? { location: Object.freeze({ ...conflict.location }) } : {},
113
+ ...conflict.meta ? { meta: cloneRecord(conflict.meta) } : {}
114
+ })
115
+ )
116
+ )
117
+ });
118
+ }
119
+ function runnerSuccess(value) {
120
+ return ok(
121
+ Object.freeze({
122
+ operationsPlanned: value.operationsPlanned,
123
+ operationsExecuted: value.operationsExecuted
124
+ })
125
+ );
126
+ }
127
+ function runnerFailure(code, summary, options) {
128
+ const failure = Object.freeze({
129
+ code,
130
+ summary,
131
+ ...options?.why ? { why: options.why } : {},
132
+ ...options?.meta ? { meta: cloneRecord(options.meta) } : {}
133
+ });
134
+ return notOk(failure);
135
+ }
136
+
137
+ // src/core/migrations/policies.ts
138
+ var INIT_ADDITIVE_POLICY = Object.freeze({
139
+ allowedOperationClasses: Object.freeze(["additive"])
140
+ });
141
+
1371
142
  // src/exports/control.ts
1372
143
  var control_default = new SqlFamilyDescriptor();
1373
144
  export {
1374
- control_default as default
145
+ INIT_ADDITIVE_POLICY,
146
+ createMigrationPlan,
147
+ control_default as default,
148
+ plannerFailure,
149
+ plannerSuccess,
150
+ runnerFailure,
151
+ runnerSuccess
1375
152
  };
1376
153
  //# sourceMappingURL=control.js.map