@prisma-next/sql-runtime 0.3.0-pr.99.6 → 0.4.0-dev.1
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.
- package/LICENSE +201 -0
- package/README.md +141 -24
- package/dist/exports-BO6Fl7yn.mjs +889 -0
- package/dist/exports-BO6Fl7yn.mjs.map +1 -0
- package/dist/index-n6z6trta.d.mts +186 -0
- package/dist/index-n6z6trta.d.mts.map +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +3 -0
- package/dist/test/utils.d.mts +77 -0
- package/dist/test/utils.d.mts.map +1 -0
- package/dist/test/utils.mjs +221 -0
- package/dist/test/utils.mjs.map +1 -0
- package/package.json +26 -20
- package/src/codecs/decoding.ts +84 -3
- package/src/codecs/encoding.ts +5 -15
- package/src/codecs/json-schema-validation.ts +61 -0
- package/src/codecs/validation.ts +7 -6
- package/src/exports/index.ts +20 -9
- package/src/lower-sql-plan.ts +9 -9
- package/src/middleware/budgets.ts +256 -0
- package/src/middleware/lints.ts +192 -0
- package/src/middleware/sql-middleware.ts +26 -0
- package/src/sql-context.ts +357 -257
- package/src/sql-family-adapter.ts +17 -23
- package/src/sql-marker.ts +2 -2
- package/src/sql-runtime.ts +136 -61
- package/test/async-iterable-result.test.ts +42 -37
- package/test/budgets.test.ts +431 -0
- package/test/context.types.test-d.ts +18 -20
- package/test/execution-stack.test.ts +164 -0
- package/test/json-schema-validation.test.ts +571 -0
- package/test/lints.test.ts +159 -0
- package/test/mutation-default-generators.test.ts +254 -0
- package/test/parameterized-types.test.ts +181 -205
- package/test/sql-context.test.ts +301 -134
- package/test/sql-family-adapter.test.ts +37 -20
- package/test/sql-runtime.test.ts +261 -49
- package/test/utils.ts +101 -67
- package/dist/accelerate-EEKAFGN3-P6A6XJWJ.js +0 -137863
- package/dist/accelerate-EEKAFGN3-P6A6XJWJ.js.map +0 -1
- package/dist/amcheck-24VY6X5V.js +0 -13
- package/dist/amcheck-24VY6X5V.js.map +0 -1
- package/dist/bloom-VS74NLHT.js +0 -13
- package/dist/bloom-VS74NLHT.js.map +0 -1
- package/dist/btree_gin-WBC4EAAI.js +0 -13
- package/dist/btree_gin-WBC4EAAI.js.map +0 -1
- package/dist/btree_gist-UNC6QD3M.js +0 -13
- package/dist/btree_gist-UNC6QD3M.js.map +0 -1
- package/dist/chunk-3KTOEDFX.js +0 -49
- package/dist/chunk-3KTOEDFX.js.map +0 -1
- package/dist/chunk-47DZBRQC.js +0 -1280
- package/dist/chunk-47DZBRQC.js.map +0 -1
- package/dist/chunk-52N6AFZM.js +0 -133
- package/dist/chunk-52N6AFZM.js.map +0 -1
- package/dist/chunk-7D4SUZUM.js +0 -38
- package/dist/chunk-7D4SUZUM.js.map +0 -1
- package/dist/chunk-APA6GHYY.js +0 -537
- package/dist/chunk-APA6GHYY.js.map +0 -1
- package/dist/chunk-ECWIHLAT.js +0 -37
- package/dist/chunk-ECWIHLAT.js.map +0 -1
- package/dist/chunk-EI626SDC.js +0 -105
- package/dist/chunk-EI626SDC.js.map +0 -1
- package/dist/chunk-UKKOYUGL.js +0 -578
- package/dist/chunk-UKKOYUGL.js.map +0 -1
- package/dist/chunk-XPLNMXQV.js +0 -1537
- package/dist/chunk-XPLNMXQV.js.map +0 -1
- package/dist/citext-T7MXGUY7.js +0 -13
- package/dist/citext-T7MXGUY7.js.map +0 -1
- package/dist/client-5FENX6AW.js +0 -299
- package/dist/client-5FENX6AW.js.map +0 -1
- package/dist/cube-TFDQBZCI.js +0 -13
- package/dist/cube-TFDQBZCI.js.map +0 -1
- package/dist/dict_int-AEUOPGWP.js +0 -13
- package/dist/dict_int-AEUOPGWP.js.map +0 -1
- package/dist/dict_xsyn-DAAYX3FL.js +0 -13
- package/dist/dict_xsyn-DAAYX3FL.js.map +0 -1
- package/dist/dist-AQ3LWXOX.js +0 -570
- package/dist/dist-AQ3LWXOX.js.map +0 -1
- package/dist/dist-LBVX6BJW.js +0 -189
- package/dist/dist-LBVX6BJW.js.map +0 -1
- package/dist/dist-WLKUVDN2.js +0 -5127
- package/dist/dist-WLKUVDN2.js.map +0 -1
- package/dist/earthdistance-KIGTF4LE.js +0 -13
- package/dist/earthdistance-KIGTF4LE.js.map +0 -1
- package/dist/file_fdw-5N55UP6I.js +0 -13
- package/dist/file_fdw-5N55UP6I.js.map +0 -1
- package/dist/fuzzystrmatch-KN3YWBFP.js +0 -13
- package/dist/fuzzystrmatch-KN3YWBFP.js.map +0 -1
- package/dist/hstore-YX726NKN.js +0 -13
- package/dist/hstore-YX726NKN.js.map +0 -1
- package/dist/http-exception-FZY2H4OF.js +0 -8
- package/dist/http-exception-FZY2H4OF.js.map +0 -1
- package/dist/index.js +0 -30
- package/dist/index.js.map +0 -1
- package/dist/intarray-NKVXNO2D.js +0 -13
- package/dist/intarray-NKVXNO2D.js.map +0 -1
- package/dist/isn-FTEMJGEV.js +0 -13
- package/dist/isn-FTEMJGEV.js.map +0 -1
- package/dist/lo-DB7L4NGI.js +0 -13
- package/dist/lo-DB7L4NGI.js.map +0 -1
- package/dist/logger-WQ7SHNDD.js +0 -68
- package/dist/logger-WQ7SHNDD.js.map +0 -1
- package/dist/ltree-Z32TZT6W.js +0 -13
- package/dist/ltree-Z32TZT6W.js.map +0 -1
- package/dist/nodefs-NM46ACH7.js +0 -31
- package/dist/nodefs-NM46ACH7.js.map +0 -1
- package/dist/opfs-ahp-NJO33LVZ.js +0 -332
- package/dist/opfs-ahp-NJO33LVZ.js.map +0 -1
- package/dist/pageinspect-YP3IZR4X.js +0 -13
- package/dist/pageinspect-YP3IZR4X.js.map +0 -1
- package/dist/pg_buffercache-7TD5J2FB.js +0 -13
- package/dist/pg_buffercache-7TD5J2FB.js.map +0 -1
- package/dist/pg_dump-SG4KYBUB.js +0 -2492
- package/dist/pg_dump-SG4KYBUB.js.map +0 -1
- package/dist/pg_freespacemap-DZDNCPZK.js +0 -13
- package/dist/pg_freespacemap-DZDNCPZK.js.map +0 -1
- package/dist/pg_surgery-J2MUEWEP.js +0 -13
- package/dist/pg_surgery-J2MUEWEP.js.map +0 -1
- package/dist/pg_trgm-7VNQOYS6.js +0 -13
- package/dist/pg_trgm-7VNQOYS6.js.map +0 -1
- package/dist/pg_visibility-TTSIPHFL.js +0 -13
- package/dist/pg_visibility-TTSIPHFL.js.map +0 -1
- package/dist/pg_walinspect-KPFHSHRJ.js +0 -13
- package/dist/pg_walinspect-KPFHSHRJ.js.map +0 -1
- package/dist/proxy-signals-GUDAMDHV.js +0 -39
- package/dist/proxy-signals-GUDAMDHV.js.map +0 -1
- package/dist/seg-IYVDLE4O.js +0 -13
- package/dist/seg-IYVDLE4O.js.map +0 -1
- package/dist/src/codecs/decoding.d.ts +0 -4
- package/dist/src/codecs/decoding.d.ts.map +0 -1
- package/dist/src/codecs/encoding.d.ts +0 -5
- package/dist/src/codecs/encoding.d.ts.map +0 -1
- package/dist/src/codecs/validation.d.ts +0 -6
- package/dist/src/codecs/validation.d.ts.map +0 -1
- package/dist/src/exports/index.d.ts +0 -11
- package/dist/src/exports/index.d.ts.map +0 -1
- package/dist/src/index.d.ts +0 -2
- package/dist/src/index.d.ts.map +0 -1
- package/dist/src/lower-sql-plan.d.ts +0 -15
- package/dist/src/lower-sql-plan.d.ts.map +0 -1
- package/dist/src/sql-context.d.ts +0 -130
- package/dist/src/sql-context.d.ts.map +0 -1
- package/dist/src/sql-family-adapter.d.ts +0 -10
- package/dist/src/sql-family-adapter.d.ts.map +0 -1
- package/dist/src/sql-marker.d.ts +0 -22
- package/dist/src/sql-marker.d.ts.map +0 -1
- package/dist/src/sql-runtime.d.ts +0 -25
- package/dist/src/sql-runtime.d.ts.map +0 -1
- package/dist/tablefunc-EF4RCS7S.js +0 -13
- package/dist/tablefunc-EF4RCS7S.js.map +0 -1
- package/dist/tcn-3VT5BQYW.js +0 -13
- package/dist/tcn-3VT5BQYW.js.map +0 -1
- package/dist/test/utils.d.ts +0 -60
- package/dist/test/utils.d.ts.map +0 -1
- package/dist/test/utils.js +0 -24635
- package/dist/test/utils.js.map +0 -1
- package/dist/tiny-CW6F4GX6.js +0 -10
- package/dist/tiny-CW6F4GX6.js.map +0 -1
- package/dist/tsm_system_rows-ES7KNUQH.js +0 -13
- package/dist/tsm_system_rows-ES7KNUQH.js.map +0 -1
- package/dist/tsm_system_time-76WEIMBG.js +0 -13
- package/dist/tsm_system_time-76WEIMBG.js.map +0 -1
- package/dist/unaccent-7RYF3R64.js +0 -13
- package/dist/unaccent-7RYF3R64.js.map +0 -1
- package/dist/utility-Q5A254LJ-J4HTKZPT.js +0 -347
- package/dist/utility-Q5A254LJ-J4HTKZPT.js.map +0 -1
- package/dist/uuid_ossp-4ETE4FPE.js +0 -13
- package/dist/uuid_ossp-4ETE4FPE.js.map +0 -1
- package/dist/vector-74GPNV7V.js +0 -13
- package/dist/vector-74GPNV7V.js.map +0 -1
- package/src/index.ts +0 -1
|
@@ -0,0 +1,889 @@
|
|
|
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 } 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 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/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/sql-family-adapter.ts
|
|
769
|
+
var SqlFamilyAdapter = class {
|
|
770
|
+
contract;
|
|
771
|
+
markerReader;
|
|
772
|
+
constructor(contract, adapterProfile) {
|
|
773
|
+
this.contract = contract;
|
|
774
|
+
this.markerReader = adapterProfile;
|
|
775
|
+
}
|
|
776
|
+
validatePlan(plan, contract) {
|
|
777
|
+
if (plan.meta.target !== contract.target) throw runtimeError("PLAN.TARGET_MISMATCH", "Plan target does not match runtime target", {
|
|
778
|
+
planTarget: plan.meta.target,
|
|
779
|
+
runtimeTarget: contract.target
|
|
780
|
+
});
|
|
781
|
+
if (plan.meta.storageHash !== contract.storage.storageHash) throw runtimeError("PLAN.HASH_MISMATCH", "Plan storage hash does not match runtime contract", {
|
|
782
|
+
planStorageHash: plan.meta.storageHash,
|
|
783
|
+
runtimeStorageHash: contract.storage.storageHash
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
//#endregion
|
|
789
|
+
//#region src/sql-runtime.ts
|
|
790
|
+
var SqlRuntimeImpl = class {
|
|
791
|
+
core;
|
|
792
|
+
contract;
|
|
793
|
+
adapter;
|
|
794
|
+
codecRegistry;
|
|
795
|
+
jsonSchemaValidators;
|
|
796
|
+
codecRegistryValidated;
|
|
797
|
+
constructor(options) {
|
|
798
|
+
const { context, adapter, driver, verify, middleware, mode, log } = options;
|
|
799
|
+
this.contract = context.contract;
|
|
800
|
+
this.adapter = adapter;
|
|
801
|
+
this.codecRegistry = context.codecs;
|
|
802
|
+
this.jsonSchemaValidators = context.jsonSchemaValidators;
|
|
803
|
+
this.codecRegistryValidated = false;
|
|
804
|
+
if (middleware) for (const mw of middleware) checkMiddlewareCompatibility(mw, "sql", context.contract.target);
|
|
805
|
+
this.core = createRuntimeCore({
|
|
806
|
+
familyAdapter: new SqlFamilyAdapter(context.contract, adapter.profile),
|
|
807
|
+
driver,
|
|
808
|
+
verify,
|
|
809
|
+
...ifDefined("middleware", middleware),
|
|
810
|
+
...ifDefined("mode", mode),
|
|
811
|
+
...ifDefined("log", log)
|
|
812
|
+
});
|
|
813
|
+
if (verify.mode === "startup") {
|
|
814
|
+
validateCodecRegistryCompleteness(this.codecRegistry, context.contract);
|
|
815
|
+
this.codecRegistryValidated = true;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
ensureCodecRegistryValidated(contract) {
|
|
819
|
+
if (!this.codecRegistryValidated) {
|
|
820
|
+
validateCodecRegistryCompleteness(this.codecRegistry, contract);
|
|
821
|
+
this.codecRegistryValidated = true;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
toExecutionPlan(plan) {
|
|
825
|
+
const isSqlQueryPlan = (p) => {
|
|
826
|
+
return "ast" in p && !("sql" in p);
|
|
827
|
+
};
|
|
828
|
+
return isSqlQueryPlan(plan) ? lowerSqlPlan(this.adapter, this.contract, plan) : plan;
|
|
829
|
+
}
|
|
830
|
+
executeAgainstQueryable(plan, queryable) {
|
|
831
|
+
this.ensureCodecRegistryValidated(this.contract);
|
|
832
|
+
const executablePlan = this.toExecutionPlan(plan);
|
|
833
|
+
const iterator = async function* (self) {
|
|
834
|
+
const encodedParams = encodeParams(executablePlan, self.codecRegistry);
|
|
835
|
+
const planWithEncodedParams = {
|
|
836
|
+
...executablePlan,
|
|
837
|
+
params: encodedParams
|
|
838
|
+
};
|
|
839
|
+
const coreIterator = queryable.execute(planWithEncodedParams);
|
|
840
|
+
for await (const rawRow of coreIterator) yield decodeRow(rawRow, executablePlan, self.codecRegistry, self.jsonSchemaValidators);
|
|
841
|
+
};
|
|
842
|
+
return new AsyncIterableResult(iterator(this));
|
|
843
|
+
}
|
|
844
|
+
execute(plan) {
|
|
845
|
+
return this.executeAgainstQueryable(plan, this.core);
|
|
846
|
+
}
|
|
847
|
+
async connection() {
|
|
848
|
+
const coreConn = await this.core.connection();
|
|
849
|
+
const self = this;
|
|
850
|
+
return {
|
|
851
|
+
async transaction() {
|
|
852
|
+
const coreTx = await coreConn.transaction();
|
|
853
|
+
return {
|
|
854
|
+
commit: coreTx.commit.bind(coreTx),
|
|
855
|
+
rollback: coreTx.rollback.bind(coreTx),
|
|
856
|
+
execute(plan) {
|
|
857
|
+
return self.executeAgainstQueryable(plan, coreTx);
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
},
|
|
861
|
+
release: coreConn.release.bind(coreConn),
|
|
862
|
+
execute(plan) {
|
|
863
|
+
return self.executeAgainstQueryable(plan, coreConn);
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
telemetry() {
|
|
868
|
+
return this.core.telemetry();
|
|
869
|
+
}
|
|
870
|
+
close() {
|
|
871
|
+
return this.core.close();
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
function createRuntime(options) {
|
|
875
|
+
const { stackInstance, context, driver, verify, middleware, mode, log } = options;
|
|
876
|
+
return new SqlRuntimeImpl({
|
|
877
|
+
context,
|
|
878
|
+
adapter: stackInstance.adapter,
|
|
879
|
+
driver,
|
|
880
|
+
verify,
|
|
881
|
+
...ifDefined("middleware", middleware),
|
|
882
|
+
...ifDefined("mode", mode),
|
|
883
|
+
...ifDefined("log", log)
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
//#endregion
|
|
888
|
+
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 };
|
|
889
|
+
//# sourceMappingURL=exports-BO6Fl7yn.mjs.map
|