@prisma-next/sql-runtime 0.5.0-dev.3 → 0.5.0-dev.31

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 (45) hide show
  1. package/README.md +29 -21
  2. package/dist/exports-CrHMfIKo.mjs +1564 -0
  3. package/dist/exports-CrHMfIKo.mjs.map +1 -0
  4. package/dist/{index-yb51L_1h.d.mts → index-_dXSGeho.d.mts} +78 -25
  5. package/dist/index-_dXSGeho.d.mts.map +1 -0
  6. package/dist/index.d.mts +2 -2
  7. package/dist/index.mjs +2 -2
  8. package/dist/test/utils.d.mts +6 -5
  9. package/dist/test/utils.d.mts.map +1 -1
  10. package/dist/test/utils.mjs +11 -5
  11. package/dist/test/utils.mjs.map +1 -1
  12. package/package.json +11 -13
  13. package/src/codecs/decoding.ts +294 -173
  14. package/src/codecs/encoding.ts +162 -37
  15. package/src/codecs/validation.ts +22 -3
  16. package/src/exports/index.ts +11 -7
  17. package/src/fingerprint.ts +22 -0
  18. package/src/guardrails/raw.ts +165 -0
  19. package/src/lower-sql-plan.ts +3 -3
  20. package/src/marker.ts +75 -0
  21. package/src/middleware/before-compile-chain.ts +1 -0
  22. package/src/middleware/budgets.ts +26 -96
  23. package/src/middleware/lints.ts +3 -3
  24. package/src/middleware/sql-middleware.ts +6 -5
  25. package/src/runtime-spi.ts +44 -0
  26. package/src/sql-context.ts +332 -78
  27. package/src/sql-family-adapter.ts +3 -2
  28. package/src/sql-marker.ts +62 -47
  29. package/src/sql-runtime.ts +332 -113
  30. package/dist/exports-BQZSVXXt.mjs +0 -981
  31. package/dist/exports-BQZSVXXt.mjs.map +0 -1
  32. package/dist/index-yb51L_1h.d.mts.map +0 -1
  33. package/test/async-iterable-result.test.ts +0 -141
  34. package/test/before-compile-chain.test.ts +0 -223
  35. package/test/budgets.test.ts +0 -431
  36. package/test/context.types.test-d.ts +0 -68
  37. package/test/execution-stack.test.ts +0 -161
  38. package/test/json-schema-validation.test.ts +0 -571
  39. package/test/lints.test.ts +0 -160
  40. package/test/mutation-default-generators.test.ts +0 -254
  41. package/test/parameterized-types.test.ts +0 -529
  42. package/test/sql-context.test.ts +0 -384
  43. package/test/sql-family-adapter.test.ts +0 -103
  44. package/test/sql-runtime.test.ts +0 -792
  45. package/test/utils.ts +0 -297
