@prisma-next/sql-runtime 0.3.0-dev.6 → 0.3.0-dev.64
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 +137 -26
- package/dist/exports-BhZqJPVb.mjs +771 -0
- package/dist/exports-BhZqJPVb.mjs.map +1 -0
- package/dist/index-D59jqEKF.d.mts +159 -0
- package/dist/index-D59jqEKF.d.mts.map +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +3 -0
- package/dist/test/utils.d.mts +82 -0
- package/dist/test/utils.d.mts.map +1 -0
- package/dist/test/utils.mjs +212 -0
- package/dist/test/utils.mjs.map +1 -0
- package/package.json +32 -25
- package/src/codecs/decoding.ts +84 -3
- package/src/codecs/encoding.ts +15 -2
- package/src/codecs/json-schema-validation.ts +61 -0
- package/src/exports/index.ts +14 -6
- package/src/lower-sql-plan.ts +8 -8
- package/src/plugins/lints.ts +204 -0
- package/src/sql-context.ts +385 -98
- package/src/sql-family-adapter.ts +9 -5
- package/src/sql-marker.ts +2 -2
- package/src/sql-runtime.ts +131 -31
- package/test/async-iterable-result.test.ts +42 -34
- package/test/context.types.test-d.ts +68 -0
- package/test/execution-stack.test.ts +166 -0
- package/test/json-schema-validation.test.ts +653 -0
- package/test/lints.test.ts +330 -0
- package/test/parameterized-types.test.ts +539 -0
- package/test/sql-context.test.ts +292 -117
- package/test/sql-family-adapter.test.ts +7 -6
- package/test/sql-runtime.test.ts +218 -30
- package/test/utils.ts +80 -51
- 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-C6I3V3DM.js +0 -455
- package/dist/chunk-C6I3V3DM.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 -65
- 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 -59
- package/dist/test/utils.d.ts.map +0 -1
- package/dist/test/utils.js +0 -24634
- 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,771 @@
|
|
|
1
|
+
import { AsyncIterableResult, budgets, createRuntimeCore, evaluateRawGuardrails, runtimeError } from "@prisma-next/runtime-executor";
|
|
2
|
+
import { ifDefined } from "@prisma-next/utils/defined";
|
|
3
|
+
import { checkContractComponentRequirements } from "@prisma-next/contract/framework-components";
|
|
4
|
+
import { createExecutionStack } from "@prisma-next/core-execution-plane/stack";
|
|
5
|
+
import { generateId } from "@prisma-next/ids/runtime";
|
|
6
|
+
import { createOperationRegistry } from "@prisma-next/operations";
|
|
7
|
+
import { createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
|
|
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/lints.ts
|
|
78
|
+
const QUERY_AST_KINDS = new Set([
|
|
79
|
+
"select",
|
|
80
|
+
"insert",
|
|
81
|
+
"update",
|
|
82
|
+
"delete"
|
|
83
|
+
]);
|
|
84
|
+
function isSqlQueryAst(ast) {
|
|
85
|
+
if (ast === null || typeof ast !== "object" || !("kind" in ast)) return false;
|
|
86
|
+
const kind = ast.kind;
|
|
87
|
+
return typeof kind === "string" && QUERY_AST_KINDS.has(kind);
|
|
88
|
+
}
|
|
89
|
+
function lintError(code, message, details) {
|
|
90
|
+
const error = new Error(message);
|
|
91
|
+
Object.defineProperty(error, "name", {
|
|
92
|
+
value: "RuntimeError",
|
|
93
|
+
configurable: true
|
|
94
|
+
});
|
|
95
|
+
return Object.assign(error, {
|
|
96
|
+
code,
|
|
97
|
+
category: "LINT",
|
|
98
|
+
severity: "error",
|
|
99
|
+
details
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function evaluateAstLints(ast, meta) {
|
|
103
|
+
const findings = [];
|
|
104
|
+
if (ast.kind === "delete") {
|
|
105
|
+
const deleteAst = ast;
|
|
106
|
+
if (deleteAst.where === void 0) findings.push({
|
|
107
|
+
code: "LINT.DELETE_WITHOUT_WHERE",
|
|
108
|
+
severity: "error",
|
|
109
|
+
message: "DELETE without WHERE clause blocks execution to prevent accidental full-table deletion",
|
|
110
|
+
details: { table: deleteAst.table.name }
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
if (ast.kind === "update") {
|
|
114
|
+
const updateAst = ast;
|
|
115
|
+
if (updateAst.where === void 0) findings.push({
|
|
116
|
+
code: "LINT.UPDATE_WITHOUT_WHERE",
|
|
117
|
+
severity: "error",
|
|
118
|
+
message: "UPDATE without WHERE clause blocks execution to prevent accidental full-table update",
|
|
119
|
+
details: { table: updateAst.table.name }
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (ast.kind === "select") {
|
|
123
|
+
const selectAst = ast;
|
|
124
|
+
if (selectAst.limit === void 0) findings.push({
|
|
125
|
+
code: "LINT.NO_LIMIT",
|
|
126
|
+
severity: "warn",
|
|
127
|
+
message: "Unbounded SELECT may return large result sets",
|
|
128
|
+
details: { table: selectAst.from.name }
|
|
129
|
+
});
|
|
130
|
+
if (selectAst.selectAllIntent !== void 0 || meta.annotations?.selectAllIntent !== void 0) {
|
|
131
|
+
const table = selectAst.selectAllIntent?.table ?? meta.annotations?.selectAllIntent?.table;
|
|
132
|
+
findings.push({
|
|
133
|
+
code: "LINT.SELECT_STAR",
|
|
134
|
+
severity: "warn",
|
|
135
|
+
message: "Query selects all columns via selectAll intent",
|
|
136
|
+
...ifDefined("details", table !== void 0 ? { table } : void 0)
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return findings;
|
|
141
|
+
}
|
|
142
|
+
function getConfiguredSeverity(code, options) {
|
|
143
|
+
const severities = options?.severities;
|
|
144
|
+
if (!severities) return void 0;
|
|
145
|
+
switch (code) {
|
|
146
|
+
case "LINT.SELECT_STAR": return severities.selectStar;
|
|
147
|
+
case "LINT.NO_LIMIT": return severities.noLimit;
|
|
148
|
+
case "LINT.DELETE_WITHOUT_WHERE": return severities.deleteWithoutWhere;
|
|
149
|
+
case "LINT.UPDATE_WITHOUT_WHERE": return severities.updateWithoutWhere;
|
|
150
|
+
case "LINT.READ_ONLY_MUTATION": return severities.readOnlyMutation;
|
|
151
|
+
case "LINT.UNINDEXED_PREDICATE": return severities.unindexedPredicate;
|
|
152
|
+
default: return;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* AST-first lint plugin for SQL plans. When `plan.ast` is a SQL QueryAst, inspects
|
|
157
|
+
* the AST structurally. When `plan.ast` is missing, falls back to raw heuristic
|
|
158
|
+
* guardrails or skips linting depending on `fallbackWhenAstMissing`.
|
|
159
|
+
*
|
|
160
|
+
* Rules (AST-based):
|
|
161
|
+
* - DELETE without WHERE: blocks execution (configurable severity, default error)
|
|
162
|
+
* - UPDATE without WHERE: blocks execution (configurable severity, default error)
|
|
163
|
+
* - Unbounded SELECT: warn/error (severity from noLimit)
|
|
164
|
+
* - SELECT * intent: warn/error (severity from selectStar)
|
|
165
|
+
*
|
|
166
|
+
* Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic
|
|
167
|
+
* SQL parsing; `'skip'` skips all lints. Default is `'raw'`.
|
|
168
|
+
*/
|
|
169
|
+
function lints(options) {
|
|
170
|
+
const fallback = options?.fallbackWhenAstMissing ?? "raw";
|
|
171
|
+
return Object.freeze({
|
|
172
|
+
name: "lints",
|
|
173
|
+
async beforeExecute(plan, ctx) {
|
|
174
|
+
if (isSqlQueryAst(plan.ast)) {
|
|
175
|
+
const findings = evaluateAstLints(plan.ast, plan.meta);
|
|
176
|
+
for (const lint of findings) {
|
|
177
|
+
const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
|
|
178
|
+
if (effectiveSeverity === "error") throw lintError(lint.code, lint.message, lint.details);
|
|
179
|
+
if (effectiveSeverity === "warn") ctx.log.warn({
|
|
180
|
+
code: lint.code,
|
|
181
|
+
message: lint.message,
|
|
182
|
+
details: lint.details
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (fallback === "skip") return;
|
|
188
|
+
const evaluation = evaluateRawGuardrails(plan);
|
|
189
|
+
for (const lint of evaluation.lints) {
|
|
190
|
+
const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
|
|
191
|
+
if (effectiveSeverity === "error") throw lintError(lint.code, lint.message, lint.details);
|
|
192
|
+
if (effectiveSeverity === "warn") ctx.log.warn({
|
|
193
|
+
code: lint.code,
|
|
194
|
+
message: lint.message,
|
|
195
|
+
details: lint.details
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/sql-context.ts
|
|
204
|
+
function createSqlExecutionStack(options) {
|
|
205
|
+
return createExecutionStack({
|
|
206
|
+
target: options.target,
|
|
207
|
+
adapter: options.adapter,
|
|
208
|
+
driver: options.driver,
|
|
209
|
+
extensionPacks: options.extensionPacks
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function assertExecutionStackContractRequirements(contract, stack) {
|
|
213
|
+
const providedComponentIds = new Set([
|
|
214
|
+
stack.target.id,
|
|
215
|
+
stack.adapter.id,
|
|
216
|
+
...stack.extensionPacks.map((pack) => pack.id)
|
|
217
|
+
]);
|
|
218
|
+
const result = checkContractComponentRequirements({
|
|
219
|
+
contract,
|
|
220
|
+
expectedTargetFamily: "sql",
|
|
221
|
+
expectedTargetId: stack.target.targetId,
|
|
222
|
+
providedComponentIds
|
|
223
|
+
});
|
|
224
|
+
if (result.familyMismatch) throw runtimeError("RUNTIME.CONTRACT_FAMILY_MISMATCH", `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`, {
|
|
225
|
+
actual: result.familyMismatch.actual,
|
|
226
|
+
expected: result.familyMismatch.expected
|
|
227
|
+
});
|
|
228
|
+
if (result.targetMismatch) throw runtimeError("RUNTIME.CONTRACT_TARGET_MISMATCH", `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`, {
|
|
229
|
+
actual: result.targetMismatch.actual,
|
|
230
|
+
expected: result.targetMismatch.expected
|
|
231
|
+
});
|
|
232
|
+
if (result.missingExtensionPackIds.length > 0) {
|
|
233
|
+
const packIds = result.missingExtensionPackIds;
|
|
234
|
+
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 });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function validateTypeParams(typeParams, codecDescriptor, context) {
|
|
238
|
+
const result = codecDescriptor.paramsSchema(typeParams);
|
|
239
|
+
if (result instanceof type.errors) {
|
|
240
|
+
const messages = result.map((p) => p.message).join("; ");
|
|
241
|
+
throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for ${context.typeName ? `type '${context.typeName}'` : `column '${context.tableName}.${context.columnName}'`} (codecId: ${codecDescriptor.codecId}): ${messages}`, {
|
|
242
|
+
...context,
|
|
243
|
+
codecId: codecDescriptor.codecId,
|
|
244
|
+
typeParams
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
function collectParameterizedCodecDescriptors(contributors) {
|
|
250
|
+
const descriptors = /* @__PURE__ */ new Map();
|
|
251
|
+
for (const contributor of contributors) for (const descriptor of contributor.parameterizedCodecs()) {
|
|
252
|
+
if (descriptors.has(descriptor.codecId)) throw runtimeError("RUNTIME.DUPLICATE_PARAMETERIZED_CODEC", `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`, { codecId: descriptor.codecId });
|
|
253
|
+
descriptors.set(descriptor.codecId, descriptor);
|
|
254
|
+
}
|
|
255
|
+
return descriptors;
|
|
256
|
+
}
|
|
257
|
+
function initializeTypeHelpers(storageTypes, codecDescriptors) {
|
|
258
|
+
const helpers = {};
|
|
259
|
+
if (!storageTypes) return helpers;
|
|
260
|
+
for (const [typeName, typeInstance] of Object.entries(storageTypes)) {
|
|
261
|
+
const descriptor = codecDescriptors.get(typeInstance.codecId);
|
|
262
|
+
if (descriptor) {
|
|
263
|
+
const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, { typeName });
|
|
264
|
+
if (descriptor.init) helpers[typeName] = descriptor.init(validatedParams);
|
|
265
|
+
else helpers[typeName] = typeInstance;
|
|
266
|
+
} else helpers[typeName] = typeInstance;
|
|
267
|
+
}
|
|
268
|
+
return helpers;
|
|
269
|
+
}
|
|
270
|
+
function validateColumnTypeParams(storage, codecDescriptors) {
|
|
271
|
+
for (const [tableName, table] of Object.entries(storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeParams) {
|
|
272
|
+
const descriptor = codecDescriptors.get(column.codecId);
|
|
273
|
+
if (descriptor) validateTypeParams(column.typeParams, descriptor, {
|
|
274
|
+
tableName,
|
|
275
|
+
columnName
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Builds a registry of compiled JSON Schema validators by scanning the contract
|
|
281
|
+
* for columns whose codec descriptor provides an `init` hook returning `{ validate }`.
|
|
282
|
+
*
|
|
283
|
+
* Handles both:
|
|
284
|
+
* - Inline `typeParams.schema` on columns
|
|
285
|
+
* - `typeRef` → `storage.types[ref]` with init hook results already in `types` registry
|
|
286
|
+
*/
|
|
287
|
+
function buildJsonSchemaValidatorRegistry(contract, types, codecDescriptors) {
|
|
288
|
+
const validators = /* @__PURE__ */ new Map();
|
|
289
|
+
const codecIdsWithInit = /* @__PURE__ */ new Set();
|
|
290
|
+
for (const [codecId, descriptor] of codecDescriptors) if (descriptor.init) codecIdsWithInit.add(codecId);
|
|
291
|
+
if (codecIdsWithInit.size === 0) return;
|
|
292
|
+
for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
|
|
293
|
+
if (!codecIdsWithInit.has(column.codecId)) continue;
|
|
294
|
+
const key = `${tableName}.${columnName}`;
|
|
295
|
+
if (column.typeRef) {
|
|
296
|
+
const helper = types[column.typeRef];
|
|
297
|
+
if (helper?.validate) validators.set(key, helper.validate);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (column.typeParams) {
|
|
301
|
+
const descriptor = codecDescriptors.get(column.codecId);
|
|
302
|
+
if (descriptor?.init) {
|
|
303
|
+
const helper = descriptor.init(column.typeParams);
|
|
304
|
+
if (helper?.validate) validators.set(key, helper.validate);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
if (validators.size === 0) return void 0;
|
|
309
|
+
return {
|
|
310
|
+
get: (key) => validators.get(key),
|
|
311
|
+
size: validators.size
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
function computeExecutionDefaultValue(spec) {
|
|
315
|
+
switch (spec.kind) {
|
|
316
|
+
case "generator": return generateId(spec.params ? {
|
|
317
|
+
id: spec.id,
|
|
318
|
+
params: spec.params
|
|
319
|
+
} : { id: spec.id });
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function applyMutationDefaults(contract, options) {
|
|
323
|
+
const defaults = contract.execution?.mutations.defaults ?? [];
|
|
324
|
+
if (defaults.length === 0) return [];
|
|
325
|
+
const applied = [];
|
|
326
|
+
const appliedColumns = /* @__PURE__ */ new Set();
|
|
327
|
+
for (const mutationDefault of defaults) {
|
|
328
|
+
if (mutationDefault.ref.table !== options.table) continue;
|
|
329
|
+
const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
|
|
330
|
+
if (!defaultSpec) continue;
|
|
331
|
+
const columnName = mutationDefault.ref.column;
|
|
332
|
+
if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) continue;
|
|
333
|
+
applied.push({
|
|
334
|
+
column: columnName,
|
|
335
|
+
value: computeExecutionDefaultValue(defaultSpec)
|
|
336
|
+
});
|
|
337
|
+
appliedColumns.add(columnName);
|
|
338
|
+
}
|
|
339
|
+
return applied;
|
|
340
|
+
}
|
|
341
|
+
function createExecutionContext(options) {
|
|
342
|
+
const { contract, stack } = options;
|
|
343
|
+
assertExecutionStackContractRequirements(contract, stack);
|
|
344
|
+
const codecRegistry = createCodecRegistry();
|
|
345
|
+
const operationRegistry = createOperationRegistry();
|
|
346
|
+
const contributors = [
|
|
347
|
+
stack.target,
|
|
348
|
+
stack.adapter,
|
|
349
|
+
...stack.extensionPacks
|
|
350
|
+
];
|
|
351
|
+
for (const contributor of contributors) {
|
|
352
|
+
for (const c of contributor.codecs().values()) codecRegistry.register(c);
|
|
353
|
+
for (const operation of contributor.operationSignatures()) operationRegistry.register(operation);
|
|
354
|
+
}
|
|
355
|
+
const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);
|
|
356
|
+
if (parameterizedCodecDescriptors.size > 0) validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);
|
|
357
|
+
const types = initializeTypeHelpers(contract.storage.types, parameterizedCodecDescriptors);
|
|
358
|
+
const jsonSchemaValidators = buildJsonSchemaValidatorRegistry(contract, types, parameterizedCodecDescriptors);
|
|
359
|
+
return {
|
|
360
|
+
contract,
|
|
361
|
+
operations: operationRegistry,
|
|
362
|
+
codecs: codecRegistry,
|
|
363
|
+
types,
|
|
364
|
+
...jsonSchemaValidators ? { jsonSchemaValidators } : {},
|
|
365
|
+
applyMutationDefaults: (options$1) => applyMutationDefaults(contract, options$1)
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
//#endregion
|
|
370
|
+
//#region src/sql-marker.ts
|
|
371
|
+
const ensureSchemaStatement = {
|
|
372
|
+
sql: "create schema if not exists prisma_contract",
|
|
373
|
+
params: []
|
|
374
|
+
};
|
|
375
|
+
const ensureTableStatement = {
|
|
376
|
+
sql: `create table if not exists prisma_contract.marker (
|
|
377
|
+
id smallint primary key default 1,
|
|
378
|
+
core_hash text not null,
|
|
379
|
+
profile_hash text not null,
|
|
380
|
+
contract_json jsonb,
|
|
381
|
+
canonical_version int,
|
|
382
|
+
updated_at timestamptz not null default now(),
|
|
383
|
+
app_tag text,
|
|
384
|
+
meta jsonb not null default '{}'
|
|
385
|
+
)`,
|
|
386
|
+
params: []
|
|
387
|
+
};
|
|
388
|
+
function readContractMarker() {
|
|
389
|
+
return {
|
|
390
|
+
sql: `select
|
|
391
|
+
core_hash,
|
|
392
|
+
profile_hash,
|
|
393
|
+
contract_json,
|
|
394
|
+
canonical_version,
|
|
395
|
+
updated_at,
|
|
396
|
+
app_tag,
|
|
397
|
+
meta
|
|
398
|
+
from prisma_contract.marker
|
|
399
|
+
where id = $1`,
|
|
400
|
+
params: [1]
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
function writeContractMarker(input) {
|
|
404
|
+
const baseParams = [
|
|
405
|
+
1,
|
|
406
|
+
input.storageHash,
|
|
407
|
+
input.profileHash,
|
|
408
|
+
input.contractJson ?? null,
|
|
409
|
+
input.canonicalVersion ?? null,
|
|
410
|
+
input.appTag ?? null,
|
|
411
|
+
JSON.stringify(input.meta ?? {})
|
|
412
|
+
];
|
|
413
|
+
return {
|
|
414
|
+
insert: {
|
|
415
|
+
sql: `insert into prisma_contract.marker (
|
|
416
|
+
id,
|
|
417
|
+
core_hash,
|
|
418
|
+
profile_hash,
|
|
419
|
+
contract_json,
|
|
420
|
+
canonical_version,
|
|
421
|
+
updated_at,
|
|
422
|
+
app_tag,
|
|
423
|
+
meta
|
|
424
|
+
) values (
|
|
425
|
+
$1,
|
|
426
|
+
$2,
|
|
427
|
+
$3,
|
|
428
|
+
$4::jsonb,
|
|
429
|
+
$5,
|
|
430
|
+
now(),
|
|
431
|
+
$6,
|
|
432
|
+
$7::jsonb
|
|
433
|
+
)`,
|
|
434
|
+
params: baseParams
|
|
435
|
+
},
|
|
436
|
+
update: {
|
|
437
|
+
sql: `update prisma_contract.marker set
|
|
438
|
+
core_hash = $2,
|
|
439
|
+
profile_hash = $3,
|
|
440
|
+
contract_json = $4::jsonb,
|
|
441
|
+
canonical_version = $5,
|
|
442
|
+
updated_at = now(),
|
|
443
|
+
app_tag = $6,
|
|
444
|
+
meta = $7::jsonb
|
|
445
|
+
where id = $1`,
|
|
446
|
+
params: baseParams
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/codecs/json-schema-validation.ts
|
|
453
|
+
/**
|
|
454
|
+
* Validates a JSON value against its column's JSON Schema, if a validator exists.
|
|
455
|
+
*
|
|
456
|
+
* Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.
|
|
457
|
+
* No-ops if no validator is registered for the column.
|
|
458
|
+
*/
|
|
459
|
+
function validateJsonValue(registry, table, column, value, direction, codecId) {
|
|
460
|
+
const key = `${table}.${column}`;
|
|
461
|
+
const validate = registry.get(key);
|
|
462
|
+
if (!validate) return;
|
|
463
|
+
const result = validate(value);
|
|
464
|
+
if (result.valid) return;
|
|
465
|
+
throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);
|
|
466
|
+
}
|
|
467
|
+
function createJsonSchemaValidationError(table, column, direction, errors, codecId) {
|
|
468
|
+
return runtimeError("RUNTIME.JSON_SCHEMA_VALIDATION_FAILED", `JSON schema validation failed for column '${table}.${column}' (${direction}): ${formatErrorSummary(errors)}`, {
|
|
469
|
+
table,
|
|
470
|
+
column,
|
|
471
|
+
codecId,
|
|
472
|
+
direction,
|
|
473
|
+
errors: [...errors]
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
function formatErrorSummary(errors) {
|
|
477
|
+
if (errors.length === 0) return "unknown validation error";
|
|
478
|
+
if (errors.length === 1) {
|
|
479
|
+
const err = errors[0];
|
|
480
|
+
return err.path === "/" ? err.message : `${err.path}: ${err.message}`;
|
|
481
|
+
}
|
|
482
|
+
return errors.map((err) => err.path === "/" ? err.message : `${err.path}: ${err.message}`).join("; ");
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
//#endregion
|
|
486
|
+
//#region src/codecs/decoding.ts
|
|
487
|
+
function resolveRowCodec(alias, plan, registry) {
|
|
488
|
+
const planCodecId = plan.meta.annotations?.codecs?.[alias];
|
|
489
|
+
if (planCodecId) {
|
|
490
|
+
const codec$1 = registry.get(planCodecId);
|
|
491
|
+
if (codec$1) return codec$1;
|
|
492
|
+
}
|
|
493
|
+
if (plan.meta.projectionTypes) {
|
|
494
|
+
const typeId = plan.meta.projectionTypes[alias];
|
|
495
|
+
if (typeId) {
|
|
496
|
+
const codec$1 = registry.get(typeId);
|
|
497
|
+
if (codec$1) return codec$1;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Builds a lookup index from column name → { table, column } ref.
|
|
504
|
+
* Called once per decodeRow invocation to avoid O(aliases × refs) linear scans.
|
|
505
|
+
*/
|
|
506
|
+
function buildColumnRefIndex(plan) {
|
|
507
|
+
const columns = plan.meta.refs?.columns;
|
|
508
|
+
if (!columns) return null;
|
|
509
|
+
const index = /* @__PURE__ */ new Map();
|
|
510
|
+
for (const ref of columns) index.set(ref.column, ref);
|
|
511
|
+
return index;
|
|
512
|
+
}
|
|
513
|
+
function parseProjectionRef(value) {
|
|
514
|
+
if (value.startsWith("include:") || value.startsWith("operation:")) return null;
|
|
515
|
+
const separatorIndex = value.indexOf(".");
|
|
516
|
+
if (separatorIndex <= 0 || separatorIndex === value.length - 1) return null;
|
|
517
|
+
return {
|
|
518
|
+
table: value.slice(0, separatorIndex),
|
|
519
|
+
column: value.slice(separatorIndex + 1)
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
function resolveColumnRefForAlias(alias, projection, fallbackColumnRefIndex) {
|
|
523
|
+
if (projection && !Array.isArray(projection)) {
|
|
524
|
+
const mappedRef = projection[alias];
|
|
525
|
+
if (typeof mappedRef !== "string") return;
|
|
526
|
+
return parseProjectionRef(mappedRef) ?? void 0;
|
|
527
|
+
}
|
|
528
|
+
return fallbackColumnRefIndex?.get(alias);
|
|
529
|
+
}
|
|
530
|
+
function decodeRow(row, plan, registry, jsonValidators) {
|
|
531
|
+
const decoded = {};
|
|
532
|
+
const projection = plan.meta.projection;
|
|
533
|
+
const fallbackColumnRefIndex = jsonValidators && (!projection || Array.isArray(projection)) ? buildColumnRefIndex(plan) : null;
|
|
534
|
+
let aliases;
|
|
535
|
+
if (projection && !Array.isArray(projection)) aliases = Object.keys(projection);
|
|
536
|
+
else if (projection && Array.isArray(projection)) aliases = projection;
|
|
537
|
+
else aliases = Object.keys(row);
|
|
538
|
+
for (const alias of aliases) {
|
|
539
|
+
const wireValue = row[alias];
|
|
540
|
+
const projectionValue = projection && typeof projection === "object" && !Array.isArray(projection) ? projection[alias] : void 0;
|
|
541
|
+
if (typeof projectionValue === "string" && projectionValue.startsWith("include:")) {
|
|
542
|
+
if (wireValue === null || wireValue === void 0) {
|
|
543
|
+
decoded[alias] = [];
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
try {
|
|
547
|
+
let parsed;
|
|
548
|
+
if (typeof wireValue === "string") parsed = JSON.parse(wireValue);
|
|
549
|
+
else if (Array.isArray(wireValue)) parsed = wireValue;
|
|
550
|
+
else parsed = JSON.parse(String(wireValue));
|
|
551
|
+
if (!Array.isArray(parsed)) throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);
|
|
552
|
+
decoded[alias] = parsed;
|
|
553
|
+
} catch (error) {
|
|
554
|
+
const decodeError = /* @__PURE__ */ new Error(`Failed to parse JSON array for include alias '${alias}': ${error instanceof Error ? error.message : String(error)}`);
|
|
555
|
+
decodeError.code = "RUNTIME.DECODE_FAILED";
|
|
556
|
+
decodeError.category = "RUNTIME";
|
|
557
|
+
decodeError.severity = "error";
|
|
558
|
+
decodeError.details = {
|
|
559
|
+
alias,
|
|
560
|
+
wirePreview: typeof wireValue === "string" && wireValue.length > 100 ? `${wireValue.substring(0, 100)}...` : String(wireValue).substring(0, 100)
|
|
561
|
+
};
|
|
562
|
+
throw decodeError;
|
|
563
|
+
}
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (wireValue === null || wireValue === void 0) {
|
|
567
|
+
decoded[alias] = wireValue;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
const codec$1 = resolveRowCodec(alias, plan, registry);
|
|
571
|
+
if (!codec$1) {
|
|
572
|
+
decoded[alias] = wireValue;
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
const decodedValue = codec$1.decode(wireValue);
|
|
577
|
+
if (jsonValidators) {
|
|
578
|
+
const ref = resolveColumnRefForAlias(alias, projection, fallbackColumnRefIndex);
|
|
579
|
+
if (ref) validateJsonValue(jsonValidators, ref.table, ref.column, decodedValue, "decode", codec$1.id);
|
|
580
|
+
}
|
|
581
|
+
decoded[alias] = decodedValue;
|
|
582
|
+
} catch (error) {
|
|
583
|
+
if (error instanceof Error && "code" in error && error.code === "RUNTIME.JSON_SCHEMA_VALIDATION_FAILED") throw error;
|
|
584
|
+
const decodeError = /* @__PURE__ */ new Error(`Failed to decode row alias '${alias}' with codec '${codec$1.id}': ${error instanceof Error ? error.message : String(error)}`);
|
|
585
|
+
decodeError.code = "RUNTIME.DECODE_FAILED";
|
|
586
|
+
decodeError.category = "RUNTIME";
|
|
587
|
+
decodeError.severity = "error";
|
|
588
|
+
decodeError.details = {
|
|
589
|
+
alias,
|
|
590
|
+
codec: codec$1.id,
|
|
591
|
+
wirePreview: typeof wireValue === "string" && wireValue.length > 100 ? `${wireValue.substring(0, 100)}...` : String(wireValue).substring(0, 100)
|
|
592
|
+
};
|
|
593
|
+
throw decodeError;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return decoded;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
//#endregion
|
|
600
|
+
//#region src/codecs/encoding.ts
|
|
601
|
+
function resolveParamCodec(paramDescriptor, plan, registry) {
|
|
602
|
+
const paramName = paramDescriptor.name ?? `param_${paramDescriptor.index ?? 0}`;
|
|
603
|
+
const planCodecId = plan.meta.annotations?.codecs?.[paramName];
|
|
604
|
+
if (planCodecId) {
|
|
605
|
+
const codec$1 = registry.get(planCodecId);
|
|
606
|
+
if (codec$1) return codec$1;
|
|
607
|
+
}
|
|
608
|
+
if (paramDescriptor.codecId) {
|
|
609
|
+
const codec$1 = registry.get(paramDescriptor.codecId);
|
|
610
|
+
if (codec$1) return codec$1;
|
|
611
|
+
}
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
function encodeParam(value, paramDescriptor, plan, registry, jsonValidators) {
|
|
615
|
+
if (value === null || value === void 0) return null;
|
|
616
|
+
if (jsonValidators && paramDescriptor.refs) {
|
|
617
|
+
const { table, column } = paramDescriptor.refs;
|
|
618
|
+
validateJsonValue(jsonValidators, table, column, value, "encode", paramDescriptor.codecId);
|
|
619
|
+
}
|
|
620
|
+
const codec$1 = resolveParamCodec(paramDescriptor, plan, registry);
|
|
621
|
+
if (!codec$1) return value;
|
|
622
|
+
if (codec$1.encode) try {
|
|
623
|
+
return codec$1.encode(value);
|
|
624
|
+
} catch (error) {
|
|
625
|
+
throw new Error(`Failed to encode parameter ${paramDescriptor.name ?? paramDescriptor.index}: ${error instanceof Error ? error.message : String(error)}`);
|
|
626
|
+
}
|
|
627
|
+
return value;
|
|
628
|
+
}
|
|
629
|
+
function encodeParams(plan, registry, jsonValidators) {
|
|
630
|
+
if (plan.params.length === 0) return plan.params;
|
|
631
|
+
const encoded = [];
|
|
632
|
+
for (let i = 0; i < plan.params.length; i++) {
|
|
633
|
+
const paramValue = plan.params[i];
|
|
634
|
+
const paramDescriptor = plan.meta.paramDescriptors[i];
|
|
635
|
+
if (paramDescriptor) encoded.push(encodeParam(paramValue, paramDescriptor, plan, registry, jsonValidators));
|
|
636
|
+
else encoded.push(paramValue);
|
|
637
|
+
}
|
|
638
|
+
return Object.freeze(encoded);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
//#endregion
|
|
642
|
+
//#region src/sql-family-adapter.ts
|
|
643
|
+
var SqlMarkerReader = class {
|
|
644
|
+
readMarkerStatement() {
|
|
645
|
+
return readContractMarker();
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
var SqlFamilyAdapter = class {
|
|
649
|
+
contract;
|
|
650
|
+
markerReader;
|
|
651
|
+
constructor(contract) {
|
|
652
|
+
this.contract = contract;
|
|
653
|
+
this.markerReader = new SqlMarkerReader();
|
|
654
|
+
}
|
|
655
|
+
validatePlan(plan, contract) {
|
|
656
|
+
if (plan.meta.target !== contract.target) throw runtimeError("PLAN.TARGET_MISMATCH", "Plan target does not match runtime target", {
|
|
657
|
+
planTarget: plan.meta.target,
|
|
658
|
+
runtimeTarget: contract.target
|
|
659
|
+
});
|
|
660
|
+
if (plan.meta.storageHash !== contract.storageHash) throw runtimeError("PLAN.HASH_MISMATCH", "Plan storage hash does not match runtime contract", {
|
|
661
|
+
planStorageHash: plan.meta.storageHash,
|
|
662
|
+
runtimeStorageHash: contract.storageHash
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/sql-runtime.ts
|
|
669
|
+
var SqlRuntimeImpl = class {
|
|
670
|
+
core;
|
|
671
|
+
contract;
|
|
672
|
+
adapter;
|
|
673
|
+
codecRegistry;
|
|
674
|
+
jsonSchemaValidators;
|
|
675
|
+
codecRegistryValidated;
|
|
676
|
+
constructor(options) {
|
|
677
|
+
const { context, adapter, driver, verify, plugins, mode, log } = options;
|
|
678
|
+
this.contract = context.contract;
|
|
679
|
+
this.adapter = adapter;
|
|
680
|
+
this.codecRegistry = context.codecs;
|
|
681
|
+
this.jsonSchemaValidators = context.jsonSchemaValidators;
|
|
682
|
+
this.codecRegistryValidated = false;
|
|
683
|
+
this.core = createRuntimeCore({
|
|
684
|
+
familyAdapter: new SqlFamilyAdapter(context.contract),
|
|
685
|
+
driver,
|
|
686
|
+
verify,
|
|
687
|
+
plugins,
|
|
688
|
+
...ifDefined("mode", mode),
|
|
689
|
+
...ifDefined("log", log),
|
|
690
|
+
operationRegistry: context.operations
|
|
691
|
+
});
|
|
692
|
+
if (verify.mode === "startup") {
|
|
693
|
+
validateCodecRegistryCompleteness(this.codecRegistry, context.contract);
|
|
694
|
+
this.codecRegistryValidated = true;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
ensureCodecRegistryValidated(contract) {
|
|
698
|
+
if (!this.codecRegistryValidated) {
|
|
699
|
+
validateCodecRegistryCompleteness(this.codecRegistry, contract);
|
|
700
|
+
this.codecRegistryValidated = true;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
toExecutionPlan(plan) {
|
|
704
|
+
const isSqlQueryPlan = (p) => {
|
|
705
|
+
return "ast" in p && !("sql" in p);
|
|
706
|
+
};
|
|
707
|
+
return isSqlQueryPlan(plan) ? lowerSqlPlan(this.adapter, this.contract, plan) : plan;
|
|
708
|
+
}
|
|
709
|
+
executeAgainstQueryable(plan, queryable) {
|
|
710
|
+
this.ensureCodecRegistryValidated(this.contract);
|
|
711
|
+
const executablePlan = this.toExecutionPlan(plan);
|
|
712
|
+
const iterator = async function* (self) {
|
|
713
|
+
const encodedParams = encodeParams(executablePlan, self.codecRegistry, self.jsonSchemaValidators);
|
|
714
|
+
const planWithEncodedParams = {
|
|
715
|
+
...executablePlan,
|
|
716
|
+
params: encodedParams
|
|
717
|
+
};
|
|
718
|
+
const coreIterator = queryable.execute(planWithEncodedParams);
|
|
719
|
+
for await (const rawRow of coreIterator) yield decodeRow(rawRow, executablePlan, self.codecRegistry, self.jsonSchemaValidators);
|
|
720
|
+
};
|
|
721
|
+
return new AsyncIterableResult(iterator(this));
|
|
722
|
+
}
|
|
723
|
+
execute(plan) {
|
|
724
|
+
return this.executeAgainstQueryable(plan, this.core);
|
|
725
|
+
}
|
|
726
|
+
async connection() {
|
|
727
|
+
const coreConn = await this.core.connection();
|
|
728
|
+
const self = this;
|
|
729
|
+
return {
|
|
730
|
+
async transaction() {
|
|
731
|
+
const coreTx = await coreConn.transaction();
|
|
732
|
+
return {
|
|
733
|
+
commit: coreTx.commit.bind(coreTx),
|
|
734
|
+
rollback: coreTx.rollback.bind(coreTx),
|
|
735
|
+
execute(plan) {
|
|
736
|
+
return self.executeAgainstQueryable(plan, coreTx);
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
},
|
|
740
|
+
release: coreConn.release.bind(coreConn),
|
|
741
|
+
execute(plan) {
|
|
742
|
+
return self.executeAgainstQueryable(plan, coreConn);
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
telemetry() {
|
|
747
|
+
return this.core.telemetry();
|
|
748
|
+
}
|
|
749
|
+
operations() {
|
|
750
|
+
return this.core.operations();
|
|
751
|
+
}
|
|
752
|
+
close() {
|
|
753
|
+
return this.core.close();
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
function createRuntime(options) {
|
|
757
|
+
const { stackInstance, context, driver, verify, plugins, mode, log } = options;
|
|
758
|
+
return new SqlRuntimeImpl({
|
|
759
|
+
context,
|
|
760
|
+
adapter: stackInstance.adapter,
|
|
761
|
+
driver,
|
|
762
|
+
verify,
|
|
763
|
+
...ifDefined("plugins", plugins),
|
|
764
|
+
...ifDefined("mode", mode),
|
|
765
|
+
...ifDefined("log", log)
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
//#endregion
|
|
770
|
+
export { readContractMarker as a, createSqlExecutionStack as c, extractCodecIds as d, validateCodecRegistryCompleteness as f, ensureTableStatement as i, lints as l, createRuntime as n, writeContractMarker as o, validateContractCodecMappings as p, ensureSchemaStatement as r, createExecutionContext as s, budgets as t, lowerSqlPlan as u };
|
|
771
|
+
//# sourceMappingURL=exports-BhZqJPVb.mjs.map
|