@palbase/backend 10.3.0 → 12.0.0
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/dist/chunk-7LAXRLPG.js +418 -0
- package/dist/chunk-7LAXRLPG.js.map +1 -0
- package/dist/{chunk-4WOQWFUP.js → chunk-LUV36KQU.js} +26 -11
- package/dist/{chunk-4WOQWFUP.js.map → chunk-LUV36KQU.js.map} +1 -1
- package/dist/{chunk-2PCNZBNZ.js → chunk-XATG7BRC.js} +20 -2
- package/dist/chunk-XATG7BRC.js.map +1 -0
- package/dist/db/index.cjs +438 -10
- package/dist/db/index.cjs.map +1 -1
- package/dist/db/index.d.cts +2 -2
- package/dist/db/index.d.ts +2 -2
- package/dist/db/index.js +13 -1
- package/dist/{endpoint-92kVepng.d.cts → endpoint-Ck4hER_7.d.cts} +343 -11
- package/dist/{endpoint-92kVepng.d.ts → endpoint-Ck4hER_7.d.ts} +343 -11
- package/dist/{index-BaHs33jr.d.cts → index-BJAf1uPC.d.cts} +64 -34
- package/dist/{index-DfryIw9U.d.ts → index-l7DhBDtn.d.ts} +64 -34
- package/dist/index.cjs +589 -124
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +60 -162
- package/dist/index.d.ts +60 -162
- package/dist/index.js +139 -108
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +545 -12
- package/dist/test/index.cjs.map +1 -1
- package/dist/test/index.d.cts +1 -1
- package/dist/test/index.d.ts +1 -1
- package/dist/test/index.js +153 -12
- package/dist/test/index.js.map +1 -1
- package/docs/background.md +8 -9
- package/docs/database.md +106 -16
- package/docs/events.md +20 -17
- package/docs/llms-full.txt +141 -47
- package/docs/schema.md +6 -4
- package/package.json +1 -1
- package/dist/chunk-2PCNZBNZ.js.map +0 -1
package/dist/test/index.cjs
CHANGED
|
@@ -27,6 +27,386 @@ module.exports = __toCommonJS(test_exports);
|
|
|
27
27
|
|
|
28
28
|
// src/runtime.ts
|
|
29
29
|
var import_node_async_hooks = require("async_hooks");
|
|
30
|
+
|
|
31
|
+
// src/db/tx-plan.ts
|
|
32
|
+
var TxRefError = class extends Error {
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "TxRefError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var TxPlanError = class extends Error {
|
|
39
|
+
constructor(message) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "TxPlanError";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var EXPR = /* @__PURE__ */ Symbol.for("palbase.tx.expr");
|
|
45
|
+
var REF = /* @__PURE__ */ Symbol.for("palbase.tx.ref");
|
|
46
|
+
var ROW = /* @__PURE__ */ Symbol.for("palbase.tx.row");
|
|
47
|
+
var ROWS = /* @__PURE__ */ Symbol.for("palbase.tx.rows");
|
|
48
|
+
var TRAPPED_PROPS = [
|
|
49
|
+
"then",
|
|
50
|
+
"valueOf",
|
|
51
|
+
"toString",
|
|
52
|
+
"toJSON",
|
|
53
|
+
Symbol.toPrimitive
|
|
54
|
+
];
|
|
55
|
+
function trap(prop, what, hint) {
|
|
56
|
+
const name = typeof prop === "symbol" ? prop.description ?? String(prop) : prop;
|
|
57
|
+
throw new TxRefError(
|
|
58
|
+
`${what} was used as a value (via \`${name}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${hint}`
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
function makeRef(op, field) {
|
|
62
|
+
const target = { [REF]: { op, field } };
|
|
63
|
+
return new Proxy(target, {
|
|
64
|
+
get(t, prop) {
|
|
65
|
+
if (prop === REF) return t[REF];
|
|
66
|
+
if (TRAPPED_PROPS.includes(prop)) {
|
|
67
|
+
trap(
|
|
68
|
+
prop,
|
|
69
|
+
`\`${field}\` of a row this transaction has not written yet`,
|
|
70
|
+
"Pass it to another operation in the same plan, or return it from the callback and read it after `transaction()` resolves."
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function makeRowHandle(op) {
|
|
78
|
+
const target = { [ROW]: op };
|
|
79
|
+
return new Proxy(target, {
|
|
80
|
+
get(t, prop) {
|
|
81
|
+
if (prop === ROW) return t[ROW];
|
|
82
|
+
if (TRAPPED_PROPS.includes(prop)) {
|
|
83
|
+
trap(
|
|
84
|
+
prop,
|
|
85
|
+
"A row this transaction has not written yet",
|
|
86
|
+
"Read one of its columns to reference it, or return the row from the callback and read it after `transaction()` resolves."
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
if (typeof prop === "symbol") return void 0;
|
|
90
|
+
return makeRef(op, prop);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
function refDescriptor(v) {
|
|
95
|
+
if (typeof v !== "object" || v === null) return null;
|
|
96
|
+
const d = v[REF];
|
|
97
|
+
return isRefDescriptor(d) ? d : null;
|
|
98
|
+
}
|
|
99
|
+
function isRefDescriptor(d) {
|
|
100
|
+
return typeof d === "object" && d !== null && typeof d.op === "number" && typeof d.field === "string";
|
|
101
|
+
}
|
|
102
|
+
function rowOpIndex(v) {
|
|
103
|
+
if (typeof v !== "object" || v === null) return null;
|
|
104
|
+
const op = v[ROW];
|
|
105
|
+
return typeof op === "number" ? op : null;
|
|
106
|
+
}
|
|
107
|
+
function exprOf(v) {
|
|
108
|
+
if (typeof v !== "object" || v === null) return null;
|
|
109
|
+
const e = v[EXPR];
|
|
110
|
+
return typeof e === "object" && e !== null ? e : null;
|
|
111
|
+
}
|
|
112
|
+
function isRowsHandle(v) {
|
|
113
|
+
return typeof v === "object" && v !== null && v[ROWS] !== void 0;
|
|
114
|
+
}
|
|
115
|
+
function encodeValue(value, column, allowColumnExpr) {
|
|
116
|
+
const ref = refDescriptor(value);
|
|
117
|
+
if (ref) return { $ref: { op: ref.op, field: ref.field } };
|
|
118
|
+
const expr = exprOf(value);
|
|
119
|
+
if (expr) {
|
|
120
|
+
if (expr.fn !== "now" && !allowColumnExpr) {
|
|
121
|
+
throw new TxPlanError(
|
|
122
|
+
`\`${column}\`: ${expr.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return { $expr: expr };
|
|
126
|
+
}
|
|
127
|
+
if (rowOpIndex(value) !== null) {
|
|
128
|
+
throw new TxPlanError(
|
|
129
|
+
`\`${column}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (isRowsHandle(value)) {
|
|
133
|
+
throw new TxPlanError(
|
|
134
|
+
`\`${column}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
assertNoNestedHandles(value, column);
|
|
138
|
+
return value;
|
|
139
|
+
}
|
|
140
|
+
function assertNoNestedHandles(value, column) {
|
|
141
|
+
if (typeof value !== "object" || value === null) return;
|
|
142
|
+
if (value instanceof Date) return;
|
|
143
|
+
if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {
|
|
144
|
+
throw new TxPlanError(
|
|
145
|
+
`\`${column}\`: a plan handle is nested inside a value. The server would store it as literal JSON, not resolve it. Put the reference directly in the column.`
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
if (Array.isArray(value)) {
|
|
149
|
+
for (const item of value) assertNoNestedHandles(item, column);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
for (const item of Object.values(value)) {
|
|
153
|
+
assertNoNestedHandles(item, column);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function encodeMap(map, allowColumnExpr) {
|
|
157
|
+
const out = {};
|
|
158
|
+
for (const key of Object.keys(map).sort()) {
|
|
159
|
+
const value = map[key];
|
|
160
|
+
if (value === void 0) continue;
|
|
161
|
+
out[key] = encodeValue(value, key, allowColumnExpr);
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
var SKIPPED_OP = -1;
|
|
166
|
+
var TxRowsImpl = class {
|
|
167
|
+
constructor(builder, opIndex, what) {
|
|
168
|
+
this.builder = builder;
|
|
169
|
+
this.opIndex = opIndex;
|
|
170
|
+
this.what = what;
|
|
171
|
+
}
|
|
172
|
+
builder;
|
|
173
|
+
opIndex;
|
|
174
|
+
what;
|
|
175
|
+
// Present so `isRowsHandle` recognises the object; never read for its value.
|
|
176
|
+
[ROWS] = true;
|
|
177
|
+
guarded = false;
|
|
178
|
+
// The type-level `await` guard made real: TS rejects `await rows` at compile
|
|
179
|
+
// time, and reaching this means someone called `.then(...)` by hand.
|
|
180
|
+
then() {
|
|
181
|
+
throw new TxRefError(
|
|
182
|
+
`${this.what} cannot be awaited: a transaction callback builds a plan, it does not run statements. Remove the \`await\`.`
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
expectOne(error) {
|
|
186
|
+
this.declareGuard("one", 1, error);
|
|
187
|
+
if (this.opIndex === SKIPPED_OP) throw error;
|
|
188
|
+
return makeRowHandle(this.opIndex);
|
|
189
|
+
}
|
|
190
|
+
expectNone(error) {
|
|
191
|
+
this.declareGuard("none", 0, error);
|
|
192
|
+
}
|
|
193
|
+
expectAtLeast(n, error) {
|
|
194
|
+
assertGuardCount(n, "expectAtLeast");
|
|
195
|
+
this.declareGuard("atLeast", n, error);
|
|
196
|
+
if (this.opIndex === SKIPPED_OP && n > 0) throw error;
|
|
197
|
+
}
|
|
198
|
+
expectAtMost(n, error) {
|
|
199
|
+
assertGuardCount(n, "expectAtMost");
|
|
200
|
+
this.declareGuard("atMost", n, error);
|
|
201
|
+
}
|
|
202
|
+
declareGuard(kind, n, error) {
|
|
203
|
+
if (!(error instanceof Error)) {
|
|
204
|
+
throw new TxPlanError(
|
|
205
|
+
`${this.what}: an expectation needs the Error to throw when it does not hold (e.g. \`.expect\u2026(new Conflict("already accepted"))\`).`
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
if (this.guarded) {
|
|
209
|
+
throw new TxPlanError(
|
|
210
|
+
`${this.what} already has an expectation. One operation carries one expectation; declare the second one on its own operation.`
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
this.guarded = true;
|
|
214
|
+
if (this.opIndex === SKIPPED_OP) return;
|
|
215
|
+
this.builder.attachGuard(this.opIndex, kind, n, error);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
function assertGuardCount(n, fn) {
|
|
219
|
+
if (!Number.isInteger(n) || n < 0) {
|
|
220
|
+
throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
var MAX_OPS = 1e3;
|
|
224
|
+
var MAX_ROWS = 5e3;
|
|
225
|
+
var TxPlanBuilder = class {
|
|
226
|
+
ops = [];
|
|
227
|
+
/** Errors handed to expectations, indexed by the `slot` the server echoes. */
|
|
228
|
+
slots = [];
|
|
229
|
+
/** The table surface handed to the callback. Untyped here; the public
|
|
230
|
+
* `transaction()` signatures put the schema types on top. */
|
|
231
|
+
table(name) {
|
|
232
|
+
return {
|
|
233
|
+
insert: (values) => {
|
|
234
|
+
const encoded = encodeMap(values, false);
|
|
235
|
+
if (Object.keys(encoded).length === 0) {
|
|
236
|
+
throw new TxPlanError(`${name}.insert() needs at least one column`);
|
|
237
|
+
}
|
|
238
|
+
return this.push({ op: "insert", table: name, values: encoded }, `${name}.insert()`);
|
|
239
|
+
},
|
|
240
|
+
insertMany: (rows) => {
|
|
241
|
+
if (rows.length === 0) {
|
|
242
|
+
return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);
|
|
243
|
+
}
|
|
244
|
+
if (rows.length > MAX_ROWS) {
|
|
245
|
+
throw new TxPlanError(
|
|
246
|
+
`${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. Split the write across requests.`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
const encoded = rows.map((row) => encodeMap(row, false));
|
|
250
|
+
assertUniformRows(encoded, name);
|
|
251
|
+
return this.push({ op: "insertMany", table: name, rows: encoded }, `${name}.insertMany()`);
|
|
252
|
+
},
|
|
253
|
+
updateWhere: (where, set) => {
|
|
254
|
+
const encodedWhere = encodeMap(where, false);
|
|
255
|
+
const encodedSet = encodeMap(set, true);
|
|
256
|
+
if (Object.keys(encodedWhere).length === 0) {
|
|
257
|
+
throw new TxPlanError(
|
|
258
|
+
`${name}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
if (Object.keys(encodedSet).length === 0) {
|
|
262
|
+
throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);
|
|
263
|
+
}
|
|
264
|
+
return this.push(
|
|
265
|
+
{ op: "update", table: name, set: encodedSet, where: encodedWhere },
|
|
266
|
+
`${name}.updateWhere()`
|
|
267
|
+
);
|
|
268
|
+
},
|
|
269
|
+
deleteWhere: (where) => {
|
|
270
|
+
const encodedWhere = encodeMap(where, false);
|
|
271
|
+
if (Object.keys(encodedWhere).length === 0) {
|
|
272
|
+
throw new TxPlanError(
|
|
273
|
+
`${name}.deleteWhere() needs a filter. A delete with no filter empties the table.`
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
return this.push(
|
|
277
|
+
{ op: "delete", table: name, where: encodedWhere },
|
|
278
|
+
`${name}.deleteWhere()`
|
|
279
|
+
);
|
|
280
|
+
},
|
|
281
|
+
select: (where, options) => {
|
|
282
|
+
const op = { op: "select", table: name };
|
|
283
|
+
const encodedWhere = encodeMap(where ?? {}, false);
|
|
284
|
+
if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;
|
|
285
|
+
if (options?.limit !== void 0) {
|
|
286
|
+
if (!Number.isInteger(options.limit) || options.limit < 0) {
|
|
287
|
+
throw new TxPlanError(
|
|
288
|
+
`${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
op.limit = options.limit;
|
|
292
|
+
}
|
|
293
|
+
if (options?.lock !== void 0) op.lock = options.lock;
|
|
294
|
+
return this.push(op, `${name}.select()`);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
push(op, what) {
|
|
299
|
+
if (this.ops.length >= MAX_OPS) {
|
|
300
|
+
throw new TxPlanError(
|
|
301
|
+
`this transaction has ${MAX_OPS} operations, which is the limit. Use insertMany() for bulk writes, or split the work across requests.`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const index = this.ops.length;
|
|
305
|
+
this.ops.push(op);
|
|
306
|
+
return new TxRowsImpl(this, index, what);
|
|
307
|
+
}
|
|
308
|
+
/** Attach an expectation to an op and record its error in the slot table. */
|
|
309
|
+
attachGuard(opIndex, kind, n, error) {
|
|
310
|
+
const op = this.ops[opIndex];
|
|
311
|
+
if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);
|
|
312
|
+
const slot = this.slots.length;
|
|
313
|
+
this.slots.push(error);
|
|
314
|
+
op.guard = { kind, n, slot };
|
|
315
|
+
}
|
|
316
|
+
/** The serialisable plan. Empty when the callback described no writes. */
|
|
317
|
+
body() {
|
|
318
|
+
return { ops: this.ops };
|
|
319
|
+
}
|
|
320
|
+
/** The error the server's `slot` selects, or `null` when it names one this
|
|
321
|
+
* plan never declared (a server/client disagreement, not a tenant error). */
|
|
322
|
+
errorForSlot(slot) {
|
|
323
|
+
return this.slots[slot] ?? null;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
function assertUniformRows(rows, table) {
|
|
327
|
+
const first = rows[0];
|
|
328
|
+
if (!first) return;
|
|
329
|
+
const want = Object.keys(first);
|
|
330
|
+
const wantKey = want.join(",");
|
|
331
|
+
for (let i = 1; i < rows.length; i++) {
|
|
332
|
+
const got = Object.keys(rows[i]);
|
|
333
|
+
if (got.join(",") !== wantKey) {
|
|
334
|
+
throw new TxPlanError(
|
|
335
|
+
`${table}.insertMany(): every row must set the same columns. Row 0 sets [${want.join(", ")}] but row ${i} sets [${got.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function materializeResult(value, results) {
|
|
341
|
+
const ref = refDescriptor(value);
|
|
342
|
+
if (ref) {
|
|
343
|
+
const row = rowOf(results, ref.op, `\`${ref.field}\``);
|
|
344
|
+
if (!(ref.field in row)) {
|
|
345
|
+
throw new TxPlanError(
|
|
346
|
+
`the transaction's operation ${ref.op} returned no column \`${ref.field}\`.`
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
return row[ref.field];
|
|
350
|
+
}
|
|
351
|
+
const rowOp = rowOpIndex(value);
|
|
352
|
+
if (rowOp !== null) return rowOf(results, rowOp, "a row");
|
|
353
|
+
if (isRowsHandle(value)) {
|
|
354
|
+
throw new TxPlanError(
|
|
355
|
+
"an operation result cannot be returned from a transaction callback: its row count is not known until the plan runs. Declare an expectation (`.expectOne(err)`) and return the row, or a column of it."
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));
|
|
359
|
+
if (isPlainObject(value)) {
|
|
360
|
+
const out = {};
|
|
361
|
+
for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);
|
|
362
|
+
return out;
|
|
363
|
+
}
|
|
364
|
+
return value;
|
|
365
|
+
}
|
|
366
|
+
function rowOf(results, opIndex, what) {
|
|
367
|
+
const result = results[opIndex];
|
|
368
|
+
if (!result) {
|
|
369
|
+
throw new TxPlanError(
|
|
370
|
+
`the transaction returned no result for operation ${opIndex}, so ${what} cannot be read.`
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
const row = result.rows[0];
|
|
374
|
+
if (!row) {
|
|
375
|
+
throw new TxPlanError(
|
|
376
|
+
`the transaction's operation ${opIndex} returned no row, so ${what} cannot be read.`
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
return row;
|
|
380
|
+
}
|
|
381
|
+
function isPlainObject(value) {
|
|
382
|
+
if (typeof value !== "object" || value === null) return false;
|
|
383
|
+
const proto = Object.getPrototypeOf(value);
|
|
384
|
+
return proto === Object.prototype || proto === null;
|
|
385
|
+
}
|
|
386
|
+
async function runTxPlan(transport, tables, builder, fn) {
|
|
387
|
+
const returned = fn({ tables });
|
|
388
|
+
const body = builder.body();
|
|
389
|
+
if (body.ops.length === 0) {
|
|
390
|
+
return materializeResult(returned, []);
|
|
391
|
+
}
|
|
392
|
+
let response;
|
|
393
|
+
try {
|
|
394
|
+
response = await transport.txPlan(body);
|
|
395
|
+
} catch (err) {
|
|
396
|
+
throw translateRejection(err, builder);
|
|
397
|
+
}
|
|
398
|
+
return materializeResult(returned, response.results);
|
|
399
|
+
}
|
|
400
|
+
function translateRejection(err, builder) {
|
|
401
|
+
if (typeof err !== "object" || err === null) return err;
|
|
402
|
+
const rejection = err;
|
|
403
|
+
if (rejection.error_code !== "tx_guard_failed" || typeof rejection.slot !== "number") {
|
|
404
|
+
return err;
|
|
405
|
+
}
|
|
406
|
+
return builder.errorForSlot(rejection.slot) ?? err;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// src/runtime.ts
|
|
30
410
|
var __requestALS = new import_node_async_hooks.AsyncLocalStorage();
|
|
31
411
|
var runtime = null;
|
|
32
412
|
function __setRuntime(services) {
|
|
@@ -84,10 +464,23 @@ function makeTypedSurface(raw) {
|
|
|
84
464
|
return Object.assign(ops, {
|
|
85
465
|
tables: makeTablesAccessor(() => raw),
|
|
86
466
|
transaction(fn) {
|
|
87
|
-
|
|
467
|
+
const builder = new TxPlanBuilder();
|
|
468
|
+
return runTxPlan(raw, makeTxTablesAccessor(builder), builder, fn);
|
|
88
469
|
}
|
|
89
470
|
});
|
|
90
471
|
}
|
|
472
|
+
function makeTxTablesAccessor(builder) {
|
|
473
|
+
const tablesProxy = new Proxy(
|
|
474
|
+
{},
|
|
475
|
+
{
|
|
476
|
+
get(_t, prop) {
|
|
477
|
+
if (typeof prop !== "string") return void 0;
|
|
478
|
+
return builder.table(prop);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
);
|
|
482
|
+
return tablesProxy;
|
|
483
|
+
}
|
|
91
484
|
var Database = Object.assign(makeTypedSurface(rawDatabase), {
|
|
92
485
|
/**
|
|
93
486
|
* Lazily resolve the runtime's service-role sibling on each call. We do NOT
|
|
@@ -145,16 +538,27 @@ function createMockDB() {
|
|
|
145
538
|
updated: /* @__PURE__ */ new Map(),
|
|
146
539
|
deleted: /* @__PURE__ */ new Map()
|
|
147
540
|
};
|
|
541
|
+
function rowsOf(table) {
|
|
542
|
+
let rows = store.get(table);
|
|
543
|
+
if (!rows) {
|
|
544
|
+
rows = [];
|
|
545
|
+
store.set(table, rows);
|
|
546
|
+
}
|
|
547
|
+
return rows;
|
|
548
|
+
}
|
|
549
|
+
function track(map, table, row) {
|
|
550
|
+
const list = map.get(table);
|
|
551
|
+
if (list) list.push(row);
|
|
552
|
+
else map.set(table, [row]);
|
|
553
|
+
}
|
|
148
554
|
const ops = {
|
|
149
555
|
async query(_sql, _params) {
|
|
150
556
|
return [];
|
|
151
557
|
},
|
|
152
558
|
async insert(table, data) {
|
|
153
559
|
const record = { id: crypto.randomUUID(), ...data };
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if (!tracked.inserted.has(table)) tracked.inserted.set(table, []);
|
|
157
|
-
tracked.inserted.get(table).push(record);
|
|
560
|
+
rowsOf(table).push(record);
|
|
561
|
+
track(tracked.inserted, table, record);
|
|
158
562
|
return record;
|
|
159
563
|
},
|
|
160
564
|
async update(table, id, data) {
|
|
@@ -164,16 +568,16 @@ function createMockDB() {
|
|
|
164
568
|
if (idx >= 0) {
|
|
165
569
|
rows[idx] = updated;
|
|
166
570
|
}
|
|
167
|
-
|
|
168
|
-
tracked.updated.get(table).push(updated);
|
|
571
|
+
track(tracked.updated, table, updated);
|
|
169
572
|
return updated;
|
|
170
573
|
},
|
|
171
574
|
async delete(table, id) {
|
|
172
575
|
const rows = store.get(table) ?? [];
|
|
173
576
|
const idx = rows.findIndex((r) => r["id"] === id);
|
|
174
577
|
if (idx >= 0) rows.splice(idx, 1);
|
|
175
|
-
|
|
176
|
-
|
|
578
|
+
const list = tracked.deleted.get(table);
|
|
579
|
+
if (list) list.push(id);
|
|
580
|
+
else tracked.deleted.set(table, [id]);
|
|
177
581
|
},
|
|
178
582
|
async findById(table, id) {
|
|
179
583
|
const rows = store.get(table) ?? [];
|
|
@@ -187,11 +591,88 @@ function createMockDB() {
|
|
|
187
591
|
);
|
|
188
592
|
}
|
|
189
593
|
};
|
|
594
|
+
async function txPlan(plan) {
|
|
595
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
596
|
+
for (const [table, rows] of store) snapshot.set(table, [...rows]);
|
|
597
|
+
const trackedSnapshot = {
|
|
598
|
+
inserted: cloneTracked(tracked.inserted),
|
|
599
|
+
updated: cloneTracked(tracked.updated),
|
|
600
|
+
deleted: new Map([...tracked.deleted].map(([k, v]) => [k, [...v]]))
|
|
601
|
+
};
|
|
602
|
+
const results = [];
|
|
603
|
+
try {
|
|
604
|
+
for (const op of plan.ops) {
|
|
605
|
+
const result = applyOp(op, results);
|
|
606
|
+
results.push(result);
|
|
607
|
+
const failure = guardFailure(op.guard, result.rows.length);
|
|
608
|
+
if (failure) throw failure;
|
|
609
|
+
}
|
|
610
|
+
} catch (err) {
|
|
611
|
+
store.clear();
|
|
612
|
+
for (const [table, rows] of snapshot) store.set(table, rows);
|
|
613
|
+
tracked.inserted = trackedSnapshot.inserted;
|
|
614
|
+
tracked.updated = trackedSnapshot.updated;
|
|
615
|
+
tracked.deleted = trackedSnapshot.deleted;
|
|
616
|
+
throw err;
|
|
617
|
+
}
|
|
618
|
+
return { results };
|
|
619
|
+
}
|
|
620
|
+
function applyOp(op, results) {
|
|
621
|
+
switch (op.op) {
|
|
622
|
+
case "insert": {
|
|
623
|
+
const record = { id: crypto.randomUUID(), ...resolveMap(op.values ?? {}, results, null) };
|
|
624
|
+
rowsOf(op.table).push(record);
|
|
625
|
+
track(tracked.inserted, op.table, record);
|
|
626
|
+
return { rows: [record], rows_affected: 1 };
|
|
627
|
+
}
|
|
628
|
+
case "insertMany": {
|
|
629
|
+
const written = (op.rows ?? []).map((row) => {
|
|
630
|
+
const record = { id: crypto.randomUUID(), ...resolveMap(row, results, null) };
|
|
631
|
+
rowsOf(op.table).push(record);
|
|
632
|
+
track(tracked.inserted, op.table, record);
|
|
633
|
+
return record;
|
|
634
|
+
});
|
|
635
|
+
return { rows: written, rows_affected: written.length };
|
|
636
|
+
}
|
|
637
|
+
case "update": {
|
|
638
|
+
const rows = rowsOf(op.table);
|
|
639
|
+
const where = resolveMap(op.where ?? {}, results, null);
|
|
640
|
+
const written = [];
|
|
641
|
+
for (let i = 0; i < rows.length; i++) {
|
|
642
|
+
const row = rows[i];
|
|
643
|
+
if (!row || !matches(row, where)) continue;
|
|
644
|
+
const next = { ...row, ...resolveMap(op.set ?? {}, results, row) };
|
|
645
|
+
rows[i] = next;
|
|
646
|
+
track(tracked.updated, op.table, next);
|
|
647
|
+
written.push(next);
|
|
648
|
+
}
|
|
649
|
+
return { rows: written, rows_affected: written.length };
|
|
650
|
+
}
|
|
651
|
+
case "delete": {
|
|
652
|
+
const rows = rowsOf(op.table);
|
|
653
|
+
const where = resolveMap(op.where ?? {}, results, null);
|
|
654
|
+
const removed = rows.filter((row) => matches(row, where));
|
|
655
|
+
for (const row of removed) {
|
|
656
|
+
rows.splice(rows.indexOf(row), 1);
|
|
657
|
+
const id = row["id"];
|
|
658
|
+
const list = tracked.deleted.get(op.table);
|
|
659
|
+
const key = typeof id === "string" ? id : String(id);
|
|
660
|
+
if (list) list.push(key);
|
|
661
|
+
else tracked.deleted.set(op.table, [key]);
|
|
662
|
+
}
|
|
663
|
+
return { rows: removed, rows_affected: removed.length };
|
|
664
|
+
}
|
|
665
|
+
case "select": {
|
|
666
|
+
const where = resolveMap(op.where ?? {}, results, null);
|
|
667
|
+
let found = rowsOf(op.table).filter((row) => matches(row, where));
|
|
668
|
+
if (op.limit !== void 0) found = found.slice(0, op.limit);
|
|
669
|
+
return { rows: found, rows_affected: found.length };
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
190
673
|
const client = {
|
|
191
674
|
...ops,
|
|
192
|
-
|
|
193
|
-
return fn(ops);
|
|
194
|
-
},
|
|
675
|
+
txPlan,
|
|
195
676
|
// In tests there is no real DB role; `asService()` returns the same
|
|
196
677
|
// in-memory client so RLS-bypass code paths still hit the same store and
|
|
197
678
|
// tracking maps. The omitted `asService` matches the contract (no
|
|
@@ -214,6 +695,58 @@ function createMockDB() {
|
|
|
214
695
|
};
|
|
215
696
|
return client;
|
|
216
697
|
}
|
|
698
|
+
function cloneTracked(map) {
|
|
699
|
+
return new Map([...map].map(([k, v]) => [k, [...v]]));
|
|
700
|
+
}
|
|
701
|
+
function resolveValue(value, results, current, column) {
|
|
702
|
+
if (typeof value !== "object" || value === null) return value;
|
|
703
|
+
const tagged = value;
|
|
704
|
+
if (tagged.$ref) {
|
|
705
|
+
const row = results[tagged.$ref.op]?.rows[0];
|
|
706
|
+
if (!row) {
|
|
707
|
+
throw txRejection(409, "tx_ref_unresolved", {
|
|
708
|
+
message: `operation ${tagged.$ref.op} produced no row to reference`
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
return row[tagged.$ref.field];
|
|
712
|
+
}
|
|
713
|
+
if (tagged.$expr) {
|
|
714
|
+
const fn = tagged.$expr["fn"];
|
|
715
|
+
if (fn === "now") return (/* @__PURE__ */ new Date()).toISOString();
|
|
716
|
+
const by = Number(tagged.$expr["by"]);
|
|
717
|
+
const base = Number(current?.[column] ?? 0);
|
|
718
|
+
return fn === "dec" ? base - by : base + by;
|
|
719
|
+
}
|
|
720
|
+
return value;
|
|
721
|
+
}
|
|
722
|
+
function resolveMap(map, results, current) {
|
|
723
|
+
const out = {};
|
|
724
|
+
for (const [key, value] of Object.entries(map)) {
|
|
725
|
+
out[key] = resolveValue(value, results, current, key);
|
|
726
|
+
}
|
|
727
|
+
return out;
|
|
728
|
+
}
|
|
729
|
+
function matches(row, where) {
|
|
730
|
+
return Object.entries(where).every(
|
|
731
|
+
([key, value]) => value === null ? row[key] === null || row[key] === void 0 : row[key] === value
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
function guardFailure(guard, count) {
|
|
735
|
+
if (!guard) return null;
|
|
736
|
+
const ok = guard.kind === "one" ? count === 1 : guard.kind === "none" ? count === 0 : guard.kind === "atLeast" ? count >= guard.n : count <= guard.n;
|
|
737
|
+
if (ok) return null;
|
|
738
|
+
return txRejection(409, "tx_guard_failed", {
|
|
739
|
+
slot: guard.slot,
|
|
740
|
+
message: `expected ${guard.kind} ${guard.n} row(s), got ${count}`
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
function txRejection(status, code, extra) {
|
|
744
|
+
const err = new Error(extra.message);
|
|
745
|
+
err.status = status;
|
|
746
|
+
err.error_code = code;
|
|
747
|
+
if (extra.slot !== void 0) err.slot = extra.slot;
|
|
748
|
+
return err;
|
|
749
|
+
}
|
|
217
750
|
|
|
218
751
|
// src/test/context.ts
|
|
219
752
|
function createMockLogger(logs) {
|