@niscorp/vex 0.2.0 → 0.2.3
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/CHANGELOG.md +161 -0
- package/DESIGN.md +78 -3
- package/DOCS.md +167 -14
- package/README.md +2 -1
- package/dist/adapters/express/index.cjs +241 -19
- package/dist/adapters/express/index.cjs.map +1 -1
- package/dist/adapters/express/index.d.cts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +2 -2
- package/dist/adapters/hono/index.cjs +260 -24
- package/dist/adapters/hono/index.cjs.map +1 -1
- package/dist/adapters/hono/index.d.cts +2 -2
- package/dist/adapters/hono/index.d.ts +2 -2
- package/dist/adapters/hono/index.js +21 -7
- package/dist/adapters/hono/index.js.map +1 -1
- package/dist/agent/index.cjs +2 -0
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/{chunk-HF25Q53I.js → chunk-H4BHW76Q.js} +6 -3
- package/dist/chunk-H4BHW76Q.js.map +1 -0
- package/dist/{chunk-5CBKESBJ.js → chunk-IQM4SQE2.js} +279 -29
- package/dist/chunk-IQM4SQE2.js.map +1 -0
- package/dist/{handler-Cql8SJ3F.d.cts → handler-BGCL6_Si.d.ts} +3 -2
- package/dist/{handler-mICf9ins.d.ts → handler-CMrjTXNx.d.cts} +3 -2
- package/dist/index.cjs +320 -57
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +45 -37
- package/dist/index.js.map +1 -1
- package/dist/{types-BRvMB6IM.d.cts → types-Bi-Lg86b.d.cts} +48 -2
- package/dist/{types-BRvMB6IM.d.ts → types-Bi-Lg86b.d.ts} +48 -2
- package/package.json +9 -8
- package/dist/chunk-5CBKESBJ.js.map +0 -1
- package/dist/chunk-HF25Q53I.js.map +0 -1
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var zod = require('zod');
|
|
4
|
-
var crypto = require('crypto');
|
|
5
4
|
var strata = require('@niscorp/strata');
|
|
6
5
|
|
|
7
6
|
// src/handler.ts
|
|
@@ -184,6 +183,144 @@ var isEntryFresh = (entry, currentFingerprint) => {
|
|
|
184
183
|
const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
|
|
185
184
|
return !expired && !stale;
|
|
186
185
|
};
|
|
186
|
+
|
|
187
|
+
// src/utils/sha256.ts
|
|
188
|
+
var ROUND_CONSTANTS = new Uint32Array([
|
|
189
|
+
1116352408,
|
|
190
|
+
1899447441,
|
|
191
|
+
3049323471,
|
|
192
|
+
3921009573,
|
|
193
|
+
961987163,
|
|
194
|
+
1508970993,
|
|
195
|
+
2453635748,
|
|
196
|
+
2870763221,
|
|
197
|
+
3624381080,
|
|
198
|
+
310598401,
|
|
199
|
+
607225278,
|
|
200
|
+
1426881987,
|
|
201
|
+
1925078388,
|
|
202
|
+
2162078206,
|
|
203
|
+
2614888103,
|
|
204
|
+
3248222580,
|
|
205
|
+
3835390401,
|
|
206
|
+
4022224774,
|
|
207
|
+
264347078,
|
|
208
|
+
604807628,
|
|
209
|
+
770255983,
|
|
210
|
+
1249150122,
|
|
211
|
+
1555081692,
|
|
212
|
+
1996064986,
|
|
213
|
+
2554220882,
|
|
214
|
+
2821834349,
|
|
215
|
+
2952996808,
|
|
216
|
+
3210313671,
|
|
217
|
+
3336571891,
|
|
218
|
+
3584528711,
|
|
219
|
+
113926993,
|
|
220
|
+
338241895,
|
|
221
|
+
666307205,
|
|
222
|
+
773529912,
|
|
223
|
+
1294757372,
|
|
224
|
+
1396182291,
|
|
225
|
+
1695183700,
|
|
226
|
+
1986661051,
|
|
227
|
+
2177026350,
|
|
228
|
+
2456956037,
|
|
229
|
+
2730485921,
|
|
230
|
+
2820302411,
|
|
231
|
+
3259730800,
|
|
232
|
+
3345764771,
|
|
233
|
+
3516065817,
|
|
234
|
+
3600352804,
|
|
235
|
+
4094571909,
|
|
236
|
+
275423344,
|
|
237
|
+
430227734,
|
|
238
|
+
506948616,
|
|
239
|
+
659060556,
|
|
240
|
+
883997877,
|
|
241
|
+
958139571,
|
|
242
|
+
1322822218,
|
|
243
|
+
1537002063,
|
|
244
|
+
1747873779,
|
|
245
|
+
1955562222,
|
|
246
|
+
2024104815,
|
|
247
|
+
2227730452,
|
|
248
|
+
2361852424,
|
|
249
|
+
2428436474,
|
|
250
|
+
2756734187,
|
|
251
|
+
3204031479,
|
|
252
|
+
3329325298
|
|
253
|
+
]);
|
|
254
|
+
var BLOCK_BYTES = 64;
|
|
255
|
+
var rotateRight = (word, bits) => word >>> bits | word << 32 - bits;
|
|
256
|
+
var wordHex = (word) => (word >>> 0).toString(16).padStart(8, "0");
|
|
257
|
+
var sha256Hex = (text) => {
|
|
258
|
+
const bytes = new TextEncoder().encode(text);
|
|
259
|
+
const padded = new Uint8Array(Math.ceil((bytes.length + 9) / BLOCK_BYTES) * BLOCK_BYTES);
|
|
260
|
+
padded.set(bytes);
|
|
261
|
+
padded[bytes.length] = 128;
|
|
262
|
+
const view = new DataView(padded.buffer);
|
|
263
|
+
const bitLength = bytes.length * 8;
|
|
264
|
+
view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296));
|
|
265
|
+
view.setUint32(padded.length - 4, bitLength >>> 0);
|
|
266
|
+
let h0 = 1779033703;
|
|
267
|
+
let h1 = 3144134277;
|
|
268
|
+
let h2 = 1013904242;
|
|
269
|
+
let h3 = 2773480762;
|
|
270
|
+
let h4 = 1359893119;
|
|
271
|
+
let h5 = 2600822924;
|
|
272
|
+
let h6 = 528734635;
|
|
273
|
+
let h7 = 1541459225;
|
|
274
|
+
const schedule = new Uint32Array(64);
|
|
275
|
+
for (let offset = 0; offset < padded.length; offset += BLOCK_BYTES) {
|
|
276
|
+
for (let i = 0; i < 16; i += 1) schedule[i] = view.getUint32(offset + i * 4);
|
|
277
|
+
for (let i = 16; i < 64; i += 1) {
|
|
278
|
+
const w15 = schedule[i - 15] ?? 0;
|
|
279
|
+
const w2 = schedule[i - 2] ?? 0;
|
|
280
|
+
const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ w15 >>> 3;
|
|
281
|
+
const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ w2 >>> 10;
|
|
282
|
+
schedule[i] = (schedule[i - 16] ?? 0) + s0 + (schedule[i - 7] ?? 0) + s1;
|
|
283
|
+
}
|
|
284
|
+
let a = h0;
|
|
285
|
+
let b = h1;
|
|
286
|
+
let c = h2;
|
|
287
|
+
let d = h3;
|
|
288
|
+
let e = h4;
|
|
289
|
+
let f = h5;
|
|
290
|
+
let g = h6;
|
|
291
|
+
let h = h7;
|
|
292
|
+
for (let i = 0; i < 64; i += 1) {
|
|
293
|
+
const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
|
|
294
|
+
const choice = e & f ^ ~e & g;
|
|
295
|
+
const temp1 = h + sum1 + choice + (ROUND_CONSTANTS[i] ?? 0) + (schedule[i] ?? 0) | 0;
|
|
296
|
+
const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
|
|
297
|
+
const majority = a & b ^ a & c ^ b & c;
|
|
298
|
+
const temp2 = sum0 + majority | 0;
|
|
299
|
+
h = g;
|
|
300
|
+
g = f;
|
|
301
|
+
f = e;
|
|
302
|
+
e = d + temp1 | 0;
|
|
303
|
+
d = c;
|
|
304
|
+
c = b;
|
|
305
|
+
b = a;
|
|
306
|
+
a = temp1 + temp2 | 0;
|
|
307
|
+
}
|
|
308
|
+
h0 = h0 + a | 0;
|
|
309
|
+
h1 = h1 + b | 0;
|
|
310
|
+
h2 = h2 + c | 0;
|
|
311
|
+
h3 = h3 + d | 0;
|
|
312
|
+
h4 = h4 + e | 0;
|
|
313
|
+
h5 = h5 + f | 0;
|
|
314
|
+
h6 = h6 + g | 0;
|
|
315
|
+
h7 = h7 + h | 0;
|
|
316
|
+
}
|
|
317
|
+
return wordHex(h0) + wordHex(h1) + wordHex(h2) + wordHex(h3) + wordHex(h4) + wordHex(h5) + wordHex(h6) + wordHex(h7);
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// src/utils/canonical.ts
|
|
321
|
+
var hashText = (text) => sha256Hex(text);
|
|
322
|
+
|
|
323
|
+
// src/cache/hash.ts
|
|
187
324
|
var computeSchemaFingerprint = (schema) => {
|
|
188
325
|
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
189
326
|
const stable = {
|
|
@@ -213,10 +350,11 @@ var computeSchemaFingerprint = (schema) => {
|
|
|
213
350
|
}))
|
|
214
351
|
}))
|
|
215
352
|
};
|
|
216
|
-
return
|
|
353
|
+
return hashText(JSON.stringify(stable));
|
|
217
354
|
};
|
|
218
355
|
|
|
219
356
|
// src/errors.ts
|
|
357
|
+
var VEX_ERROR = /* @__PURE__ */ Symbol.for("@niscorp/vex:VexError");
|
|
220
358
|
var VexError = class extends Error {
|
|
221
359
|
code;
|
|
222
360
|
details;
|
|
@@ -227,6 +365,8 @@ var VexError = class extends Error {
|
|
|
227
365
|
this.details = details;
|
|
228
366
|
}
|
|
229
367
|
};
|
|
368
|
+
Object.defineProperty(VexError.prototype, VEX_ERROR, { value: true });
|
|
369
|
+
var isVexError = (err) => err instanceof VexError || err instanceof Error && Reflect.get(err, VEX_ERROR) === true;
|
|
230
370
|
|
|
231
371
|
// src/engine/optional.ts
|
|
232
372
|
var refuseOptional = (where) => {
|
|
@@ -505,13 +645,21 @@ var LookupSchema = zod.z.object({
|
|
|
505
645
|
where: FilterSchema.describe("Bounds the lookup \u2014 should match at most one row")
|
|
506
646
|
}).strict()
|
|
507
647
|
}).strict().describe("Scalar subquery: reads one value from another table at write time; read scope rules apply");
|
|
648
|
+
var ReturnedSchema = zod.z.object({
|
|
649
|
+
$returned: FieldPathSchema.describe(
|
|
650
|
+
"`table.column`: `table` is written by exactly one earlier statement of this batch; `column` is a column of that table, including one the database generated."
|
|
651
|
+
)
|
|
652
|
+
}).strict().describe(
|
|
653
|
+
"A column of the one row an earlier statement of this batch (an insert, update, upsert or delete) returned \u2014 how a later row gets an id the database generated. That statement must return exactly one row; none (its `where` matched no row, or scope kept the row back) or several fails the whole batch and nothing is written. Allowed only as the value of a column a statement sets; never inside a `where`, a `$lookup` or `items`, and never naming an `insertEach` or an `insert` whose `onConflict` has no `set`."
|
|
654
|
+
);
|
|
508
655
|
var ValueSchema = zod.z.union([
|
|
509
656
|
zod.z.string(),
|
|
510
657
|
zod.z.number(),
|
|
511
658
|
zod.z.boolean(),
|
|
512
659
|
zod.z.null(),
|
|
513
660
|
zod.z.object({ $context: zod.z.string() }).strict(),
|
|
514
|
-
LookupSchema
|
|
661
|
+
LookupSchema,
|
|
662
|
+
ReturnedSchema
|
|
515
663
|
]);
|
|
516
664
|
var Columns = zod.z.record(zod.z.string(), ValueSchema).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
|
|
517
665
|
var OnConflictSchema = zod.z.object({
|
|
@@ -609,17 +757,23 @@ var walkFilter = (filter, schema, sig) => {
|
|
|
609
757
|
};
|
|
610
758
|
var isLookupRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
611
759
|
var columnsOf = (m) => m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : m.op === "upsert" ? { ...m.columns, ...m.insert ?? {} } : {};
|
|
760
|
+
var positionsSetBy = (m) => {
|
|
761
|
+
const positions = (cols, insertOnly = false) => Object.entries(cols ?? {}).map(([column, value]) => ({ column, value, insertOnly }));
|
|
762
|
+
if (m.op === "insert" || m.op === "insertEach") return [...positions(m.values), ...positions(m.onConflict?.set)];
|
|
763
|
+
if (m.op === "update") return positions(m.set);
|
|
764
|
+
if (m.op === "upsert") return [...positions(m.columns), ...positions(m.insert, true)];
|
|
765
|
+
return [];
|
|
766
|
+
};
|
|
612
767
|
var collectMutationContext = (def, schema) => {
|
|
613
768
|
const sig = {};
|
|
614
769
|
const list = Array.isArray(def) ? def : [def];
|
|
615
770
|
for (const m of list) {
|
|
616
|
-
for (const
|
|
771
|
+
for (const { column: col, value: v, insertOnly } of positionsSetBy(m)) {
|
|
617
772
|
if (isLookupRef(v)) {
|
|
618
773
|
walkFilter(v.$lookup.where, schema, sig);
|
|
619
774
|
continue;
|
|
620
775
|
}
|
|
621
776
|
if (!isContextRef(v)) continue;
|
|
622
|
-
const insertOnly = m.op === "upsert" && m.insert !== void 0 && col in m.insert;
|
|
623
777
|
addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...insertOnly ? { note: "insert only" } : {} });
|
|
624
778
|
}
|
|
625
779
|
if (m.op === "update" || m.op === "delete") walkFilter(m.where, schema, sig);
|
|
@@ -657,8 +811,7 @@ var mutationEffect = (def) => {
|
|
|
657
811
|
};
|
|
658
812
|
var requiredContextKeys = (m) => {
|
|
659
813
|
const keys = /* @__PURE__ */ new Set();
|
|
660
|
-
const
|
|
661
|
-
for (const v of Object.values(cols)) {
|
|
814
|
+
for (const { value: v } of positionsSetBy(m)) {
|
|
662
815
|
if (isContextRef(v)) keys.add(v.$context);
|
|
663
816
|
else if (isLookupRef(v)) {
|
|
664
817
|
const sub = {};
|
|
@@ -674,10 +827,41 @@ var requiredContextKeys = (m) => {
|
|
|
674
827
|
}
|
|
675
828
|
return [...keys].sort();
|
|
676
829
|
};
|
|
830
|
+
var isReturnedRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v && typeof v.$returned === "string";
|
|
831
|
+
var returnedIn = (list, at) => {
|
|
832
|
+
const refs = /* @__PURE__ */ new Map();
|
|
833
|
+
const issues = [];
|
|
834
|
+
const m = list[at];
|
|
835
|
+
if (m === void 0) return { refs, issues };
|
|
836
|
+
const judged = /* @__PURE__ */ new Set();
|
|
837
|
+
for (const { value: v } of positionsSetBy(m)) {
|
|
838
|
+
if (!isReturnedRef(v) || judged.has(v.$returned)) continue;
|
|
839
|
+
judged.add(v.$returned);
|
|
840
|
+
const dot = v.$returned.indexOf(".");
|
|
841
|
+
const table = v.$returned.slice(0, dot);
|
|
842
|
+
const column = v.$returned.slice(dot + 1);
|
|
843
|
+
const reads = `${m.op} on "${m.table}" reads "${v.$returned}"`;
|
|
844
|
+
const earlier = list.flatMap((s, i) => i < at && s.table === table ? [{ s, i }] : []);
|
|
845
|
+
const source = earlier[0];
|
|
846
|
+
if (source === void 0) {
|
|
847
|
+
issues.push(`${reads}, and no earlier statement writes "${table}" \u2014 put the statement that writes it before this one, in the same batch`);
|
|
848
|
+
} else if (earlier.length > 1) {
|
|
849
|
+
issues.push(`${reads}, and ${earlier.length} earlier statements write "${table}" \u2014 a reference cannot tell them apart`);
|
|
850
|
+
} else if (source.s.op === "insertEach") {
|
|
851
|
+
issues.push(`${reads} from an insertEach, which writes a row per element \u2014 there is no one row to read`);
|
|
852
|
+
} else if (source.s.op === "insert" && source.s.onConflict !== void 0 && source.s.onConflict.set === void 0) {
|
|
853
|
+
issues.push(`${reads} from an insert that does nothing on conflict, which then returns no row \u2014 give its onConflict a \`set\``);
|
|
854
|
+
} else {
|
|
855
|
+
refs.set(v.$returned, { statement: source.i, table, column });
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return { refs, issues };
|
|
859
|
+
};
|
|
677
860
|
|
|
678
861
|
// src/mutations/engine.ts
|
|
679
862
|
var isLookup = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
680
863
|
var isItemRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$item" in v;
|
|
864
|
+
var isReturned = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v;
|
|
681
865
|
var collectLookups = (m) => {
|
|
682
866
|
const out = [];
|
|
683
867
|
const scan = (cols) => {
|
|
@@ -775,6 +959,13 @@ var assertWritableColumns = (m, schema) => {
|
|
|
775
959
|
if (m.onConflict.where !== void 0) assertFilterColumns(m.onConflict.where, m.table, schema, "onConflict");
|
|
776
960
|
}
|
|
777
961
|
};
|
|
962
|
+
var assertReturnedColumns = (refs, schema) => {
|
|
963
|
+
for (const [ref, source] of refs) {
|
|
964
|
+
if (findEntity(source.table, schema)?.fields.some((f) => f.name === source.column) !== true) {
|
|
965
|
+
throw new VexError("invalid_dsl", `Unknown column "${ref}" in $returned.`);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
};
|
|
778
969
|
var readMatchesFor = (table, policy) => {
|
|
779
970
|
const rule = policy.entities[table];
|
|
780
971
|
if (rule === void 0) {
|
|
@@ -883,7 +1074,8 @@ var newCtx = () => ({
|
|
|
883
1074
|
resolvedPaths: /* @__PURE__ */ new Map(),
|
|
884
1075
|
aliasMap: /* @__PURE__ */ new Map(),
|
|
885
1076
|
paramSlots: [],
|
|
886
|
-
paramCounter: { value: 0 }
|
|
1077
|
+
paramCounter: { value: 0 },
|
|
1078
|
+
returned: /* @__PURE__ */ new Map()
|
|
887
1079
|
});
|
|
888
1080
|
var indexFilterFields = (filter, aliasMap) => {
|
|
889
1081
|
for (const path of filterColumns(filter)) aliasMap.set(path, path);
|
|
@@ -894,13 +1086,19 @@ var compileValue = (v, ctx) => {
|
|
|
894
1086
|
const where = compileFilter(v.$lookup.where, ctx);
|
|
895
1087
|
return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
|
|
896
1088
|
}
|
|
1089
|
+
if (isReturned(v)) {
|
|
1090
|
+
ctx.paramCounter.value += 1;
|
|
1091
|
+
ctx.returned.set(ctx.paramSlots.length, v.$returned);
|
|
1092
|
+
ctx.paramSlots.push({ key: v.$returned, kind: "context", type: "string" });
|
|
1093
|
+
return `$${ctx.paramCounter.value}`;
|
|
1094
|
+
}
|
|
897
1095
|
return compileFieldOrValue(v, ctx);
|
|
898
1096
|
};
|
|
899
1097
|
var compileColumnValue = (table, column, v, ctx, schema) => {
|
|
900
1098
|
const before = ctx.paramSlots.length;
|
|
901
1099
|
const sql = compileValue(v, ctx);
|
|
902
1100
|
const json = findEntity(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === "json";
|
|
903
|
-
if (json && typeof v === "object" && v !== null && "$context" in v) {
|
|
1101
|
+
if (json && typeof v === "object" && v !== null && ("$context" in v || "$returned" in v)) {
|
|
904
1102
|
const slot = ctx.paramSlots[before];
|
|
905
1103
|
if (slot !== void 0) ctx.paramSlots[before] = { ...slot, encode: "json" };
|
|
906
1104
|
}
|
|
@@ -931,7 +1129,7 @@ var compileMutation = (m, schema) => {
|
|
|
931
1129
|
const entries = Object.entries(m.values);
|
|
932
1130
|
const cols = entries.map(([c]) => c);
|
|
933
1131
|
const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
|
|
934
|
-
return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };
|
|
1132
|
+
return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
935
1133
|
}
|
|
936
1134
|
if (m.op === "insertEach") {
|
|
937
1135
|
const entity = findEntity(m.table, schema);
|
|
@@ -945,25 +1143,26 @@ var compileMutation = (m, schema) => {
|
|
|
945
1143
|
const raw = `(item.value->>${quoteLiteral(v.$item)})`;
|
|
946
1144
|
return cast === void 0 ? raw : `${raw}::${cast}`;
|
|
947
1145
|
}
|
|
948
|
-
return compileValue(v, ctx);
|
|
1146
|
+
return isReturned(v) ? compileColumnValue(m.table, col, v, ctx, schema) : compileValue(v, ctx);
|
|
949
1147
|
});
|
|
950
1148
|
ctx.paramCounter.value += 1;
|
|
951
1149
|
ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
|
|
952
1150
|
const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;
|
|
953
1151
|
return {
|
|
954
1152
|
sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
|
|
955
|
-
slots: ctx.paramSlots
|
|
1153
|
+
slots: ctx.paramSlots,
|
|
1154
|
+
returned: ctx.returned
|
|
956
1155
|
};
|
|
957
1156
|
}
|
|
958
1157
|
if (m.op === "update") {
|
|
959
1158
|
const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
|
|
960
1159
|
indexFilterFields(m.where, ctx.aliasMap);
|
|
961
1160
|
const where2 = compileFilter(m.where, ctx);
|
|
962
|
-
return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots };
|
|
1161
|
+
return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
963
1162
|
}
|
|
964
1163
|
indexFilterFields(m.where, ctx.aliasMap);
|
|
965
1164
|
const where = compileFilter(m.where, ctx);
|
|
966
|
-
return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };
|
|
1165
|
+
return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
967
1166
|
};
|
|
968
1167
|
var SUGAR = {
|
|
969
1168
|
upsert: (m, context) => {
|
|
@@ -978,24 +1177,47 @@ var desugarMutation = (m, context) => {
|
|
|
978
1177
|
var executeWrites = async (client, def, mctx) => {
|
|
979
1178
|
const parsed = MutationDefinitionSchema.parse(def);
|
|
980
1179
|
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
981
|
-
const
|
|
982
|
-
|
|
1180
|
+
const cores = entries.map((entry) => desugarMutation(entry, mctx.context));
|
|
1181
|
+
const compiled = cores.map((core, at) => {
|
|
983
1182
|
const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
|
|
984
1183
|
if (missing.length > 0) {
|
|
985
1184
|
throw new VexError("missing_context", `Mutation is missing context: ${missing.join(", ")}.`, {
|
|
986
1185
|
expected: collectMutationContext(parsed, mctx.schema)
|
|
987
1186
|
});
|
|
988
1187
|
}
|
|
1188
|
+
const returned = returnedIn(cores, at);
|
|
1189
|
+
if (returned.issues.length > 0) throw new VexError("invalid_dsl", `${returned.issues.join("; ")}.`);
|
|
989
1190
|
const m = scopeMutation(core, mctx.policy);
|
|
990
1191
|
assertWritableColumns(m, mctx.schema);
|
|
1192
|
+
assertReturnedColumns(returned.refs, mctx.schema);
|
|
991
1193
|
const statement = compileMutation(m, mctx.schema);
|
|
992
1194
|
requireScope({ paramSlots: statement.slots }, mctx.scope);
|
|
993
|
-
|
|
1195
|
+
const reads = [...statement.returned].map(([slot, ref]) => {
|
|
1196
|
+
const source = returned.refs.get(ref);
|
|
1197
|
+
if (source === void 0) throw new VexError("invalid_dsl", `"${ref}" names no earlier statement of the batch.`);
|
|
1198
|
+
return { slot, ref, source };
|
|
1199
|
+
});
|
|
1200
|
+
return { ...statement, reads, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
|
|
994
1201
|
});
|
|
995
1202
|
const runAll = async (q) => {
|
|
996
1203
|
const results = [];
|
|
997
1204
|
for (const c of compiled) {
|
|
998
1205
|
const params = await resolveParams(c.slots, mctx.context, mctx.scope);
|
|
1206
|
+
for (const read of c.reads) {
|
|
1207
|
+
const rows = results[read.source.statement]?.rows ?? [];
|
|
1208
|
+
const row = rows[0];
|
|
1209
|
+
if (rows.length !== 1 || row === void 0) {
|
|
1210
|
+
throw new VexError(
|
|
1211
|
+
"execution_error",
|
|
1212
|
+
`"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
|
|
1213
|
+
{ returned: read.ref, rows: rows.length }
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
if (!(read.source.column in row)) {
|
|
1217
|
+
throw new VexError("execution_error", `"${read.ref}": the row statement ${read.source.statement + 1} returned has no "${read.source.column}" key. Nothing was written.`, { returned: read.ref });
|
|
1218
|
+
}
|
|
1219
|
+
params[read.slot] = row[read.source.column];
|
|
1220
|
+
}
|
|
999
1221
|
const bound = params.map((value, i) => {
|
|
1000
1222
|
if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
|
|
1001
1223
|
if (c.slots[i]?.type !== "json") return value;
|
|
@@ -1293,11 +1515,11 @@ var runQuery = async (config, body, scope, probe, live) => {
|
|
|
1293
1515
|
}
|
|
1294
1516
|
return { status: 200, body: response };
|
|
1295
1517
|
} catch (err) {
|
|
1296
|
-
if (err
|
|
1518
|
+
if (isVexError(err) && err.code === "missing_scope") {
|
|
1297
1519
|
console.error("[vex] refused a statement the host did not scope:", err.message);
|
|
1298
1520
|
return { status: 500, body: { error: "missing_scope", message: "The server did not supply the scope this request needs." } };
|
|
1299
1521
|
}
|
|
1300
|
-
if (err
|
|
1522
|
+
if (isVexError(err)) {
|
|
1301
1523
|
const status = err.code === "fingerprint_protected" ? 409 : err.code === "cache_miss" ? 404 : 400;
|
|
1302
1524
|
return {
|
|
1303
1525
|
status,
|