@@ -1,981 +0,0 @@
1
- import { checkMiddlewareCompatibility, runtimeError } from "@prisma-next/framework-components/runtime";
2
- import { createCodecRegistry, isQueryAst } from "@prisma-next/sql-relational-core/ast";
3
- import { AsyncIterableResult, createRuntimeCore, evaluateRawGuardrails, runtimeError as runtimeError$1 } from "@prisma-next/runtime-executor";
4
- import { ifDefined } from "@prisma-next/utils/defined";
5
- import { checkContractComponentRequirements } from "@prisma-next/framework-components/components";
6
- import { createExecutionStack } from "@prisma-next/framework-components/execution";
7
- import { createSqlOperationRegistry } from "@prisma-next/sql-operations";
8
- import { type } from "arktype";
9
-
10
- //#region src/codecs/validation.ts
11
- function extractCodecIds(contract) {
12
- const codecIds = /* @__PURE__ */ new Set();
13
- for (const table of Object.values(contract.storage.tables)) for (const column of Object.values(table.columns)) {
14
- const codecId = column.codecId;
15
- codecIds.add(codecId);
16
- }
17
- return codecIds;
18
- }
19
- function extractCodecIdsFromColumns(contract) {
20
- const codecIds = /* @__PURE__ */ new Map();
21
- for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
22
- const codecId = column.codecId;
23
- const key = `${tableName}.${columnName}`;
24
- codecIds.set(key, codecId);
25
- }
26
- return codecIds;
27
- }
28
- function validateContractCodecMappings(registry, contract) {
29
- const codecIds = extractCodecIdsFromColumns(contract);
30
- const invalidCodecs = [];
31
- for (const [key, codecId] of codecIds.entries()) if (!registry.has(codecId)) {
32
- const parts = key.split(".");
33
- const table = parts[0] ?? "";
34
- const column = parts[1] ?? "";
35
- invalidCodecs.push({
36
- table,
37
- column,
38
- codecId
39
- });
40
- }
41
- if (invalidCodecs.length > 0) {
42
- const details = {
43
- contractTarget: contract.target,
44
- invalidCodecs
45
- };
46
- throw runtimeError("RUNTIME.CODEC_MISSING", `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(", ")}`, details);
47
- }
48
- }
49
- function validateCodecRegistryCompleteness(registry, contract) {
50
- validateContractCodecMappings(registry, contract);
51
- }
52
-
53
- //#endregion
54
- //#region src/lower-sql-plan.ts
55
- /**
56
- * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.
57
- *
58
- * @param adapter - Adapter to lower AST to SQL
59
- * @param contract - Contract for lowering context
60
- * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)
61
- * @returns Fully executable Plan with SQL string
62
- */
63
- function lowerSqlPlan(adapter, contract, queryPlan) {
64
- const lowered = adapter.lower(queryPlan.ast, {
65
- contract,
66
- params: queryPlan.params
67
- });
68
- return Object.freeze({
69
- sql: lowered.sql,
70
- params: lowered.params ?? queryPlan.params,
71
- ast: queryPlan.ast,
72
- meta: queryPlan.meta
73
- });
74
- }
75
-
76
- //#endregion
77
- //#region src/middleware/budgets.ts
78
- function hasAggregateWithoutGroupBy(ast) {
79
- if (ast.groupBy !== void 0) return false;
80
- return ast.projection.some((item) => item.expr.kind === "aggregate");
81
- }
82
- function estimateRowsFromAst(ast, tableRows, defaultTableRows, refs, hasAggregateWithoutGroup) {
83
- if (hasAggregateWithoutGroup) return 1;
84
- const table = refs?.tables?.[0];
85
- if (!table) return null;
86
- const tableEstimate = tableRows[table] ?? defaultTableRows;
87
- if (ast.limit !== void 0) return Math.min(ast.limit, tableEstimate);
88
- return tableEstimate;
89
- }
90
- function estimateRowsFromHeuristics(plan, tableRows, defaultTableRows) {
91
- const table = plan.meta.refs?.tables?.[0];
92
- if (!table) return null;
93
- const tableEstimate = tableRows[table] ?? defaultTableRows;
94
- const limit = plan.meta.annotations?.["limit"];
95
- if (typeof limit === "number") return Math.min(limit, tableEstimate);
96
- return tableEstimate;
97
- }
98
- function hasDetectableLimitFromHeuristics(plan) {
99
- return typeof plan.meta.annotations?.["limit"] === "number";
100
- }
101
- function emitBudgetViolation(error, shouldBlock, ctx) {
102
- if (shouldBlock) throw error;
103
- ctx.log.warn({
104
- code: error.code,
105
- message: error.message,
106
- details: error.details
107
- });
108
- }
109
- function budgets(options) {
110
- const maxRows = options?.maxRows ?? 1e4;
111
- const defaultTableRows = options?.defaultTableRows ?? 1e4;
112
- const tableRows = options?.tableRows ?? {};
113
- const maxLatencyMs = options?.maxLatencyMs ?? 1e3;
114
- const rowSeverity = options?.severities?.rowCount ?? "error";
115
- const observedRowsByPlan = /* @__PURE__ */ new WeakMap();
116
- return Object.freeze({
117
- name: "budgets",
118
- familyId: "sql",
119
- async beforeExecute(plan, ctx) {
120
- observedRowsByPlan.set(plan, { count: 0 });
121
- if (isQueryAst(plan.ast)) {
122
- if (plan.ast.kind === "select") return evaluateSelectAst(plan, plan.ast, ctx);
123
- return;
124
- }
125
- return evaluateWithHeuristics(plan, ctx);
126
- },
127
- async onRow(_row, plan, _ctx) {
128
- const state = observedRowsByPlan.get(plan);
129
- if (!state) return;
130
- state.count += 1;
131
- if (state.count > maxRows) throw runtimeError("BUDGET.ROWS_EXCEEDED", "Observed row count exceeds budget", {
132
- source: "observed",
133
- observedRows: state.count,
134
- maxRows
135
- });
136
- },
137
- async afterExecute(_plan, result, ctx) {
138
- const latencyMs = result.latencyMs;
139
- if (latencyMs > maxLatencyMs) {
140
- const shouldBlock = ctx.mode === "strict";
141
- emitBudgetViolation(runtimeError("BUDGET.TIME_EXCEEDED", "Query latency exceeds budget", {
142
- latencyMs,
143
- maxLatencyMs
144
- }), shouldBlock, ctx);
145
- }
146
- }
147
- });
148
- function evaluateSelectAst(plan, ast, ctx) {
149
- const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);
150
- const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, plan.meta.refs, hasAggNoGroup);
151
- const isUnbounded = ast.limit === void 0 && !hasAggNoGroup;
152
- const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
153
- if (isUnbounded) {
154
- if (estimated !== null && estimated >= maxRows) {
155
- emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
156
- source: "ast",
157
- estimatedRows: estimated,
158
- maxRows
159
- }), shouldBlock, ctx);
160
- return;
161
- }
162
- emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
163
- source: "ast",
164
- maxRows
165
- }), shouldBlock, ctx);
166
- return;
167
- }
168
- if (estimated !== null && estimated > maxRows) emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Estimated row count exceeds budget", {
169
- source: "ast",
170
- estimatedRows: estimated,
171
- maxRows
172
- }), shouldBlock, ctx);
173
- }
174
- async function evaluateWithHeuristics(plan, ctx) {
175
- const estimated = estimateRowsFromHeuristics(plan, tableRows, defaultTableRows);
176
- const isUnbounded = !hasDetectableLimitFromHeuristics(plan);
177
- const isSelect = plan.sql.trimStart().toUpperCase().startsWith("SELECT");
178
- const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
179
- if (isSelect && isUnbounded) {
180
- if (estimated !== null && estimated >= maxRows) {
181
- emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
182
- source: "heuristic",
183
- estimatedRows: estimated,
184
- maxRows
185
- }), shouldBlock, ctx);
186
- return;
187
- }
188
- emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
189
- source: "heuristic",
190
- maxRows
191
- }), shouldBlock, ctx);
192
- return;
193
- }
194
- if (estimated !== null) {
195
- if (estimated > maxRows) emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Estimated row count exceeds budget", {
196
- source: "heuristic",
197
- estimatedRows: estimated,
198
- maxRows
199
- }), shouldBlock, ctx);
200
- return;
201
- }
202
- }
203
- }
204
-
205
- //#endregion
206
- //#region src/middleware/lints.ts
207
- function getFromSourceTableDetail(source) {
208
- switch (source.kind) {
209
- case "table-source": return source.name;
210
- case "derived-table-source": return source.alias;
211
- default: throw new Error(`Unsupported source kind: ${source.kind}`);
212
- }
213
- }
214
- function evaluateAstLints(ast) {
215
- const findings = [];
216
- switch (ast.kind) {
217
- case "delete":
218
- if (ast.where === void 0) findings.push({
219
- code: "LINT.DELETE_WITHOUT_WHERE",
220
- severity: "error",
221
- message: "DELETE without WHERE clause blocks execution to prevent accidental full-table deletion",
222
- details: { table: ast.table.name }
223
- });
224
- break;
225
- case "update":
226
- if (ast.where === void 0) findings.push({
227
- code: "LINT.UPDATE_WITHOUT_WHERE",
228
- severity: "error",
229
- message: "UPDATE without WHERE clause blocks execution to prevent accidental full-table update",
230
- details: { table: ast.table.name }
231
- });
232
- break;
233
- case "select":
234
- if (ast.limit === void 0) {
235
- const table = getFromSourceTableDetail(ast.from);
236
- findings.push({
237
- code: "LINT.NO_LIMIT",
238
- severity: "warn",
239
- message: "Unbounded SELECT may return large result sets",
240
- ...ifDefined("details", table !== void 0 ? { table } : void 0)
241
- });
242
- }
243
- if (ast.selectAllIntent !== void 0) {
244
- const table = ast.selectAllIntent.table;
245
- findings.push({
246
- code: "LINT.SELECT_STAR",
247
- severity: "warn",
248
- message: "Query selects all columns via selectAll intent",
249
- ...ifDefined("details", table !== void 0 ? { table } : void 0)
250
- });
251
- }
252
- break;
253
- case "insert": break;
254
- default: throw new Error(`Unsupported AST kind: ${ast.kind}`);
255
- }
256
- return findings;
257
- }
258
- function getConfiguredSeverity(code, options) {
259
- const severities = options?.severities;
260
- if (!severities) return void 0;
261
- switch (code) {
262
- case "LINT.SELECT_STAR": return severities.selectStar;
263
- case "LINT.NO_LIMIT": return severities.noLimit;
264
- case "LINT.DELETE_WITHOUT_WHERE": return severities.deleteWithoutWhere;
265
- case "LINT.UPDATE_WITHOUT_WHERE": return severities.updateWithoutWhere;
266
- case "LINT.READ_ONLY_MUTATION": return severities.readOnlyMutation;
267
- case "LINT.UNINDEXED_PREDICATE": return severities.unindexedPredicate;
268
- default: return;
269
- }
270
- }
271
- /**
272
- * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects
273
- * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic
274
- * guardrails or skips linting depending on `fallbackWhenAstMissing`.
275
- *
276
- * Rules (AST-based):
277
- * - DELETE without WHERE: blocks execution (configurable severity, default error)
278
- * - UPDATE without WHERE: blocks execution (configurable severity, default error)
279
- * - Unbounded SELECT: warn/error (severity from noLimit)
280
- * - SELECT * intent: warn/error (severity from selectStar)
281
- *
282
- * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic
283
- * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.
284
- */
285
- function lints(options) {
286
- const fallback = options?.fallbackWhenAstMissing ?? "raw";
287
- return Object.freeze({
288
- name: "lints",
289
- familyId: "sql",
290
- async beforeExecute(plan, ctx) {
291
- if (isQueryAst(plan.ast)) {
292
- const findings = evaluateAstLints(plan.ast);
293
- for (const lint of findings) {
294
- const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
295
- if (effectiveSeverity === "error") throw runtimeError(lint.code, lint.message, lint.details);
296
- if (effectiveSeverity === "warn") ctx.log.warn({
297
- code: lint.code,
298
- message: lint.message,
299
- details: lint.details
300
- });
301
- }
302
- return;
303
- }
304
- if (fallback === "skip") return;
305
- const evaluation = evaluateRawGuardrails(plan);
306
- for (const lint of evaluation.lints) {
307
- const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
308
- if (effectiveSeverity === "error") throw runtimeError(lint.code, lint.message, lint.details);
309
- if (effectiveSeverity === "warn") ctx.log.warn({
310
- code: lint.code,
311
- message: lint.message,
312
- details: lint.details
313
- });
314
- }
315
- }
316
- });
317
- }
318
-
319
- //#endregion
320
- //#region src/sql-context.ts
321
- function createSqlExecutionStack(options) {
322
- return createExecutionStack({
323
- target: options.target,
324
- adapter: options.adapter,
325
- driver: options.driver,
326
- extensionPacks: options.extensionPacks
327
- });
328
- }
329
- function assertExecutionStackContractRequirements(contract, stack) {
330
- const providedComponentIds = new Set([
331
- stack.target.id,
332
- stack.adapter.id,
333
- ...stack.extensionPacks.map((pack) => pack.id)
334
- ]);
335
- const result = checkContractComponentRequirements({
336
- contract,
337
- expectedTargetFamily: "sql",
338
- expectedTargetId: stack.target.targetId,
339
- providedComponentIds
340
- });
341
- if (result.familyMismatch) throw runtimeError("RUNTIME.CONTRACT_FAMILY_MISMATCH", `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`, {
342
- actual: result.familyMismatch.actual,
343
- expected: result.familyMismatch.expected
344
- });
345
- if (result.targetMismatch) throw runtimeError("RUNTIME.CONTRACT_TARGET_MISMATCH", `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`, {
346
- actual: result.targetMismatch.actual,
347
- expected: result.targetMismatch.expected
348
- });
349
- if (result.missingExtensionPackIds.length > 0) {
350
- const packIds = result.missingExtensionPackIds;
351
- throw runtimeError("RUNTIME.MISSING_EXTENSION_PACK", `Contract requires extension pack(s) ${packIds.map((id) => `'${id}'`).join(", ")}, but runtime descriptors do not provide matching component(s).`, { packIds });
352
- }
353
- }
354
- function validateTypeParams(typeParams, codecDescriptor, context) {
355
- const result = codecDescriptor.paramsSchema(typeParams);
356
- if (result instanceof type.errors) {
357
- const messages = result.map((p) => p.message).join("; ");
358
- throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for ${context.typeName ? `type '${context.typeName}'` : `column '${context.tableName}.${context.columnName}'`} (codecId: ${codecDescriptor.codecId}): ${messages}`, {
359
- ...context,
360
- codecId: codecDescriptor.codecId,
361
- typeParams
362
- });
363
- }
364
- return result;
365
- }
366
- function collectParameterizedCodecDescriptors(contributors) {
367
- const descriptors = /* @__PURE__ */ new Map();
368
- for (const contributor of contributors) for (const descriptor of contributor.parameterizedCodecs()) {
369
- if (descriptors.has(descriptor.codecId)) throw runtimeError("RUNTIME.DUPLICATE_PARAMETERIZED_CODEC", `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`, { codecId: descriptor.codecId });
370
- descriptors.set(descriptor.codecId, descriptor);
371
- }
372
- return descriptors;
373
- }
374
- function initializeTypeHelpers(storageTypes, codecDescriptors) {
375
- const helpers = {};
376
- if (!storageTypes) return helpers;
377
- for (const [typeName, typeInstance] of Object.entries(storageTypes)) {
378
- const descriptor = codecDescriptors.get(typeInstance.codecId);
379
- if (descriptor) {
380
- const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, { typeName });
381
- if (descriptor.init) helpers[typeName] = descriptor.init(validatedParams);
382
- else helpers[typeName] = typeInstance;
383
- } else helpers[typeName] = typeInstance;
384
- }
385
- return helpers;
386
- }
387
- function validateColumnTypeParams(storage, codecDescriptors) {
388
- for (const [tableName, table] of Object.entries(storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeParams) {
389
- const descriptor = codecDescriptors.get(column.codecId);
390
- if (descriptor) validateTypeParams(column.typeParams, descriptor, {
391
- tableName,
392
- columnName
393
- });
394
- }
395
- }
396
- /**
397
- * Builds a registry of compiled JSON Schema validators by scanning the contract
398
- * for columns whose codec descriptor provides an `init` hook returning `{ validate }`.
399
- *
400
- * Handles both:
401
- * - Inline `typeParams.schema` on columns
402
- * - `typeRef` → `storage.types[ref]` with init hook results already in `types` registry
403
- */
404
- function buildJsonSchemaValidatorRegistry(contract, types, codecDescriptors) {
405
- const validators = /* @__PURE__ */ new Map();
406
- const codecIdsWithInit = /* @__PURE__ */ new Set();
407
- for (const [codecId, descriptor] of codecDescriptors) if (descriptor.init) codecIdsWithInit.add(codecId);
408
- if (codecIdsWithInit.size === 0) return;
409
- for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
410
- if (!codecIdsWithInit.has(column.codecId)) continue;
411
- const key = `${tableName}.${columnName}`;
412
- if (column.typeRef) {
413
- const helper = types[column.typeRef];
414
- if (helper?.validate) validators.set(key, helper.validate);
415
- continue;
416
- }
417
- if (column.typeParams) {
418
- const descriptor = codecDescriptors.get(column.codecId);
419
- if (descriptor?.init) {
420
- const helper = descriptor.init(column.typeParams);
421
- if (helper?.validate) validators.set(key, helper.validate);
422
- }
423
- }
424
- }
425
- if (validators.size === 0) return void 0;
426
- return {
427
- get: (key) => validators.get(key),
428
- size: validators.size
429
- };
430
- }
431
- function collectMutationDefaultGenerators(contributors) {
432
- const generators = /* @__PURE__ */ new Map();
433
- const owners = /* @__PURE__ */ new Map();
434
- for (const contributor of contributors) {
435
- const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];
436
- for (const generator of nextGenerators) {
437
- const existingOwner = owners.get(generator.id);
438
- if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR", `Duplicate mutation default generator '${generator.id}'.`, {
439
- id: generator.id,
440
- existingOwner,
441
- incomingOwner: contributor.id
442
- });
443
- generators.set(generator.id, generator);
444
- owners.set(generator.id, contributor.id);
445
- }
446
- }
447
- return generators;
448
- }
449
- function computeExecutionDefaultValue(spec, generatorRegistry) {
450
- switch (spec.kind) {
451
- case "generator": {
452
- const generator = generatorRegistry.get(spec.id);
453
- if (!generator) throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`, { id: spec.id });
454
- return generator.generate(spec.params);
455
- }
456
- }
457
- }
458
- function applyMutationDefaults(contract, generatorRegistry, options) {
459
- const defaults = contract.execution?.mutations.defaults ?? [];
460
- if (defaults.length === 0) return [];
461
- const applied = [];
462
- const appliedColumns = /* @__PURE__ */ new Set();
463
- for (const mutationDefault of defaults) {
464
- if (mutationDefault.ref.table !== options.table) continue;
465
- const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
466
- if (!defaultSpec) continue;
467
- const columnName = mutationDefault.ref.column;
468
- if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) continue;
469
- applied.push({
470
- column: columnName,
471
- value: computeExecutionDefaultValue(defaultSpec, generatorRegistry)
472
- });
473
- appliedColumns.add(columnName);
474
- }
475
- return applied;
476
- }
477
- function createExecutionContext(options) {
478
- const { contract, stack } = options;
479
- assertExecutionStackContractRequirements(contract, stack);
480
- const codecRegistry = createCodecRegistry();
481
- const contributors = [
482
- stack.target,
483
- stack.adapter,
484
- ...stack.extensionPacks
485
- ];
486
- for (const contributor of contributors) for (const c of contributor.codecs().values()) codecRegistry.register(c);
487
- const queryOperationRegistry = createSqlOperationRegistry();
488
- for (const contributor of contributors) for (const op of contributor.queryOperations?.() ?? []) queryOperationRegistry.register(op);
489
- const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);
490
- const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);
491
- if (parameterizedCodecDescriptors.size > 0) validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);
492
- const types = initializeTypeHelpers(contract.storage.types, parameterizedCodecDescriptors);
493
- const jsonSchemaValidators = buildJsonSchemaValidatorRegistry(contract, types, parameterizedCodecDescriptors);
494
- return {
495
- contract,
496
- codecs: codecRegistry,
497
- queryOperations: queryOperationRegistry,
498
- types,
499
- ...jsonSchemaValidators ? { jsonSchemaValidators } : {},
500
- applyMutationDefaults: (options$1) => applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options$1)
501
- };
502
- }
503
-
504
- //#endregion
505
- //#region src/sql-marker.ts
506
- const ensureSchemaStatement = {
507
- sql: "create schema if not exists prisma_contract",
508
- params: []
509
- };
510
- const ensureTableStatement = {
511
- sql: `create table if not exists prisma_contract.marker (
512
- id smallint primary key default 1,
513
- core_hash text not null,
514
- profile_hash text not null,
515
- contract_json jsonb,
516
- canonical_version int,
517
- updated_at timestamptz not null default now(),
518
- app_tag text,
519
- meta jsonb not null default '{}'
520
- )`,
521
- params: []
522
- };
523
- function readContractMarker() {
524
- return {
525
- sql: `select
526
- core_hash,
527
- profile_hash,
528
- contract_json,
529
- canonical_version,
530
- updated_at,
531
- app_tag,
532
- meta
533
- from prisma_contract.marker
534
- where id = $1`,
535
- params: [1]
536
- };
537
- }
538
- function writeContractMarker(input) {
539
- const baseParams = [
540
- 1,
541
- input.storageHash,
542
- input.profileHash,
543
- input.contractJson ?? null,
544
- input.canonicalVersion ?? null,
545
- input.appTag ?? null,
546
- JSON.stringify(input.meta ?? {})
547
- ];
548
- return {
549
- insert: {
550
- sql: `insert into prisma_contract.marker (
551
- id,
552
- core_hash,
553
- profile_hash,
554
- contract_json,
555
- canonical_version,
556
- updated_at,
557
- app_tag,
558
- meta
559
- ) values (
560
- $1,
561
- $2,
562
- $3,
563
- $4::jsonb,
564
- $5,
565
- now(),
566
- $6,
567
- $7::jsonb
568
- )`,
569
- params: baseParams
570
- },
571
- update: {
572
- sql: `update prisma_contract.marker set
573
- core_hash = $2,
574
- profile_hash = $3,
575
- contract_json = $4::jsonb,
576
- canonical_version = $5,
577
- updated_at = now(),
578
- app_tag = $6,
579
- meta = $7::jsonb
580
- where id = $1`,
581
- params: baseParams
582
- }
583
- };
584
- }
585
-
586
- //#endregion
587
- //#region src/codecs/json-schema-validation.ts
588
- /**
589
- * Validates a JSON value against its column's JSON Schema, if a validator exists.
590
- *
591
- * Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.
592
- * No-ops if no validator is registered for the column.
593
- */
594
- function validateJsonValue(registry, table, column, value, direction, codecId) {
595
- const key = `${table}.${column}`;
596
- const validate = registry.get(key);
597
- if (!validate) return;
598
- const result = validate(value);
599
- if (result.valid) return;
600
- throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);
601
- }
602
- function createJsonSchemaValidationError(table, column, direction, errors, codecId) {
603
- return runtimeError("RUNTIME.JSON_SCHEMA_VALIDATION_FAILED", `JSON schema validation failed for column '${table}.${column}' (${direction}): ${formatErrorSummary(errors)}`, {
604
- table,
605
- column,
606
- codecId,
607
- direction,
608
- errors: [...errors]
609
- });
610
- }
611
- function formatErrorSummary(errors) {
612
- if (errors.length === 0) return "unknown validation error";
613
- if (errors.length === 1) {
614
- const err = errors[0];
615
- return err.path === "/" ? err.message : `${err.path}: ${err.message}`;
616
- }
617
- return errors.map((err) => err.path === "/" ? err.message : `${err.path}: ${err.message}`).join("; ");
618
- }
619
-
620
- //#endregion
621
- //#region src/codecs/decoding.ts
622
- function resolveRowCodec(alias, plan, registry) {
623
- const planCodecId = plan.meta.annotations?.codecs?.[alias];
624
- if (planCodecId) {
625
- const codec$1 = registry.get(planCodecId);
626
- if (codec$1) return codec$1;
627
- }
628
- if (plan.meta.projectionTypes) {
629
- const typeId = plan.meta.projectionTypes[alias];
630
- if (typeId) {
631
- const codec$1 = registry.get(typeId);
632
- if (codec$1) return codec$1;
633
- }
634
- }
635
- return null;
636
- }
637
- /**
638
- * Builds a lookup index from column name → { table, column } ref.
639
- * Called once per decodeRow invocation to avoid O(aliases × refs) linear scans.
640
- */
641
- function buildColumnRefIndex(plan) {
642
- const columns = plan.meta.refs?.columns;
643
- if (!columns) return null;
644
- const index = /* @__PURE__ */ new Map();
645
- for (const ref of columns) index.set(ref.column, ref);
646
- return index;
647
- }
648
- function parseProjectionRef(value) {
649
- if (value.startsWith("include:") || value.startsWith("operation:")) return null;
650
- const separatorIndex = value.indexOf(".");
651
- if (separatorIndex <= 0 || separatorIndex === value.length - 1) return null;
652
- return {
653
- table: value.slice(0, separatorIndex),
654
- column: value.slice(separatorIndex + 1)
655
- };
656
- }
657
- function resolveColumnRefForAlias(alias, projection, fallbackColumnRefIndex) {
658
- if (projection && !Array.isArray(projection)) {
659
- const mappedRef = projection[alias];
660
- if (typeof mappedRef !== "string") return;
661
- return parseProjectionRef(mappedRef) ?? void 0;
662
- }
663
- return fallbackColumnRefIndex?.get(alias);
664
- }
665
- function decodeRow(row, plan, registry, jsonValidators) {
666
- const decoded = {};
667
- const projection = plan.meta.projection;
668
- const fallbackColumnRefIndex = jsonValidators && (!projection || Array.isArray(projection)) ? buildColumnRefIndex(plan) : null;
669
- let aliases;
670
- if (projection && !Array.isArray(projection)) aliases = Object.keys(projection);
671
- else if (projection && Array.isArray(projection)) aliases = projection;
672
- else aliases = Object.keys(row);
673
- for (const alias of aliases) {
674
- const wireValue = row[alias];
675
- const projectionValue = projection && typeof projection === "object" && !Array.isArray(projection) ? projection[alias] : void 0;
676
- if (typeof projectionValue === "string" && projectionValue.startsWith("include:")) {
677
- if (wireValue === null || wireValue === void 0) {
678
- decoded[alias] = [];
679
- continue;
680
- }
681
- try {
682
- let parsed;
683
- if (typeof wireValue === "string") parsed = JSON.parse(wireValue);
684
- else if (Array.isArray(wireValue)) parsed = wireValue;
685
- else parsed = JSON.parse(String(wireValue));
686
- if (!Array.isArray(parsed)) throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);
687
- decoded[alias] = parsed;
688
- } catch (error) {
689
- const decodeError = /* @__PURE__ */ new Error(`Failed to parse JSON array for include alias '${alias}': ${error instanceof Error ? error.message : String(error)}`);
690
- decodeError.code = "RUNTIME.DECODE_FAILED";
691
- decodeError.category = "RUNTIME";
692
- decodeError.severity = "error";
693
- decodeError.details = {
694
- alias,
695
- wirePreview: typeof wireValue === "string" && wireValue.length > 100 ? `${wireValue.substring(0, 100)}...` : String(wireValue).substring(0, 100)
696
- };
697
- throw decodeError;
698
- }
699
- continue;
700
- }
701
- if (wireValue === null || wireValue === void 0) {
702
- decoded[alias] = wireValue;
703
- continue;
704
- }
705
- const codec$1 = resolveRowCodec(alias, plan, registry);
706
- if (!codec$1) {
707
- decoded[alias] = wireValue;
708
- continue;
709
- }
710
- try {
711
- const decodedValue = codec$1.decode(wireValue);
712
- if (jsonValidators) {
713
- const ref = resolveColumnRefForAlias(alias, projection, fallbackColumnRefIndex);
714
- if (ref) validateJsonValue(jsonValidators, ref.table, ref.column, decodedValue, "decode", codec$1.id);
715
- }
716
- decoded[alias] = decodedValue;
717
- } catch (error) {
718
- if (error instanceof Error && "code" in error && error.code === "RUNTIME.JSON_SCHEMA_VALIDATION_FAILED") throw error;
719
- const decodeError = /* @__PURE__ */ new Error(`Failed to decode row alias '${alias}' with codec '${codec$1.id}': ${error instanceof Error ? error.message : String(error)}`);
720
- decodeError.code = "RUNTIME.DECODE_FAILED";
721
- decodeError.category = "RUNTIME";
722
- decodeError.severity = "error";
723
- decodeError.details = {
724
- alias,
725
- codec: codec$1.id,
726
- wirePreview: typeof wireValue === "string" && wireValue.length > 100 ? `${wireValue.substring(0, 100)}...` : String(wireValue).substring(0, 100)
727
- };
728
- throw decodeError;
729
- }
730
- }
731
- return decoded;
732
- }
733
-
734
- //#endregion
735
- //#region src/codecs/encoding.ts
736
- function resolveParamCodec(paramDescriptor, registry) {
737
- if (paramDescriptor.codecId) {
738
- const codec$1 = registry.get(paramDescriptor.codecId);
739
- if (codec$1) return codec$1;
740
- }
741
- return null;
742
- }
743
- function encodeParam(value, paramDescriptor, paramIndex, registry) {
744
- if (value === null || value === void 0) return null;
745
- const codec$1 = resolveParamCodec(paramDescriptor, registry);
746
- if (!codec$1) return value;
747
- if (codec$1.encode) try {
748
- return codec$1.encode(value);
749
- } catch (error) {
750
- const label = paramDescriptor.name ?? `param[${paramIndex}]`;
751
- throw new Error(`Failed to encode parameter ${label}: ${error instanceof Error ? error.message : String(error)}`);
752
- }
753
- return value;
754
- }
755
- function encodeParams(plan, registry) {
756
- if (plan.params.length === 0) return plan.params;
757
- const encoded = [];
758
- for (let i = 0; i < plan.params.length; i++) {
759
- const paramValue = plan.params[i];
760
- const paramDescriptor = plan.meta.paramDescriptors[i];
761
- if (paramDescriptor) encoded.push(encodeParam(paramValue, paramDescriptor, i, registry));
762
- else encoded.push(paramValue);
763
- }
764
- return Object.freeze(encoded);
765
- }
766
-
767
- //#endregion
768
- //#region src/middleware/before-compile-chain.ts
769
- async function runBeforeCompileChain(middleware, initial, ctx) {
770
- let current = initial;
771
- for (const mw of middleware) {
772
- if (!mw.beforeCompile) continue;
773
- const result = await mw.beforeCompile(current, ctx);
774
- if (result === void 0) continue;
775
- if (result.ast === current.ast) continue;
776
- ctx.log.debug?.({
777
- event: "middleware.rewrite",
778
- middleware: mw.name,
779
- lane: current.meta.lane
780
- });
781
- current = result;
782
- }
783
- return current;
784
- }
785
-
786
- //#endregion
787
- //#region src/sql-family-adapter.ts
788
- var SqlFamilyAdapter = class {
789
- contract;
790
- markerReader;
791
- constructor(contract, adapterProfile) {
792
- this.contract = contract;
793
- this.markerReader = adapterProfile;
794
- }
795
- validatePlan(plan, contract) {
796
- if (plan.meta.target !== contract.target) throw runtimeError("PLAN.TARGET_MISMATCH", "Plan target does not match runtime target", {
797
- planTarget: plan.meta.target,
798
- runtimeTarget: contract.target
799
- });
800
- if (plan.meta.storageHash !== contract.storage.storageHash) throw runtimeError("PLAN.HASH_MISMATCH", "Plan storage hash does not match runtime contract", {
801
- planStorageHash: plan.meta.storageHash,
802
- runtimeStorageHash: contract.storage.storageHash
803
- });
804
- }
805
- };
806
-
807
- //#endregion
808
- //#region src/sql-runtime.ts
809
- var SqlRuntimeImpl = class {
810
- core;
811
- contract;
812
- adapter;
813
- codecRegistry;
814
- jsonSchemaValidators;
815
- codecRegistryValidated;
816
- constructor(options) {
817
- const { context, adapter, driver, verify, middleware, mode, log } = options;
818
- this.contract = context.contract;
819
- this.adapter = adapter;
820
- this.codecRegistry = context.codecs;
821
- this.jsonSchemaValidators = context.jsonSchemaValidators;
822
- this.codecRegistryValidated = false;
823
- if (middleware) for (const mw of middleware) checkMiddlewareCompatibility(mw, "sql", context.contract.target);
824
- this.core = createRuntimeCore({
825
- familyAdapter: new SqlFamilyAdapter(context.contract, adapter.profile),
826
- driver,
827
- verify,
828
- ...ifDefined("middleware", middleware),
829
- ...ifDefined("mode", mode),
830
- ...ifDefined("log", log)
831
- });
832
- if (verify.mode === "startup") {
833
- validateCodecRegistryCompleteness(this.codecRegistry, context.contract);
834
- this.codecRegistryValidated = true;
835
- }
836
- }
837
- ensureCodecRegistryValidated(contract) {
838
- if (!this.codecRegistryValidated) {
839
- validateCodecRegistryCompleteness(this.codecRegistry, contract);
840
- this.codecRegistryValidated = true;
841
- }
842
- }
843
- async toExecutionPlan(plan) {
844
- const isSqlQueryPlan = (p) => {
845
- return "ast" in p && !("sql" in p);
846
- };
847
- if (!isSqlQueryPlan(plan)) return plan;
848
- const rewrittenDraft = await runBeforeCompileChain(this.core.middleware, {
849
- ast: plan.ast,
850
- meta: plan.meta
851
- }, this.core.middlewareContext);
852
- const planToLower = rewrittenDraft.ast === plan.ast ? plan : {
853
- ...plan,
854
- ast: rewrittenDraft.ast
855
- };
856
- return lowerSqlPlan(this.adapter, this.contract, planToLower);
857
- }
858
- executeAgainstQueryable(plan, queryable) {
859
- this.ensureCodecRegistryValidated(this.contract);
860
- const iterator = async function* (self) {
861
- const executablePlan = await self.toExecutionPlan(plan);
862
- const encodedParams = encodeParams(executablePlan, self.codecRegistry);
863
- const planWithEncodedParams = {
864
- ...executablePlan,
865
- params: encodedParams
866
- };
867
- const coreIterator = queryable.execute(planWithEncodedParams);
868
- for await (const rawRow of coreIterator) yield decodeRow(rawRow, executablePlan, self.codecRegistry, self.jsonSchemaValidators);
869
- };
870
- return new AsyncIterableResult(iterator(this));
871
- }
872
- execute(plan) {
873
- return this.executeAgainstQueryable(plan, this.core);
874
- }
875
- async connection() {
876
- const coreConn = await this.core.connection();
877
- const self = this;
878
- return {
879
- async transaction() {
880
- const coreTx = await coreConn.transaction();
881
- return {
882
- commit: coreTx.commit.bind(coreTx),
883
- rollback: coreTx.rollback.bind(coreTx),
884
- execute(plan) {
885
- return self.executeAgainstQueryable(plan, coreTx);
886
- }
887
- };
888
- },
889
- release: coreConn.release.bind(coreConn),
890
- destroy: coreConn.destroy.bind(coreConn),
891
- execute(plan) {
892
- return self.executeAgainstQueryable(plan, coreConn);
893
- }
894
- };
895
- }
896
- telemetry() {
897
- return this.core.telemetry();
898
- }
899
- close() {
900
- return this.core.close();
901
- }
902
- };
903
- function transactionClosedError() {
904
- return runtimeError$1("RUNTIME.TRANSACTION_CLOSED", "Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.", {});
905
- }
906
- async function withTransaction(runtime, fn) {
907
- const connection = await runtime.connection();
908
- const transaction = await connection.transaction();
909
- let invalidated = false;
910
- const txContext = {
911
- get invalidated() {
912
- return invalidated;
913
- },
914
- execute(plan) {
915
- if (invalidated) throw transactionClosedError();
916
- const inner = transaction.execute(plan);
917
- const guarded = async function* () {
918
- for await (const row of inner) {
919
- if (invalidated) throw transactionClosedError();
920
- yield row;
921
- }
922
- };
923
- return new AsyncIterableResult(guarded());
924
- }
925
- };
926
- let connectionDisposed = false;
927
- const destroyConnection = async (reason) => {
928
- if (connectionDisposed) return;
929
- connectionDisposed = true;
930
- await connection.destroy(reason).catch(() => void 0);
931
- };
932
- try {
933
- let result;
934
- try {
935
- result = await fn(txContext);
936
- } catch (error) {
937
- try {
938
- await transaction.rollback();
939
- } catch (rollbackError) {
940
- await destroyConnection(rollbackError);
941
- const wrapped = runtimeError$1("RUNTIME.TRANSACTION_ROLLBACK_FAILED", "Transaction rollback failed after callback error", { rollbackError });
942
- wrapped.cause = error;
943
- throw wrapped;
944
- }
945
- throw error;
946
- } finally {
947
- invalidated = true;
948
- }
949
- try {
950
- await transaction.commit();
951
- } catch (commitError) {
952
- try {
953
- await transaction.rollback();
954
- } catch {
955
- await destroyConnection(commitError);
956
- }
957
- const wrapped = runtimeError$1("RUNTIME.TRANSACTION_COMMIT_FAILED", "Transaction commit failed", { commitError });
958
- wrapped.cause = commitError;
959
- throw wrapped;
960
- }
961
- return result;
962
- } finally {
963
- if (!connectionDisposed) await connection.release();
964
- }
965
- }
966
- function createRuntime(options) {
967
- const { stackInstance, context, driver, verify, middleware, mode, log } = options;
968
- return new SqlRuntimeImpl({
969
- context,
970
- adapter: stackInstance.adapter,
971
- driver,
972
- verify,
973
- ...ifDefined("middleware", middleware),
974
- ...ifDefined("mode", mode),
975
- ...ifDefined("log", log)
976
- });
977
- }
978
-
979
- //#endregion
980
- export { readContractMarker as a, createSqlExecutionStack as c, lowerSqlPlan as d, extractCodecIds as f, ensureTableStatement as i, lints as l, validateContractCodecMappings as m, withTransaction as n, writeContractMarker as o, validateCodecRegistryCompleteness as p, ensureSchemaStatement as r, createExecutionContext as s, createRuntime as t, budgets as u };
981
- //# sourceMappingURL=exports-BQZSVXXt.mjs.map