@prisma-next/sql-runtime 0.3.0-dev.10 → 0.3.0-dev.113

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