@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.
@@ -0,0 +1,609 @@
1
+ import {
2
+ collectSupportedCodecTypeIds,
3
+ readMarker
4
+ } from "./chunk-C3GKWCKA.js";
5
+ import {
6
+ verifySqlSchema
7
+ } from "./chunk-54XYY6SU.js";
8
+
9
+ // src/core/assembly.ts
10
+ import { createOperationRegistry } from "@prisma-next/operations";
11
+
12
+ // src/core/instance.ts
13
+ import { emit } from "@prisma-next/core-control-plane/emission";
14
+ import { sqlTargetFamilyHook } from "@prisma-next/sql-contract-emitter";
15
+ import { validateContract } from "@prisma-next/sql-contract-ts/contract";
16
+ import {
17
+ ensureSchemaStatement,
18
+ ensureTableStatement,
19
+ writeContractMarker
20
+ } from "@prisma-next/sql-runtime";
21
+ import { ifDefined } from "@prisma-next/utils/defined";
22
+ function convertOperationManifest(manifest) {
23
+ return {
24
+ forTypeId: manifest.for,
25
+ method: manifest.method,
26
+ args: manifest.args.map((arg) => {
27
+ if (arg.kind === "typeId") {
28
+ if (!arg.type) {
29
+ throw new Error("typeId arg must have type property");
30
+ }
31
+ return { kind: "typeId", type: arg.type };
32
+ }
33
+ if (arg.kind === "param") {
34
+ return { kind: "param" };
35
+ }
36
+ if (arg.kind === "literal") {
37
+ return { kind: "literal" };
38
+ }
39
+ throw new Error(`Invalid arg kind: ${arg.kind}`);
40
+ }),
41
+ returns: (() => {
42
+ if (manifest.returns.kind === "typeId") {
43
+ return { kind: "typeId", type: manifest.returns.type };
44
+ }
45
+ if (manifest.returns.kind === "builtin") {
46
+ return {
47
+ kind: "builtin",
48
+ type: manifest.returns.type
49
+ };
50
+ }
51
+ throw new Error(`Invalid return kind: ${manifest.returns.kind}`);
52
+ })(),
53
+ lowering: {
54
+ targetFamily: "sql",
55
+ strategy: manifest.lowering.strategy,
56
+ template: manifest.lowering.template
57
+ },
58
+ ...manifest.capabilities ? { capabilities: manifest.capabilities } : {}
59
+ };
60
+ }
61
+ function extractCodecTypeIdsFromContract(contract) {
62
+ const typeIds = /* @__PURE__ */ new Set();
63
+ if (typeof contract === "object" && contract !== null && "storage" in contract && typeof contract.storage === "object" && contract.storage !== null && "tables" in contract.storage) {
64
+ const storage = contract.storage;
65
+ if (storage.tables && typeof storage.tables === "object") {
66
+ for (const table of Object.values(storage.tables)) {
67
+ if (typeof table === "object" && table !== null && "columns" in table && typeof table.columns === "object" && table.columns !== null) {
68
+ const columns = table.columns;
69
+ for (const column of Object.values(columns)) {
70
+ if (column && typeof column === "object" && "codecId" in column && typeof column.codecId === "string") {
71
+ typeIds.add(column.codecId);
72
+ }
73
+ }
74
+ }
75
+ }
76
+ }
77
+ }
78
+ return Array.from(typeIds).sort();
79
+ }
80
+ function createVerifyResult(options) {
81
+ const contract = {
82
+ coreHash: options.contractCoreHash
83
+ };
84
+ if (options.contractProfileHash) {
85
+ contract.profileHash = options.contractProfileHash;
86
+ }
87
+ const target = {
88
+ expected: options.expectedTargetId
89
+ };
90
+ if (options.actualTargetId) {
91
+ target.actual = options.actualTargetId;
92
+ }
93
+ const meta = {
94
+ contractPath: options.contractPath
95
+ };
96
+ if (options.configPath) {
97
+ meta.configPath = options.configPath;
98
+ }
99
+ const result = {
100
+ ok: options.ok,
101
+ summary: options.summary,
102
+ contract,
103
+ target,
104
+ meta,
105
+ timings: {
106
+ total: options.totalTime
107
+ }
108
+ };
109
+ if (options.code) {
110
+ result.code = options.code;
111
+ }
112
+ if (options.marker) {
113
+ result.marker = {
114
+ coreHash: options.marker.coreHash,
115
+ profileHash: options.marker.profileHash
116
+ };
117
+ }
118
+ if (options.missingCodecs) {
119
+ result.missingCodecs = options.missingCodecs;
120
+ }
121
+ if (options.codecCoverageSkipped) {
122
+ result.codecCoverageSkipped = options.codecCoverageSkipped;
123
+ }
124
+ return result;
125
+ }
126
+ function buildSqlTypeMetadataRegistry(options) {
127
+ const { target, adapter, extensions } = options;
128
+ const registry = /* @__PURE__ */ new Map();
129
+ const targetId = adapter.targetId;
130
+ const descriptors = [target, adapter, ...extensions];
131
+ for (const descriptor of descriptors) {
132
+ const manifest = descriptor.manifest;
133
+ const storageTypes = manifest.types?.storage;
134
+ if (!storageTypes) {
135
+ continue;
136
+ }
137
+ for (const storageType of storageTypes) {
138
+ if (storageType.familyId === "sql" && storageType.targetId === targetId) {
139
+ registry.set(storageType.typeId, {
140
+ typeId: storageType.typeId,
141
+ familyId: "sql",
142
+ targetId: storageType.targetId,
143
+ ...storageType.nativeType !== void 0 ? { nativeType: storageType.nativeType } : {}
144
+ });
145
+ }
146
+ }
147
+ }
148
+ return registry;
149
+ }
150
+ function createSqlFamilyInstance(options) {
151
+ const { target, adapter, extensions } = options;
152
+ const descriptors = [target, adapter, ...extensions];
153
+ const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest);
154
+ const codecTypeImports = extractCodecTypeImports(descriptors);
155
+ const operationTypeImports = extractOperationTypeImports(descriptors);
156
+ const extensionIds = extractExtensionIds(adapter, target, extensions);
157
+ const typeMetadataRegistry = buildSqlTypeMetadataRegistry({ target, adapter, extensions });
158
+ function stripMappings(contract) {
159
+ if (typeof contract === "object" && contract !== null && "mappings" in contract) {
160
+ const { mappings: _mappings, ...contractIR } = contract;
161
+ return contractIR;
162
+ }
163
+ return contract;
164
+ }
165
+ return {
166
+ familyId: "sql",
167
+ operationRegistry,
168
+ codecTypeImports,
169
+ operationTypeImports,
170
+ extensionIds,
171
+ typeMetadataRegistry,
172
+ validateContractIR(contractJson) {
173
+ const validated = validateContract(contractJson);
174
+ const { mappings: _mappings, ...contractIR } = validated;
175
+ return contractIR;
176
+ },
177
+ async verify(verifyOptions) {
178
+ const { driver, contractIR, expectedTargetId, contractPath, configPath } = verifyOptions;
179
+ const startTime = Date.now();
180
+ if (typeof contractIR !== "object" || contractIR === null || !("coreHash" in contractIR) || !("target" in contractIR) || typeof contractIR.coreHash !== "string" || typeof contractIR.target !== "string") {
181
+ throw new Error("Contract is missing required fields: coreHash or target");
182
+ }
183
+ const contractCoreHash = contractIR.coreHash;
184
+ const contractProfileHash = "profileHash" in contractIR && typeof contractIR.profileHash === "string" ? contractIR.profileHash : void 0;
185
+ const contractTarget = contractIR.target;
186
+ const marker = await readMarker(driver);
187
+ let missingCodecs;
188
+ let codecCoverageSkipped = false;
189
+ const supportedTypeIds = collectSupportedCodecTypeIds([
190
+ adapter,
191
+ target,
192
+ ...extensions
193
+ ]);
194
+ if (supportedTypeIds.length === 0) {
195
+ codecCoverageSkipped = true;
196
+ } else {
197
+ const supportedSet = new Set(supportedTypeIds);
198
+ const usedTypeIds = extractCodecTypeIdsFromContract(contractIR);
199
+ const missing = usedTypeIds.filter((id) => !supportedSet.has(id));
200
+ if (missing.length > 0) {
201
+ missingCodecs = missing;
202
+ }
203
+ }
204
+ if (!marker) {
205
+ const totalTime2 = Date.now() - startTime;
206
+ return createVerifyResult({
207
+ ok: false,
208
+ code: "PN-RTM-3001",
209
+ summary: "Marker missing",
210
+ contractCoreHash,
211
+ expectedTargetId,
212
+ contractPath,
213
+ totalTime: totalTime2,
214
+ ...contractProfileHash ? { contractProfileHash } : {},
215
+ ...missingCodecs ? { missingCodecs } : {},
216
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
217
+ ...configPath ? { configPath } : {}
218
+ });
219
+ }
220
+ if (contractTarget !== expectedTargetId) {
221
+ const totalTime2 = Date.now() - startTime;
222
+ return createVerifyResult({
223
+ ok: false,
224
+ code: "PN-RTM-3003",
225
+ summary: "Target mismatch",
226
+ contractCoreHash,
227
+ marker,
228
+ expectedTargetId,
229
+ actualTargetId: contractTarget,
230
+ contractPath,
231
+ totalTime: totalTime2,
232
+ ...contractProfileHash ? { contractProfileHash } : {},
233
+ ...missingCodecs ? { missingCodecs } : {},
234
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
235
+ ...configPath ? { configPath } : {}
236
+ });
237
+ }
238
+ if (marker.coreHash !== contractCoreHash) {
239
+ const totalTime2 = Date.now() - startTime;
240
+ return createVerifyResult({
241
+ ok: false,
242
+ code: "PN-RTM-3002",
243
+ summary: "Hash mismatch",
244
+ contractCoreHash,
245
+ marker,
246
+ expectedTargetId,
247
+ contractPath,
248
+ totalTime: totalTime2,
249
+ ...contractProfileHash ? { contractProfileHash } : {},
250
+ ...missingCodecs ? { missingCodecs } : {},
251
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
252
+ ...configPath ? { configPath } : {}
253
+ });
254
+ }
255
+ if (contractProfileHash && marker.profileHash !== contractProfileHash) {
256
+ const totalTime2 = Date.now() - startTime;
257
+ return createVerifyResult({
258
+ ok: false,
259
+ code: "PN-RTM-3002",
260
+ summary: "Hash mismatch",
261
+ contractCoreHash,
262
+ contractProfileHash,
263
+ marker,
264
+ expectedTargetId,
265
+ contractPath,
266
+ totalTime: totalTime2,
267
+ ...missingCodecs ? { missingCodecs } : {},
268
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
269
+ ...configPath ? { configPath } : {}
270
+ });
271
+ }
272
+ const totalTime = Date.now() - startTime;
273
+ return createVerifyResult({
274
+ ok: true,
275
+ summary: "Database matches contract",
276
+ contractCoreHash,
277
+ marker,
278
+ expectedTargetId,
279
+ contractPath,
280
+ totalTime,
281
+ ...contractProfileHash ? { contractProfileHash } : {},
282
+ ...missingCodecs ? { missingCodecs } : {},
283
+ ...codecCoverageSkipped ? { codecCoverageSkipped } : {},
284
+ ...configPath ? { configPath } : {}
285
+ });
286
+ },
287
+ async schemaVerify(options2) {
288
+ const { driver, contractIR, strict, context, frameworkComponents } = options2;
289
+ const contract = validateContract(contractIR);
290
+ const controlAdapter = adapter.create();
291
+ const schemaIR = await controlAdapter.introspect(driver, contractIR);
292
+ return verifySqlSchema({
293
+ contract,
294
+ schema: schemaIR,
295
+ strict,
296
+ ...ifDefined("context", context),
297
+ typeMetadataRegistry,
298
+ frameworkComponents
299
+ });
300
+ },
301
+ async sign(options2) {
302
+ const { driver, contractIR, contractPath, configPath } = options2;
303
+ const startTime = Date.now();
304
+ const contract = validateContract(contractIR);
305
+ const contractCoreHash = contract.coreHash;
306
+ const contractProfileHash = "profileHash" in contract && typeof contract.profileHash === "string" ? contract.profileHash : contractCoreHash;
307
+ const contractTarget = contract.target;
308
+ await driver.query(ensureSchemaStatement.sql, ensureSchemaStatement.params);
309
+ await driver.query(ensureTableStatement.sql, ensureTableStatement.params);
310
+ const existingMarker = await readMarker(driver);
311
+ let markerCreated = false;
312
+ let markerUpdated = false;
313
+ let previousHashes;
314
+ if (!existingMarker) {
315
+ const write = writeContractMarker({
316
+ coreHash: contractCoreHash,
317
+ profileHash: contractProfileHash,
318
+ contractJson: contractIR,
319
+ canonicalVersion: 1
320
+ });
321
+ await driver.query(write.insert.sql, write.insert.params);
322
+ markerCreated = true;
323
+ } else {
324
+ const existingCoreHash = existingMarker.coreHash;
325
+ const existingProfileHash = existingMarker.profileHash;
326
+ const coreHashMatches = existingCoreHash === contractCoreHash;
327
+ const profileHashMatches = existingProfileHash === contractProfileHash;
328
+ if (!coreHashMatches || !profileHashMatches) {
329
+ previousHashes = {
330
+ coreHash: existingCoreHash,
331
+ profileHash: existingProfileHash
332
+ };
333
+ const write = writeContractMarker({
334
+ coreHash: contractCoreHash,
335
+ profileHash: contractProfileHash,
336
+ contractJson: contractIR,
337
+ canonicalVersion: existingMarker.canonicalVersion ?? 1
338
+ });
339
+ await driver.query(write.update.sql, write.update.params);
340
+ markerUpdated = true;
341
+ }
342
+ }
343
+ let summary;
344
+ if (markerCreated) {
345
+ summary = "Database signed (marker created)";
346
+ } else if (markerUpdated) {
347
+ summary = `Database signed (marker updated from ${previousHashes?.coreHash ?? "unknown"})`;
348
+ } else {
349
+ summary = "Database already signed with this contract";
350
+ }
351
+ const totalTime = Date.now() - startTime;
352
+ return {
353
+ ok: true,
354
+ summary,
355
+ contract: {
356
+ coreHash: contractCoreHash,
357
+ profileHash: contractProfileHash
358
+ },
359
+ target: {
360
+ expected: contractTarget,
361
+ actual: contractTarget
362
+ },
363
+ marker: {
364
+ created: markerCreated,
365
+ updated: markerUpdated,
366
+ ...previousHashes ? { previous: previousHashes } : {}
367
+ },
368
+ meta: {
369
+ contractPath,
370
+ ...configPath ? { configPath } : {}
371
+ },
372
+ timings: {
373
+ total: totalTime
374
+ }
375
+ };
376
+ },
377
+ async readMarker(options2) {
378
+ return readMarker(options2.driver);
379
+ },
380
+ async introspect(options2) {
381
+ const { driver, contractIR } = options2;
382
+ const controlAdapter = adapter.create();
383
+ return controlAdapter.introspect(driver, contractIR);
384
+ },
385
+ toSchemaView(schema) {
386
+ const rootLabel = "contract";
387
+ const tableNodes = Object.entries(schema.tables).map(
388
+ ([tableName, table]) => {
389
+ const children = [];
390
+ const columnNodes = [];
391
+ for (const [columnName, column] of Object.entries(table.columns)) {
392
+ const nullableText = column.nullable ? "(nullable)" : "(not nullable)";
393
+ const typeDisplay = column.nativeType;
394
+ const label = `${columnName}: ${typeDisplay} ${nullableText}`;
395
+ columnNodes.push({
396
+ kind: "field",
397
+ id: `column-${tableName}-${columnName}`,
398
+ label,
399
+ meta: {
400
+ nativeType: column.nativeType,
401
+ nullable: column.nullable
402
+ }
403
+ });
404
+ }
405
+ if (columnNodes.length > 0) {
406
+ children.push({
407
+ kind: "collection",
408
+ id: `columns-${tableName}`,
409
+ label: "columns",
410
+ children: columnNodes
411
+ });
412
+ }
413
+ if (table.primaryKey) {
414
+ const pkColumns = table.primaryKey.columns.join(", ");
415
+ children.push({
416
+ kind: "index",
417
+ id: `primary-key-${tableName}`,
418
+ label: `primary key: ${pkColumns}`,
419
+ meta: {
420
+ columns: table.primaryKey.columns,
421
+ ...table.primaryKey.name ? { name: table.primaryKey.name } : {}
422
+ }
423
+ });
424
+ }
425
+ for (const unique of table.uniques) {
426
+ const name = unique.name ?? `${tableName}_${unique.columns.join("_")}_unique`;
427
+ const label = `unique ${name}`;
428
+ children.push({
429
+ kind: "index",
430
+ id: `unique-${tableName}-${name}`,
431
+ label,
432
+ meta: {
433
+ columns: unique.columns,
434
+ unique: true
435
+ }
436
+ });
437
+ }
438
+ for (const index of table.indexes) {
439
+ const name = index.name ?? `${tableName}_${index.columns.join("_")}_idx`;
440
+ const label = index.unique ? `unique index ${name}` : `index ${name}`;
441
+ children.push({
442
+ kind: "index",
443
+ id: `index-${tableName}-${name}`,
444
+ label,
445
+ meta: {
446
+ columns: index.columns,
447
+ unique: index.unique
448
+ }
449
+ });
450
+ }
451
+ const tableMeta = {};
452
+ if (table.primaryKey) {
453
+ tableMeta["primaryKey"] = table.primaryKey.columns;
454
+ if (table.primaryKey.name) {
455
+ tableMeta["primaryKeyName"] = table.primaryKey.name;
456
+ }
457
+ }
458
+ if (table.foreignKeys.length > 0) {
459
+ tableMeta["foreignKeys"] = table.foreignKeys.map((fk) => ({
460
+ columns: fk.columns,
461
+ referencedTable: fk.referencedTable,
462
+ referencedColumns: fk.referencedColumns,
463
+ ...fk.name ? { name: fk.name } : {}
464
+ }));
465
+ }
466
+ const node = {
467
+ kind: "entity",
468
+ id: `table-${tableName}`,
469
+ label: `table ${tableName}`,
470
+ ...Object.keys(tableMeta).length > 0 ? { meta: tableMeta } : {},
471
+ ...children.length > 0 ? { children } : {}
472
+ };
473
+ return node;
474
+ }
475
+ );
476
+ const extensionNodes = schema.extensions.map((extName) => ({
477
+ kind: "extension",
478
+ id: `extension-${extName}`,
479
+ label: `${extName} extension is enabled`
480
+ }));
481
+ const rootChildren = [...tableNodes, ...extensionNodes];
482
+ const rootNode = {
483
+ kind: "root",
484
+ id: "sql-schema",
485
+ label: rootLabel,
486
+ ...rootChildren.length > 0 ? { children: rootChildren } : {}
487
+ };
488
+ return {
489
+ root: rootNode
490
+ };
491
+ },
492
+ async emitContract({ contractIR }) {
493
+ const contractWithoutMappings = stripMappings(contractIR);
494
+ const validatedIR = this.validateContractIR(contractWithoutMappings);
495
+ const result = await emit(
496
+ validatedIR,
497
+ {
498
+ outputDir: "",
499
+ operationRegistry,
500
+ codecTypeImports,
501
+ operationTypeImports,
502
+ extensionIds
503
+ },
504
+ sqlTargetFamilyHook
505
+ );
506
+ return {
507
+ contractJson: result.contractJson,
508
+ contractDts: result.contractDts,
509
+ coreHash: result.coreHash,
510
+ profileHash: result.profileHash
511
+ };
512
+ }
513
+ };
514
+ }
515
+
516
+ // src/core/assembly.ts
517
+ function assembleOperationRegistry(descriptors, convertOperationManifest2) {
518
+ const registry = createOperationRegistry();
519
+ for (const descriptor of descriptors) {
520
+ const operations = descriptor.manifest.operations ?? [];
521
+ for (const operationManifest of operations) {
522
+ const signature = convertOperationManifest2(operationManifest);
523
+ registry.register(signature);
524
+ }
525
+ }
526
+ return registry;
527
+ }
528
+ function extractCodecTypeImports(descriptors) {
529
+ const imports = [];
530
+ for (const descriptor of descriptors) {
531
+ const codecTypes = descriptor.manifest.types?.codecTypes;
532
+ if (codecTypes?.import) {
533
+ imports.push(codecTypes.import);
534
+ }
535
+ }
536
+ return imports;
537
+ }
538
+ function extractOperationTypeImports(descriptors) {
539
+ const imports = [];
540
+ for (const descriptor of descriptors) {
541
+ const operationTypes = descriptor.manifest.types?.operationTypes;
542
+ if (operationTypes?.import) {
543
+ imports.push(operationTypes.import);
544
+ }
545
+ }
546
+ return imports;
547
+ }
548
+ function extractExtensionIds(adapter, target, extensions) {
549
+ const ids = [];
550
+ const seen = /* @__PURE__ */ new Set();
551
+ if (!seen.has(adapter.id)) {
552
+ ids.push(adapter.id);
553
+ seen.add(adapter.id);
554
+ }
555
+ if (!seen.has(target.id)) {
556
+ ids.push(target.id);
557
+ seen.add(target.id);
558
+ }
559
+ for (const ext of extensions) {
560
+ if (!seen.has(ext.id)) {
561
+ ids.push(ext.id);
562
+ seen.add(ext.id);
563
+ }
564
+ }
565
+ return ids;
566
+ }
567
+ function extractCodecTypeImportsFromPacks(packs) {
568
+ const imports = [];
569
+ for (const pack of packs) {
570
+ const codecTypes = pack.manifest.types?.codecTypes;
571
+ if (codecTypes?.import) {
572
+ imports.push(codecTypes.import);
573
+ }
574
+ }
575
+ return imports;
576
+ }
577
+ function extractOperationTypeImportsFromPacks(packs) {
578
+ const imports = [];
579
+ for (const pack of packs) {
580
+ const operationTypes = pack.manifest.types?.operationTypes;
581
+ if (operationTypes?.import) {
582
+ imports.push(operationTypes.import);
583
+ }
584
+ }
585
+ return imports;
586
+ }
587
+ function assembleOperationRegistryFromPacks(packs) {
588
+ const registry = createOperationRegistry();
589
+ for (const pack of packs) {
590
+ const operations = pack.manifest.operations ?? [];
591
+ for (const operationManifest of operations) {
592
+ const signature = convertOperationManifest(operationManifest);
593
+ registry.register(signature);
594
+ }
595
+ }
596
+ return registry;
597
+ }
598
+ function extractExtensionIdsFromPacks(packs) {
599
+ return packs.map((pack) => pack.manifest.id);
600
+ }
601
+
602
+ export {
603
+ extractCodecTypeImportsFromPacks,
604
+ extractOperationTypeImportsFromPacks,
605
+ assembleOperationRegistryFromPacks,
606
+ extractExtensionIdsFromPacks,
607
+ createSqlFamilyInstance
608
+ };
609
+ //# sourceMappingURL=chunk-LECWNGKN.js.map