@prisma-idb/client-idb 0.9.1 → 0.11.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/README.md +2 -0
- package/dist/client-auto.d.mts +3 -19
- package/dist/client-auto.d.mts.map +1 -1
- package/dist/client-auto.mjs +2 -2
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{idb-orm-MOH1S3ES.d.mts → executor-Bp-hdRg2.d.mts} +4 -397
- package/dist/executor-Bp-hdRg2.d.mts.map +1 -0
- package/dist/idb-orm-9XN3c9ly.d.mts +399 -0
- package/dist/idb-orm-9XN3c9ly.d.mts.map +1 -0
- package/dist/idb-orm-BitJ-EMq.mjs +1401 -0
- package/dist/idb-orm-BitJ-EMq.mjs.map +1 -0
- package/dist/internal.d.mts +39 -0
- package/dist/internal.d.mts.map +1 -0
- package/dist/internal.mjs +2 -0
- package/dist/{managed-client-CJD9lBx5.d.mts → managed-client-CS78EjPu.d.mts} +3 -2
- package/dist/managed-client-CS78EjPu.d.mts.map +1 -0
- package/dist/{managed-client-CA1_fthM.mjs → managed-client-CxlNmERd.mjs} +3 -2
- package/dist/{managed-client-CA1_fthM.mjs.map → managed-client-CxlNmERd.mjs.map} +1 -1
- package/dist/{idb-orm-kDKFzR3S.mjs → mutation-executor-SJqTuSbb.mjs} +12 -1326
- package/dist/mutation-executor-SJqTuSbb.mjs.map +1 -0
- package/dist/mutation-scope-1hS0ogGa.d.mts +33 -0
- package/dist/mutation-scope-1hS0ogGa.d.mts.map +1 -0
- package/dist/orm.d.mts +4 -75
- package/dist/orm.d.mts.map +1 -1
- package/dist/orm.mjs +3 -2
- package/dist/orm.mjs.map +1 -1
- package/package.json +8 -6
- package/dist/idb-orm-MOH1S3ES.d.mts.map +0 -1
- package/dist/idb-orm-kDKFzR3S.mjs.map +0 -1
- package/dist/managed-client-CJD9lBx5.d.mts.map +0 -1
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { andExpr, evaluateFilter, fieldFilter, nullCheckExpr, shorthandToFilterExpr } from "@prisma-idb/adapter-idb/runtime";
|
|
1
|
+
import { evaluateFilter, shorthandToFilterExpr } from "@prisma-idb/adapter-idb/runtime";
|
|
3
2
|
import { domainModelsAtDefaultNamespace } from "@prisma/orm-framework/contract/types";
|
|
4
|
-
import {
|
|
3
|
+
import { fieldValueToken, fieldValuesEqual, keyEquals as keyEquals$1, keyToken } from "@prisma-idb/target-idb/runtime";
|
|
5
4
|
import { generateId } from "@prisma/orm-framework/ids/runtime";
|
|
6
5
|
import { keyPathFields } from "@prisma-idb/target-idb/pack";
|
|
7
6
|
//#region src/core/types.ts
|
|
@@ -40,19 +39,6 @@ function extractKeyFromRow(row, keyPath) {
|
|
|
40
39
|
return keyPath.map((field) => row[field]);
|
|
41
40
|
}
|
|
42
41
|
/**
|
|
43
|
-
* Build a field → indexName lookup for every single-field, non-multi-entry
|
|
44
|
-
* index on `storeName`. Top-level scans use this map to find indexed equality
|
|
45
|
-
* conditions in combined filter expressions. Compound and multi-entry indexes
|
|
46
|
-
* cannot serve these single-field point lookups.
|
|
47
|
-
*/
|
|
48
|
-
function buildFieldToIndexMap(contract, storeName) {
|
|
49
|
-
const storeDef = contract.storage.stores[storeName];
|
|
50
|
-
const result = {};
|
|
51
|
-
if (storeDef?.indexes === void 0) return result;
|
|
52
|
-
for (const [indexName, indexDef] of Object.entries(storeDef.indexes)) if (typeof indexDef.keyPath === "string" && indexDef.multiEntry !== true) result[indexDef.keyPath] = indexName;
|
|
53
|
-
return result;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
42
|
* Resolve a model's named relation to a {@link ContractReferenceRelation} at
|
|
57
43
|
* runtime, or `undefined` when the relation is absent or an embedded relation
|
|
58
44
|
* (no `on` join block). Used by `include()` to find the related model name and
|
|
@@ -64,431 +50,6 @@ function getRelation(contract, modelName, relName) {
|
|
|
64
50
|
return relation;
|
|
65
51
|
}
|
|
66
52
|
//#endregion
|
|
67
|
-
//#region src/core/model-accessor.ts
|
|
68
|
-
/**
|
|
69
|
-
* Proxy-based typed accessor handed to `where(fn)` callbacks.
|
|
70
|
-
*
|
|
71
|
-
* Mirrors `createModelAccessor()` from
|
|
72
|
-
* Prisma ORM's SQL client, but without
|
|
73
|
-
* the codec-trait gating — IDB stores native JS values, so every operator
|
|
74
|
-
* is available on every field. The runtime accessor object is a Proxy
|
|
75
|
-
* that materialises an `IdbFieldAccessor` on demand for whichever field
|
|
76
|
-
* name is read; the type-level surface narrows that to the model's
|
|
77
|
-
* actual field set so callbacks get autocomplete.
|
|
78
|
-
*/
|
|
79
|
-
/**
|
|
80
|
-
* Build an {@link IdbFieldAccessor} for a single field. The accessor is
|
|
81
|
-
* shared via the proxy below, but each accessor instance is bound to its
|
|
82
|
-
* own field name so the produced AST nodes carry the right field.
|
|
83
|
-
*/
|
|
84
|
-
function createFieldAccessor(field) {
|
|
85
|
-
return {
|
|
86
|
-
eq: (value) => fieldFilter(field, "eq", value),
|
|
87
|
-
neq: (value) => fieldFilter(field, "neq", value),
|
|
88
|
-
gt: (value) => fieldFilter(field, "gt", value),
|
|
89
|
-
lt: (value) => fieldFilter(field, "lt", value),
|
|
90
|
-
gte: (value) => fieldFilter(field, "gte", value),
|
|
91
|
-
lte: (value) => fieldFilter(field, "lte", value),
|
|
92
|
-
in: (values) => fieldFilter(field, "in", values),
|
|
93
|
-
notIn: (values) => fieldFilter(field, "notIn", values),
|
|
94
|
-
contains: (sub) => fieldFilter(field, "contains", sub),
|
|
95
|
-
startsWith: (sub) => fieldFilter(field, "startsWith", sub),
|
|
96
|
-
endsWith: (sub) => fieldFilter(field, "endsWith", sub),
|
|
97
|
-
isNull: () => nullCheckExpr(field, true),
|
|
98
|
-
isNotNull: () => nullCheckExpr(field, false)
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Create the typed model accessor used by `where(fn)` callbacks.
|
|
103
|
-
*
|
|
104
|
-
* Implemented as a Proxy keyed on field names — every read returns an
|
|
105
|
-
* {@link IdbFieldAccessor} bound to that field. The accessor cache means
|
|
106
|
-
* `m.name.eq(...)` and `m.name.startsWith(...)` reuse the same per-field
|
|
107
|
-
* accessor object across the same `where()` invocation.
|
|
108
|
-
*
|
|
109
|
-
* The type parameter is structural — no contract is consulted at
|
|
110
|
-
* runtime, because TS already gates the visible field set at compile
|
|
111
|
-
* time. (Misspelled fields surface as accessor calls on names that
|
|
112
|
-
* don't exist in stored rows, which is consistent with how the
|
|
113
|
-
* shorthand form behaves today.)
|
|
114
|
-
*/
|
|
115
|
-
function createModelAccessor() {
|
|
116
|
-
const cache = /* @__PURE__ */ new Map();
|
|
117
|
-
return new Proxy({}, { get(_target, prop) {
|
|
118
|
-
if (typeof prop !== "string") return void 0;
|
|
119
|
-
let acc = cache.get(prop);
|
|
120
|
-
if (acc === void 0) {
|
|
121
|
-
acc = createFieldAccessor(prop);
|
|
122
|
-
cache.set(prop, acc);
|
|
123
|
-
}
|
|
124
|
-
return acc;
|
|
125
|
-
} });
|
|
126
|
-
}
|
|
127
|
-
//#endregion
|
|
128
|
-
//#region src/core/store-state.ts
|
|
129
|
-
/** Build an {@link IdbIncludeScalar} marker for a `count()` reducer. */
|
|
130
|
-
function createIncludeScalar(state) {
|
|
131
|
-
return {
|
|
132
|
-
kind: "includeScalar",
|
|
133
|
-
fn: "count",
|
|
134
|
-
state
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
/** Type guard: is `value` an {@link IdbIncludeScalar} marker? */
|
|
138
|
-
function isIncludeScalar(value) {
|
|
139
|
-
if (typeof value !== "object" || value === null) return false;
|
|
140
|
-
const candidate = value;
|
|
141
|
-
return candidate.kind === "includeScalar" && candidate.fn === "count";
|
|
142
|
-
}
|
|
143
|
-
/** Create a fresh, empty accessor state (no filters, no ordering, no includes). */
|
|
144
|
-
function emptyAccessorState() {
|
|
145
|
-
return {
|
|
146
|
-
filters: [],
|
|
147
|
-
includes: {}
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
/** Return a shallow-merged copy of `state` with the given overrides applied. */
|
|
151
|
-
function mergeAccessorState(state, overrides) {
|
|
152
|
-
return {
|
|
153
|
-
...state,
|
|
154
|
-
...overrides
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
//#endregion
|
|
158
|
-
//#region src/core/query-shaping.ts
|
|
159
|
-
/**
|
|
160
|
-
* Combine accumulated filter expressions with AND.
|
|
161
|
-
*
|
|
162
|
-
* Returns `undefined` when no filter is present so callers can skip building a
|
|
163
|
-
* row-filter closure. Shared by {@link IdbStoreAccessorImpl} (top-level scans)
|
|
164
|
-
* and the relation loader (refined `include()` child scans).
|
|
165
|
-
*/
|
|
166
|
-
function combineFilterExprs(filters) {
|
|
167
|
-
if (filters.length === 0) return void 0;
|
|
168
|
-
if (filters.length === 1) return filters[0];
|
|
169
|
-
return andExpr(filters);
|
|
170
|
-
}
|
|
171
|
-
/** Recursively flatten nested AND nodes into a single array of children. */
|
|
172
|
-
function flattenAnd(filter) {
|
|
173
|
-
if (filter.kind !== "and") return [filter];
|
|
174
|
-
return filter.exprs.flatMap(flattenAnd);
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* `true` when `field` is a *single-field* primary key that a lone `eq`
|
|
178
|
-
* condition can directly point-range-query (`store.get`/`openCursor(range)`
|
|
179
|
-
* against the store's own keyPath, no named index required).
|
|
180
|
-
*
|
|
181
|
-
* Deliberately `false` for a compound (array) `keyPath`, even if `field`
|
|
182
|
-
* happens to be one of its member fields — a single `eq` condition can only
|
|
183
|
-
* pin one member, not the whole compound key, so it can't drive a PK
|
|
184
|
-
* point-range scan on its own. Accelerating that case needs *all* member
|
|
185
|
-
* fields ANDed together, which is a cost-based multi-field planner decision
|
|
186
|
-
* (Phase 10 §3.2), not this peephole optimizer's job.
|
|
187
|
-
*/
|
|
188
|
-
function isPrimaryKeyField(field, keyPath) {
|
|
189
|
-
return typeof keyPath === "string" && field === keyPath;
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Scan the combined filter expression for the first `eq` field condition whose
|
|
193
|
-
* field either has a matching IDB index (`fieldToIndexName[field]` is set) or
|
|
194
|
-
* *is* the store's own primary key (`keyPath`) — a store's keyPath is always
|
|
195
|
-
* point-range-queryable directly, no named index required.
|
|
196
|
-
*
|
|
197
|
-
* When found, the indexed condition is peeled off and returned as an
|
|
198
|
-
* {@link IndexEqualityHint}; any remaining conditions are preserved in
|
|
199
|
-
* `remainingFilter`. Returns `null` when no usable index can be found.
|
|
200
|
-
*
|
|
201
|
-
* Nested AND nodes are flattened before scanning, so deeply-composed filters
|
|
202
|
-
* are handled correctly. Only `eq` conditions are considered — range operators
|
|
203
|
-
* (`gt`, `lt`, etc.) could also use an index range but that optimization is
|
|
204
|
-
* not yet implemented.
|
|
205
|
-
*/
|
|
206
|
-
function extractIndexEqualityHint(filter, fieldToIndexName, keyPath) {
|
|
207
|
-
if (filter === void 0) return null;
|
|
208
|
-
if (filter.kind === "field" && filter.op === "eq") {
|
|
209
|
-
const indexName = fieldToIndexName[filter.field];
|
|
210
|
-
if ((indexName !== void 0 || isPrimaryKeyField(filter.field, keyPath)) && isValidIdbKey(filter.value)) return {
|
|
211
|
-
indexName,
|
|
212
|
-
value: filter.value,
|
|
213
|
-
remainingFilter: void 0
|
|
214
|
-
};
|
|
215
|
-
return null;
|
|
216
|
-
}
|
|
217
|
-
if (filter.kind === "and") {
|
|
218
|
-
const flat = flattenAnd(filter);
|
|
219
|
-
for (let i = 0; i < flat.length; i++) {
|
|
220
|
-
const expr = flat[i];
|
|
221
|
-
if (expr.kind === "field" && expr.op === "eq") {
|
|
222
|
-
const indexName = fieldToIndexName[expr.field];
|
|
223
|
-
if ((indexName !== void 0 || isPrimaryKeyField(expr.field, keyPath)) && isValidIdbKey(expr.value)) {
|
|
224
|
-
const rest = flat.filter((_, j) => j !== i);
|
|
225
|
-
return {
|
|
226
|
-
indexName,
|
|
227
|
-
value: expr.value,
|
|
228
|
-
remainingFilter: combineFilterExprs(rest)
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
return null;
|
|
235
|
-
}
|
|
236
|
-
/**
|
|
237
|
-
* Check whether every branch of an OR node is a single `field eq value`
|
|
238
|
-
* condition whose field has a matching index. Returns an {@link IndexOrHint}
|
|
239
|
-
* when the whole OR can be satisfied by N point-range cursor scans, `null`
|
|
240
|
-
* otherwise.
|
|
241
|
-
*/
|
|
242
|
-
function tryExtractOrBranches(orNode, fieldToIndexName, keyPath, remainingFilter) {
|
|
243
|
-
if (orNode.exprs.length === 0) return null;
|
|
244
|
-
const branches = [];
|
|
245
|
-
for (const expr of orNode.exprs) {
|
|
246
|
-
if (expr.kind !== "field" || expr.op !== "eq") return null;
|
|
247
|
-
const indexName = fieldToIndexName[expr.field];
|
|
248
|
-
if (indexName === void 0 && !isPrimaryKeyField(expr.field, keyPath) || !isValidIdbKey(expr.value)) return null;
|
|
249
|
-
branches.push({
|
|
250
|
-
indexName,
|
|
251
|
-
value: expr.value
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
return {
|
|
255
|
-
branches,
|
|
256
|
-
remainingFilter
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Attempt to extract an {@link IndexOrHint} from `filter`.
|
|
261
|
-
*
|
|
262
|
-
* Handles two shapes:
|
|
263
|
-
* - Top-level `or` where every branch is `field eq value` on an indexed field.
|
|
264
|
-
* - Top-level `and` (with nested ANDs flattened) that contains exactly one `or`
|
|
265
|
-
* child fitting the above pattern; the remaining AND children become
|
|
266
|
-
* `remainingFilter` applied in-memory after the union.
|
|
267
|
-
*
|
|
268
|
-
* Returns `null` when the filter cannot be accelerated via OR index scans.
|
|
269
|
-
*/
|
|
270
|
-
function extractIndexOrHint(filter, fieldToIndexName, keyPath) {
|
|
271
|
-
if (filter === void 0) return null;
|
|
272
|
-
if (filter.kind === "or") return tryExtractOrBranches(filter, fieldToIndexName, keyPath, void 0);
|
|
273
|
-
if (filter.kind === "and") {
|
|
274
|
-
const flat = flattenAnd(filter);
|
|
275
|
-
const orIndices = [];
|
|
276
|
-
for (let i = 0; i < flat.length; i++) if (flat[i].kind === "or") orIndices.push(i);
|
|
277
|
-
if (orIndices.length !== 1) return null;
|
|
278
|
-
const orIdx = orIndices[0];
|
|
279
|
-
const orNode = flat[orIdx];
|
|
280
|
-
return tryExtractOrBranches(orNode, fieldToIndexName, keyPath, combineFilterExprs(flat.filter((_, j) => j !== orIdx)));
|
|
281
|
-
}
|
|
282
|
-
return null;
|
|
283
|
-
}
|
|
284
|
-
/**
|
|
285
|
-
* Build an in-memory comparator from an `orderBy` spec (field → direction).
|
|
286
|
-
*
|
|
287
|
-
* Returns `undefined` when there is nothing to sort by. Compares fields in
|
|
288
|
-
* declaration order, with {@link compareFieldValues}: the same order an
|
|
289
|
-
* IndexedDB index uses, so equal `Date`s tie and fall through to the next
|
|
290
|
-
* field, and `null`s sort last (first when descending).
|
|
291
|
-
*/
|
|
292
|
-
function buildRowComparator(orderBy) {
|
|
293
|
-
if (orderBy === void 0) return void 0;
|
|
294
|
-
return (a, b) => {
|
|
295
|
-
for (const [field, dir] of Object.entries(orderBy)) {
|
|
296
|
-
const cmp = compareFieldValues(a[field], b[field]);
|
|
297
|
-
if (cmp === 0) continue;
|
|
298
|
-
return dir === "desc" ? -cmp : cmp;
|
|
299
|
-
}
|
|
300
|
-
return 0;
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
/**
|
|
304
|
-
* `true` when a `cursor-scan` plan's result *cardinality* is fully determined
|
|
305
|
-
* by its store/index + key range — i.e. there is no in-memory `filter` that
|
|
306
|
-
* would need each row's value. Only then can `count()` be answered natively
|
|
307
|
-
* (`store.count(range)` / `index.count(range)`) without deserializing rows.
|
|
308
|
-
*
|
|
309
|
-
* `comparator` (ORDER BY), `direction`, `skip` and `take` don't change *which*
|
|
310
|
-
* rows match, so they don't disqualify a plan — `skip`/`take` are applied to
|
|
311
|
-
* the native total afterwards via {@link clampCount}.
|
|
312
|
-
*
|
|
313
|
-
* Safe for index scans because the equality hint that builds `range` never
|
|
314
|
-
* selects a `multiEntry` (or compound) index — `buildFieldToIndexMap` excludes
|
|
315
|
-
* them — so one record maps to at most one index entry and entries == rows.
|
|
316
|
-
*/
|
|
317
|
-
function isNativelyCountable(plan) {
|
|
318
|
-
return plan.filter === void 0;
|
|
319
|
-
}
|
|
320
|
-
/** Rewrites a natively-countable `cursor-scan` as the equivalent native `count` plan. */
|
|
321
|
-
function toCountPlan(plan) {
|
|
322
|
-
return {
|
|
323
|
-
meta: plan.meta,
|
|
324
|
-
kind: "count",
|
|
325
|
-
storeName: plan.storeName,
|
|
326
|
-
...plan.indexName !== void 0 ? { indexName: plan.indexName } : {},
|
|
327
|
-
...plan.range !== void 0 ? { range: plan.range } : {}
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Applies `skip`/`take` to an *unpaginated* total. A paginated count is pure
|
|
332
|
-
* arithmetic on the unpaginated count — `max(0, total - skip)`, capped at
|
|
333
|
-
* `take` — so this is exact, not an approximation.
|
|
334
|
-
*/
|
|
335
|
-
function clampCount(total, skip, take) {
|
|
336
|
-
let n = total;
|
|
337
|
-
if (skip !== void 0) n = Math.max(0, n - skip);
|
|
338
|
-
if (take !== void 0) n = Math.min(take, n);
|
|
339
|
-
return n;
|
|
340
|
-
}
|
|
341
|
-
//#endregion
|
|
342
|
-
//#region src/core/aggregate-builder.ts
|
|
343
|
-
/**
|
|
344
|
-
* Build the aggregate selector factory handed to `.aggregate(agg => …)` and
|
|
345
|
-
* `groupBy(...).aggregate(agg => …)`.
|
|
346
|
-
*
|
|
347
|
-
* Each method returns an {@link IdbAggregateSelector} marker; the actual
|
|
348
|
-
* reduction happens in {@link reduceAggregate} once the matching rows are
|
|
349
|
-
* materialised in memory. Mirrors `createAggregateBuilder` from the vendor
|
|
350
|
-
* `sql-orm-client/aggregate-builder.ts`, minus the field→column mapping (IDB
|
|
351
|
-
* stores native field names).
|
|
352
|
-
*/
|
|
353
|
-
function createAggregateBuilder() {
|
|
354
|
-
return {
|
|
355
|
-
count: () => ({
|
|
356
|
-
kind: "aggregate",
|
|
357
|
-
fn: "count"
|
|
358
|
-
}),
|
|
359
|
-
sum: (field) => ({
|
|
360
|
-
kind: "aggregate",
|
|
361
|
-
fn: "sum",
|
|
362
|
-
field
|
|
363
|
-
}),
|
|
364
|
-
avg: (field) => ({
|
|
365
|
-
kind: "aggregate",
|
|
366
|
-
fn: "avg",
|
|
367
|
-
field
|
|
368
|
-
}),
|
|
369
|
-
min: (field) => ({
|
|
370
|
-
kind: "aggregate",
|
|
371
|
-
fn: "min",
|
|
372
|
-
field
|
|
373
|
-
}),
|
|
374
|
-
max: (field) => ({
|
|
375
|
-
kind: "aggregate",
|
|
376
|
-
fn: "max",
|
|
377
|
-
field
|
|
378
|
-
})
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
/** Type guard: is `value` an {@link IdbAggregateSelector}? */
|
|
382
|
-
function isAggregateSelector(value) {
|
|
383
|
-
if (typeof value !== "object" || value === null) return false;
|
|
384
|
-
const candidate = value;
|
|
385
|
-
return candidate.kind === "aggregate" && (candidate.fn === "count" || candidate.fn === "sum" || candidate.fn === "avg" || candidate.fn === "min" || candidate.fn === "max");
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* Reduce a set of materialised rows to a single aggregate value.
|
|
389
|
-
*
|
|
390
|
-
* - `count` → the number of rows (always a number, never null).
|
|
391
|
-
* - `sum`/`avg`/`min`/`max` → computed over the non-null numeric values of
|
|
392
|
-
* `field`; `null` when no row has a non-null value (matching Prisma's
|
|
393
|
-
* "aggregate of an empty set is null" and the vendor `coerceAggregateValue`
|
|
394
|
-
* null handling). String-encoded numbers are coerced via `Number()`.
|
|
395
|
-
*/
|
|
396
|
-
function reduceAggregate(fn, field, rows) {
|
|
397
|
-
if (fn === "count") return rows.length;
|
|
398
|
-
if (field === void 0) return null;
|
|
399
|
-
const values = [];
|
|
400
|
-
for (const row of rows) {
|
|
401
|
-
const raw = row[field];
|
|
402
|
-
if (raw === null || raw === void 0) continue;
|
|
403
|
-
const n = typeof raw === "bigint" ? Number(raw) : Number(raw);
|
|
404
|
-
if (!Number.isNaN(n)) values.push(n);
|
|
405
|
-
}
|
|
406
|
-
if (values.length === 0) return null;
|
|
407
|
-
switch (fn) {
|
|
408
|
-
case "sum": return values.reduce((acc, n) => acc + n, 0);
|
|
409
|
-
case "avg": return values.reduce((acc, n) => acc + n, 0) / values.length;
|
|
410
|
-
case "min": return Math.min(...values);
|
|
411
|
-
case "max": return Math.max(...values);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* Run every selector in an aggregate spec against `rows`, producing the
|
|
416
|
-
* result object keyed by the spec's aliases.
|
|
417
|
-
*/
|
|
418
|
-
function computeAggregateSpec(spec, rows) {
|
|
419
|
-
const result = {};
|
|
420
|
-
for (const [alias, selector] of Object.entries(spec)) result[alias] = reduceAggregate(selector.fn, selector.field, rows);
|
|
421
|
-
return result;
|
|
422
|
-
}
|
|
423
|
-
/**
|
|
424
|
-
* Project an aggregate spec down to the plain `{ fn, field? }` shape carried by
|
|
425
|
-
* the query AST (`IdbAggregateAst.aggregates` / `IdbGroupByAst.aggregates`), so
|
|
426
|
-
* middleware can observe the requested aggregations.
|
|
427
|
-
*/
|
|
428
|
-
function toAggregateRequests(spec) {
|
|
429
|
-
const out = {};
|
|
430
|
-
for (const [alias, selector] of Object.entries(spec)) out[alias] = selector.field !== void 0 ? {
|
|
431
|
-
fn: selector.fn,
|
|
432
|
-
field: selector.field
|
|
433
|
-
} : { fn: selector.fn };
|
|
434
|
-
return out;
|
|
435
|
-
}
|
|
436
|
-
/**
|
|
437
|
-
* Validate a user-supplied aggregate spec: it must be non-empty and every
|
|
438
|
-
* value must be a real selector. Throws a descriptive error otherwise, so a
|
|
439
|
-
* typo (e.g. returning a plain object) fails loudly rather than silently
|
|
440
|
-
* producing `NaN`/`undefined` results.
|
|
441
|
-
*/
|
|
442
|
-
function assertValidAggregateSpec(spec, context) {
|
|
443
|
-
const entries = Object.entries(spec);
|
|
444
|
-
if (entries.length === 0) throw new Error(`${context} requires at least one aggregation selector`);
|
|
445
|
-
for (const [alias, selector] of entries) if (!isAggregateSelector(selector)) throw new Error(`${context} selector "${alias}" is invalid`);
|
|
446
|
-
}
|
|
447
|
-
//#endregion
|
|
448
|
-
//#region src/core/grouped-accessor.ts
|
|
449
|
-
/**
|
|
450
|
-
* Build the composite group key for a row. Uses a JSON encoding of the ordered
|
|
451
|
-
* key-field values so multi-field groups and primitive value types (string,
|
|
452
|
-
* number, boolean, null) partition correctly.
|
|
453
|
-
*/
|
|
454
|
-
function groupKeyOf(by, row) {
|
|
455
|
-
return JSON.stringify(by.map((field) => row[field] ?? null));
|
|
456
|
-
}
|
|
457
|
-
/** Build a grouped accessor that reduces materialized rows from the source accessor. */
|
|
458
|
-
function createGroupedAccessor(init) {
|
|
459
|
-
return { async aggregate(fn) {
|
|
460
|
-
const spec = fn(createAggregateBuilder());
|
|
461
|
-
assertValidAggregateSpec(spec, "groupBy().aggregate()");
|
|
462
|
-
const ast = {
|
|
463
|
-
kind: "groupBy",
|
|
464
|
-
modelName: init.modelName,
|
|
465
|
-
by: init.by,
|
|
466
|
-
aggregates: toAggregateRequests(spec),
|
|
467
|
-
...init.where !== void 0 ? { where: init.where } : {}
|
|
468
|
-
};
|
|
469
|
-
const rows = await init.materialize(ast);
|
|
470
|
-
const groups = /* @__PURE__ */ new Map();
|
|
471
|
-
for (const row of rows) {
|
|
472
|
-
const gk = groupKeyOf(init.by, row);
|
|
473
|
-
let group = groups.get(gk);
|
|
474
|
-
if (group === void 0) {
|
|
475
|
-
const key = {};
|
|
476
|
-
for (const field of init.by) key[field] = row[field];
|
|
477
|
-
group = {
|
|
478
|
-
key,
|
|
479
|
-
rows: []
|
|
480
|
-
};
|
|
481
|
-
groups.set(gk, group);
|
|
482
|
-
}
|
|
483
|
-
group.rows.push(row);
|
|
484
|
-
}
|
|
485
|
-
return Array.from(groups.values()).map((group) => ({
|
|
486
|
-
...group.key,
|
|
487
|
-
...computeAggregateSpec(spec, group.rows)
|
|
488
|
-
}));
|
|
489
|
-
} };
|
|
490
|
-
}
|
|
491
|
-
//#endregion
|
|
492
53
|
//#region src/core/enum-validation.ts
|
|
493
54
|
const rulesByContract = /* @__PURE__ */ new WeakMap();
|
|
494
55
|
function resolveEnumRule(contract, field) {
|
|
@@ -617,191 +178,6 @@ function applyUpdateDefaults(defaults, storeName, patch, cache) {
|
|
|
617
178
|
return result;
|
|
618
179
|
}
|
|
619
180
|
//#endregion
|
|
620
|
-
//#region src/core/relation-loader.ts
|
|
621
|
-
/**
|
|
622
|
-
* Batch-load a single named relation for all rows in `rows` and attach the
|
|
623
|
-
* result to each row under the `relName` key.
|
|
624
|
-
*
|
|
625
|
-
* The join matches every field of the relation, so compound foreign keys join
|
|
626
|
-
* on the whole tuple. It uses one key-range scan per distinct tuple when an
|
|
627
|
-
* index or the related primary key covers the target fields, and otherwise
|
|
628
|
-
* one full scan with an in-memory filter. Rows are then grouped in memory,
|
|
629
|
-
* which avoids N+1 queries.
|
|
630
|
-
*
|
|
631
|
-
* The `entry` carries any `include()` refinement:
|
|
632
|
-
*
|
|
633
|
-
* - `collection` — the refined `where` further filters the child scan;
|
|
634
|
-
* `orderBy` / `skip` / `take` are applied **per parent group** for `1:N`
|
|
635
|
-
* relations (each parent's children are independently sorted and paginated).
|
|
636
|
-
* - `scalar` — the relation field becomes the `count` of matching children
|
|
637
|
-
* (to-many only; `include()` rejects scalar refinements on to-one relations).
|
|
638
|
-
*
|
|
639
|
-
* @param relName - The relation key to load (e.g. `"posts"`, `"author"`).
|
|
640
|
-
* @param entry - How to materialise the relation (collection vs scalar + refinement state).
|
|
641
|
-
* @param rows - The parent rows to attach related data to.
|
|
642
|
-
* @param contract - The resolved IDB contract.
|
|
643
|
-
* @param modelName - The source model name (owner of the relation).
|
|
644
|
-
* @param executor - The query executor used to run the related-store scan.
|
|
645
|
-
*/
|
|
646
|
-
async function loadRelation(relName, entry, rows, contract, modelName, executor, groupingKey) {
|
|
647
|
-
if (rows.length === 0) return rows;
|
|
648
|
-
const models = domainModelsAtDefaultNamespace(contract.domain);
|
|
649
|
-
const model = models[modelName];
|
|
650
|
-
if (model === void 0) return rows;
|
|
651
|
-
const rawRelation = model.relations[relName];
|
|
652
|
-
if (rawRelation === void 0) return rows;
|
|
653
|
-
if (!("on" in rawRelation)) return rows;
|
|
654
|
-
const relation = rawRelation;
|
|
655
|
-
const { cardinality, on } = relation;
|
|
656
|
-
const relatedModelName = relation.to.model;
|
|
657
|
-
const localFields = on.localFields;
|
|
658
|
-
const targetFields = on.targetFields;
|
|
659
|
-
if (localFields.length === 0 || localFields.length !== targetFields.length) return rows;
|
|
660
|
-
const relatedModel = models[relatedModelName];
|
|
661
|
-
if (relatedModel === void 0) return rows;
|
|
662
|
-
const relatedStoreName = typeof relatedModel.storage === "object" && relatedModel.storage !== null && "storeName" in relatedModel.storage ? String(relatedModel.storage["storeName"]) : relatedModelName;
|
|
663
|
-
const isScalar = entry.kind === "scalar";
|
|
664
|
-
const localTuples = /* @__PURE__ */ new Map();
|
|
665
|
-
for (const row of rows) {
|
|
666
|
-
const token = tupleToken(row, localFields);
|
|
667
|
-
if (token !== null) localTuples.set(token, localFields.map((f) => row[f]));
|
|
668
|
-
}
|
|
669
|
-
if (localTuples.size === 0) return rows.map((row) => ({
|
|
670
|
-
...row,
|
|
671
|
-
[relName]: isScalar ? 0 : cardinality === "1:N" ? [] : null
|
|
672
|
-
}));
|
|
673
|
-
const refinedWhere = combineFilterExprs(entry.state.filters);
|
|
674
|
-
const planMeta = {
|
|
675
|
-
target: "idb",
|
|
676
|
-
storageHash: contract.storage.storageHash,
|
|
677
|
-
lane: "idb-orm",
|
|
678
|
-
annotations: { groupingKey }
|
|
679
|
-
};
|
|
680
|
-
const rangeSource = findRangeSource(contract, relatedStoreName, relatedModelName, targetFields);
|
|
681
|
-
let relatedRows;
|
|
682
|
-
if (rangeSource !== void 0) {
|
|
683
|
-
const refinedFilter = refinedWhere !== void 0 ? (row) => evaluateFilter(refinedWhere, row) : void 0;
|
|
684
|
-
const ranges = [];
|
|
685
|
-
for (const values of localTuples.values()) {
|
|
686
|
-
const ordered = keyPathFields(rangeSource.keyPath).map((f) => values[targetFields.indexOf(f)]);
|
|
687
|
-
if (!ordered.every((v) => isValidIdbKey(v))) continue;
|
|
688
|
-
ranges.push(IDBKeyRange.only(typeof rangeSource.keyPath === "string" ? ordered[0] : ordered));
|
|
689
|
-
}
|
|
690
|
-
relatedRows = (await Promise.all(ranges.map(async (range) => {
|
|
691
|
-
const plan = {
|
|
692
|
-
meta: planMeta,
|
|
693
|
-
idbPlan: {
|
|
694
|
-
meta: planMeta,
|
|
695
|
-
kind: "cursor-scan",
|
|
696
|
-
storeName: relatedStoreName,
|
|
697
|
-
...rangeSource.indexName !== void 0 ? { indexName: rangeSource.indexName } : {},
|
|
698
|
-
range,
|
|
699
|
-
...refinedFilter !== void 0 ? { filter: refinedFilter } : {}
|
|
700
|
-
}
|
|
701
|
-
};
|
|
702
|
-
const rows = [];
|
|
703
|
-
for await (const row of executor.query(plan)) rows.push(row);
|
|
704
|
-
return rows;
|
|
705
|
-
}))).flat();
|
|
706
|
-
} else {
|
|
707
|
-
relatedRows = [];
|
|
708
|
-
const filter = (row) => {
|
|
709
|
-
const token = tupleToken(row, targetFields);
|
|
710
|
-
return token !== null && localTuples.has(token) && (refinedWhere === void 0 || evaluateFilter(refinedWhere, row));
|
|
711
|
-
};
|
|
712
|
-
const plan = {
|
|
713
|
-
meta: planMeta,
|
|
714
|
-
idbPlan: {
|
|
715
|
-
meta: planMeta,
|
|
716
|
-
kind: "cursor-scan",
|
|
717
|
-
storeName: relatedStoreName,
|
|
718
|
-
filter
|
|
719
|
-
}
|
|
720
|
-
};
|
|
721
|
-
for await (const row of executor.query(plan)) relatedRows.push(row);
|
|
722
|
-
}
|
|
723
|
-
return attachRelatedRows(relName, entry, rows, relatedRows, relation);
|
|
724
|
-
}
|
|
725
|
-
/** Attach related rows by their join tuple, shaping each parent's collection independently. */
|
|
726
|
-
function attachRelatedRows(relName, entry, rows, relatedRows, relation) {
|
|
727
|
-
const { cardinality, on: { localFields, targetFields } } = relation;
|
|
728
|
-
if (cardinality === "1:N") {
|
|
729
|
-
const grouped = /* @__PURE__ */ new Map();
|
|
730
|
-
for (const rrow of relatedRows) {
|
|
731
|
-
const gk = tupleToken(rrow, targetFields);
|
|
732
|
-
if (gk === null) continue;
|
|
733
|
-
const group = grouped.get(gk) ?? [];
|
|
734
|
-
group.push(rrow);
|
|
735
|
-
grouped.set(gk, group);
|
|
736
|
-
}
|
|
737
|
-
const groupFor = (row) => {
|
|
738
|
-
const token = tupleToken(row, localFields);
|
|
739
|
-
return token === null ? [] : grouped.get(token) ?? [];
|
|
740
|
-
};
|
|
741
|
-
if (entry.kind === "scalar") return rows.map((row) => ({
|
|
742
|
-
...row,
|
|
743
|
-
[relName]: groupFor(row).length
|
|
744
|
-
}));
|
|
745
|
-
const comparator = buildRowComparator(entry.state.orderBy);
|
|
746
|
-
const skip = entry.state.skip ?? 0;
|
|
747
|
-
const take = entry.state.take;
|
|
748
|
-
return rows.map((row) => {
|
|
749
|
-
let group = groupFor(row);
|
|
750
|
-
if (comparator !== void 0) group = [...group].sort(comparator);
|
|
751
|
-
if (skip > 0 || take !== void 0) group = group.slice(skip, take !== void 0 ? skip + take : void 0);
|
|
752
|
-
return {
|
|
753
|
-
...row,
|
|
754
|
-
[relName]: group
|
|
755
|
-
};
|
|
756
|
-
});
|
|
757
|
-
}
|
|
758
|
-
const indexed = /* @__PURE__ */ new Map();
|
|
759
|
-
for (const rrow of relatedRows) {
|
|
760
|
-
const token = tupleToken(rrow, targetFields);
|
|
761
|
-
if (token !== null) indexed.set(token, rrow);
|
|
762
|
-
}
|
|
763
|
-
return rows.map((row) => {
|
|
764
|
-
const token = tupleToken(row, localFields);
|
|
765
|
-
return {
|
|
766
|
-
...row,
|
|
767
|
-
[relName]: (token === null ? void 0 : indexed.get(token)) ?? null
|
|
768
|
-
};
|
|
769
|
-
});
|
|
770
|
-
}
|
|
771
|
-
/**
|
|
772
|
-
* A `Map` key for the values of `fields` in `row`, or `null` when any of them
|
|
773
|
-
* is null or undefined. Equal `Date`s and binary values give equal tokens.
|
|
774
|
-
*/
|
|
775
|
-
function tupleToken(row, fields) {
|
|
776
|
-
const parts = [];
|
|
777
|
-
for (const field of fields) {
|
|
778
|
-
const value = row[field];
|
|
779
|
-
if (value === null || value === void 0) return null;
|
|
780
|
-
const token = fieldValueToken(value);
|
|
781
|
-
parts.push([typeof token, String(token)]);
|
|
782
|
-
}
|
|
783
|
-
return JSON.stringify(parts);
|
|
784
|
-
}
|
|
785
|
-
/**
|
|
786
|
-
* Finds an index, or else the store's primary key, whose key path has exactly
|
|
787
|
-
* `fields` (in any order), so a lookup on those fields can use a key range.
|
|
788
|
-
* Returns `undefined` when there is none, or when `IDBKeyRange` isn't available.
|
|
789
|
-
*/
|
|
790
|
-
function findRangeSource(contract, storeName, modelName, fields) {
|
|
791
|
-
if (typeof IDBKeyRange === "undefined") return void 0;
|
|
792
|
-
const coversFields = (keyPath) => {
|
|
793
|
-
const keyFields = keyPathFields(keyPath);
|
|
794
|
-
return keyFields.length === fields.length && keyFields.every((f) => fields.includes(f));
|
|
795
|
-
};
|
|
796
|
-
const indexes = contract.storage.stores[storeName]?.indexes ?? {};
|
|
797
|
-
for (const [indexName, indexDef] of Object.entries(indexes)) if (indexDef.multiEntry !== true && coversFields(indexDef.keyPath)) return {
|
|
798
|
-
indexName,
|
|
799
|
-
keyPath: indexDef.keyPath
|
|
800
|
-
};
|
|
801
|
-
const primaryKey = getKeyPath(contract, modelName);
|
|
802
|
-
return coversFields(primaryKey) ? { keyPath: primaryKey } : void 0;
|
|
803
|
-
}
|
|
804
|
-
//#endregion
|
|
805
181
|
//#region src/core/mutation-scope.ts
|
|
806
182
|
/**
|
|
807
183
|
* Run a callback inside a single multi-store IDB readwrite transaction.
|
|
@@ -1261,49 +637,10 @@ function isChildEnforcementRelation(contract, modelName, def) {
|
|
|
1261
637
|
return false;
|
|
1262
638
|
}
|
|
1263
639
|
/**
|
|
1264
|
-
* An `IDBKeyRange` for the lookup "does `modelName` have a row whose `field`
|
|
1265
|
-
* equals `value`?" — but ONLY when `field` is that model's own single-field
|
|
1266
|
-
* primary key (so the answer is a pure key lookup that needs no row value)
|
|
1267
|
-
* and `value` is a legal IDB key. `null` otherwise, and the caller keeps its
|
|
1268
|
-
* value-materializing `cursor-scan`.
|
|
1269
|
-
*
|
|
1270
|
-
* Deliberately `null` for a compound primary key even if `field` is one of its
|
|
1271
|
-
* members (one member can't pin the whole key), and for any non-key field
|
|
1272
|
-
* (that needs an index-resolution step — Phase 10.5's shared primitive, not
|
|
1273
|
-
* this helper's job). `IDBKeyRange.only` throws `DataError` on invalid keys
|
|
1274
|
-
* (`null`, `NaN`, booleans, …), hence the guard.
|
|
1275
|
-
*/
|
|
1276
|
-
function pkEqualityRange(contract, modelName, field, value) {
|
|
1277
|
-
if (typeof IDBKeyRange === "undefined") return null;
|
|
1278
|
-
const keyPath = getKeyPath(contract, modelName);
|
|
1279
|
-
if (typeof keyPath !== "string" || keyPath !== field) return null;
|
|
1280
|
-
if (!isValidIdbKey(value)) return null;
|
|
1281
|
-
return IDBKeyRange.only(value);
|
|
1282
|
-
}
|
|
1283
|
-
/**
|
|
1284
|
-
* Resolves to the first primary key in `storeName` within `range`, or
|
|
1285
|
-
* `undefined` — one `getKey` request, no row deserialized.
|
|
1286
|
-
*/
|
|
1287
|
-
async function firstKeyInRange(scope, meta, storeName, range) {
|
|
1288
|
-
return (await scope.execute({
|
|
1289
|
-
meta,
|
|
1290
|
-
kind: "keys",
|
|
1291
|
-
storeName,
|
|
1292
|
-
range,
|
|
1293
|
-
take: 1
|
|
1294
|
-
}))[0]?.["key"];
|
|
1295
|
-
}
|
|
1296
|
-
/**
|
|
1297
640
|
* `true` if any child row matches the relation against `parentRow`'s values —
|
|
1298
|
-
* the existence check behind `restrict`.
|
|
1299
|
-
* child field is the child model's own primary key (a shared-PK 1:1); a
|
|
1300
|
-
* value-materializing `cursor-scan` (`take: 1`) otherwise.
|
|
641
|
+
* the existence check behind `restrict`.
|
|
1301
642
|
*/
|
|
1302
|
-
async function childExists(scope,
|
|
1303
|
-
if (def.targetFields.length === 1) {
|
|
1304
|
-
const range = pkEqualityRange(contract, def.relatedModelName, def.targetFields[0], parentRow[def.localFields[0]]);
|
|
1305
|
-
if (range !== null) return await firstKeyInRange(scope, meta, def.relatedStoreName, range) !== void 0;
|
|
1306
|
-
}
|
|
643
|
+
async function childExists(scope, meta, def, parentRow) {
|
|
1307
644
|
return (await scope.execute({
|
|
1308
645
|
meta,
|
|
1309
646
|
kind: "cursor-scan",
|
|
@@ -1455,7 +792,7 @@ async function applyReferentialActionsForRowOnUpdate(scope, contract, modelName,
|
|
|
1455
792
|
const action = getReferentialActionForRelation(contract, modelName, def, "onUpdate");
|
|
1456
793
|
const childFilter = buildChildFilterFromRow(def, oldRow);
|
|
1457
794
|
if (action === "restrict") {
|
|
1458
|
-
if (await childExists(scope,
|
|
795
|
+
if (await childExists(scope, meta, def, oldRow)) throw new Error(`Cannot update ${modelName} '${keyToken(extractKeyFromRow(oldRow, keyPath))}': changing field(s) ${changedFields.join(", ")} would orphan child records on relation '${def.relationName}'. Update or remove those children first, or declare onUpdate: Cascade, SetNull or SetDefault on the relation.`);
|
|
1459
796
|
continue;
|
|
1460
797
|
}
|
|
1461
798
|
if (action === "cascade") {
|
|
@@ -1566,20 +903,14 @@ function fkCheckNeedsExistingRow(contract, modelName, data) {
|
|
|
1566
903
|
/**
|
|
1567
904
|
* Does `parentModel` have a row whose `fields` equal `values`, pairwise?
|
|
1568
905
|
*
|
|
1569
|
-
*
|
|
1570
|
-
* one
|
|
1571
|
-
*
|
|
1572
|
-
* for checks that run while that row is being deleted or changed.
|
|
906
|
+
* Scans the parent store, comparing values the way IndexedDB compares keys.
|
|
907
|
+
* `excludeKey` leaves out one parent row, for checks that run while that row
|
|
908
|
+
* is being deleted or changed.
|
|
1573
909
|
*/
|
|
1574
910
|
async function parentExists(scope, contract, meta, parentModel, fields, values, excludeKey) {
|
|
1575
911
|
const storeName = getStoreName(contract, parentModel);
|
|
1576
912
|
const keyPath = getKeyPath(contract, parentModel);
|
|
1577
|
-
const
|
|
1578
|
-
if (range !== null) {
|
|
1579
|
-
const foundKey = await firstKeyInRange(scope, meta, storeName, range);
|
|
1580
|
-
return foundKey !== void 0 && (excludeKey === void 0 || !keyEquals(foundKey, excludeKey));
|
|
1581
|
-
}
|
|
1582
|
-
const filter = (row) => fields.every((f, i) => fieldValuesEqual(row[f], values[i])) && (excludeKey === void 0 || !keyEquals(extractKeyFromRow(row, keyPath), excludeKey));
|
|
913
|
+
const filter = (row) => fields.every((f, i) => fieldValuesEqual(row[f], values[i])) && (excludeKey === void 0 || !keyEquals$1(extractKeyFromRow(row, keyPath), excludeKey));
|
|
1583
914
|
return (await scope.execute({
|
|
1584
915
|
meta,
|
|
1585
916
|
kind: "cursor-scan",
|
|
@@ -1588,19 +919,6 @@ async function parentExists(scope, contract, meta, parentModel, fields, values,
|
|
|
1588
919
|
take: 1
|
|
1589
920
|
})).length > 0;
|
|
1590
921
|
}
|
|
1591
|
-
/**
|
|
1592
|
-
* An `IDBKeyRange` for "the row whose primary key is `values`", when `fields`
|
|
1593
|
-
* are exactly the key's fields (in any order) and every value is a valid
|
|
1594
|
-
* IndexedDB key. `null` otherwise, and the caller scans instead.
|
|
1595
|
-
*/
|
|
1596
|
-
function primaryKeyRange(keyPath, fields, values) {
|
|
1597
|
-
if (typeof IDBKeyRange === "undefined") return null;
|
|
1598
|
-
const keyFields = keyPathFields(keyPath);
|
|
1599
|
-
if (keyFields.length !== fields.length || !keyFields.every((f) => fields.includes(f))) return null;
|
|
1600
|
-
const ordered = keyFields.map((f) => values[fields.indexOf(f)]);
|
|
1601
|
-
if (!ordered.every((v) => isValidIdbKey(v))) return null;
|
|
1602
|
-
return IDBKeyRange.only(typeof keyPath === "string" ? ordered[0] : ordered);
|
|
1603
|
-
}
|
|
1604
922
|
/** `id='u1'`, or `orgId='a', id='u1'` for a compound key. */
|
|
1605
923
|
function describeTuple(fields, values) {
|
|
1606
924
|
return fields.map((f, i) => `${f}='${String(values[i])}'`).join(", ");
|
|
@@ -1775,7 +1093,7 @@ async function applyReferentialActionsForRow(scope, contract, modelName, row, vi
|
|
|
1775
1093
|
const action = getReferentialActionForRelation(contract, modelName, def, "onDelete");
|
|
1776
1094
|
const childFilter = buildChildFilterFromRow(def, row);
|
|
1777
1095
|
if (action === "restrict") {
|
|
1778
|
-
if (await childExists(scope,
|
|
1096
|
+
if (await childExists(scope, meta, def, row)) throw new Error(`Cannot delete ${modelName} '${keyToken(extractKeyFromRow(row, keyPath))}': child records exist on relation '${def.relationName}'. Delete those children first, or declare onDelete: Cascade, SetNull or SetDefault on the relation.`);
|
|
1779
1097
|
continue;
|
|
1780
1098
|
}
|
|
1781
1099
|
if (action === "cascade") {
|
|
@@ -1873,638 +1191,6 @@ async function executeDeleteAllWithReferentialActions(options) {
|
|
|
1873
1191
|
});
|
|
1874
1192
|
}
|
|
1875
1193
|
//#endregion
|
|
1876
|
-
|
|
1877
|
-
/**
|
|
1878
|
-
* Concrete immutable query builder.
|
|
1879
|
-
*
|
|
1880
|
-
* Internal details:
|
|
1881
|
-
* - All state is in `#state` (filters, orderBy, skip, take, includes, selectedFields).
|
|
1882
|
-
* - Builder methods clone via `#clone()` — O(1) copies since state is
|
|
1883
|
-
* structurally shared.
|
|
1884
|
-
* - `all()` materialises the main rows first, then batch-loads each included
|
|
1885
|
-
* relation, then applies any `.select()` projection before yielding.
|
|
1886
|
-
* - `#includeRefinementMode` flips `count()` from an async terminal to an
|
|
1887
|
-
* {@link IdbIncludeScalar} marker so it can be used inside `include()`.
|
|
1888
|
-
*/
|
|
1889
|
-
var IdbStoreAccessorImpl = class IdbStoreAccessorImpl {
|
|
1890
|
-
#contract;
|
|
1891
|
-
#modelName;
|
|
1892
|
-
#executor;
|
|
1893
|
-
#storeName;
|
|
1894
|
-
#state;
|
|
1895
|
-
#newGroupingKey;
|
|
1896
|
-
#includeRefinementMode;
|
|
1897
|
-
constructor(contract, modelName, executor, state, newGroupingKey, includeRefinementMode = false) {
|
|
1898
|
-
this.#contract = contract;
|
|
1899
|
-
this.#modelName = modelName;
|
|
1900
|
-
this.#executor = executor;
|
|
1901
|
-
this.#storeName = getStoreName(contract, modelName);
|
|
1902
|
-
this.#state = state ?? emptyAccessorState();
|
|
1903
|
-
let _key = 0;
|
|
1904
|
-
this.#newGroupingKey = newGroupingKey ?? (() => `idb-op-${++_key}`);
|
|
1905
|
-
this.#includeRefinementMode = includeRefinementMode;
|
|
1906
|
-
}
|
|
1907
|
-
where(filter) {
|
|
1908
|
-
const expr = typeof filter === "function" ? filter(createModelAccessor()) : shorthandToFilterExpr(filter);
|
|
1909
|
-
if (expr === void 0) return this.#clone({});
|
|
1910
|
-
return this.#clone({ filters: [...this.#state.filters, expr] });
|
|
1911
|
-
}
|
|
1912
|
-
orderBy(spec) {
|
|
1913
|
-
return this.#clone({ orderBy: spec });
|
|
1914
|
-
}
|
|
1915
|
-
take(n) {
|
|
1916
|
-
return this.#clone({ take: n });
|
|
1917
|
-
}
|
|
1918
|
-
skip(n) {
|
|
1919
|
-
return this.#clone({ skip: n });
|
|
1920
|
-
}
|
|
1921
|
-
include(relation, refineFn) {
|
|
1922
|
-
const entry = this.#resolveIncludeEntry(relation, refineFn);
|
|
1923
|
-
const newState = mergeAccessorState(this.#state, { includes: {
|
|
1924
|
-
...this.#state.includes,
|
|
1925
|
-
[relation]: entry
|
|
1926
|
-
} });
|
|
1927
|
-
return new IdbStoreAccessorImpl(this.#contract, this.#modelName, this.#executor, newState, this.#newGroupingKey, this.#includeRefinementMode);
|
|
1928
|
-
}
|
|
1929
|
-
select(...fields) {
|
|
1930
|
-
return this.#clone({ selectedFields: fields });
|
|
1931
|
-
}
|
|
1932
|
-
all() {
|
|
1933
|
-
const groupingKey = this.#newGroupingKey();
|
|
1934
|
-
const buildScanPlan = this.#buildScanPlan.bind(this);
|
|
1935
|
-
const executeOrRows = this.#executeOrRows.bind(this);
|
|
1936
|
-
const executorQuery = this.#executor.query.bind(this.#executor);
|
|
1937
|
-
const applyIncludes = this.#applyIncludes.bind(this);
|
|
1938
|
-
const projectRows = this.#projectRows.bind(this);
|
|
1939
|
-
const combined = this.#combinedFilterExpr();
|
|
1940
|
-
const fieldToIndexMap = typeof IDBKeyRange !== "undefined" ? buildFieldToIndexMap(this.#contract, this.#storeName) : void 0;
|
|
1941
|
-
const keyPath = getKeyPath(this.#contract, this.#modelName);
|
|
1942
|
-
const comparator = buildRowComparator(this.#state.orderBy);
|
|
1943
|
-
const skip = this.#state.skip;
|
|
1944
|
-
const take = this.#state.take;
|
|
1945
|
-
return new AsyncIterableResult((async function* () {
|
|
1946
|
-
let rows;
|
|
1947
|
-
const orHint = fieldToIndexMap !== void 0 ? extractIndexOrHint(combined, fieldToIndexMap, keyPath) : null;
|
|
1948
|
-
if (orHint !== null) {
|
|
1949
|
-
rows = await executeOrRows(orHint, groupingKey, combined);
|
|
1950
|
-
if (comparator !== void 0) rows.sort(comparator);
|
|
1951
|
-
if (skip !== void 0) rows = rows.slice(skip);
|
|
1952
|
-
if (take !== void 0) rows = rows.slice(0, take);
|
|
1953
|
-
} else {
|
|
1954
|
-
const scanPlan = buildScanPlan(groupingKey, fieldToIndexMap);
|
|
1955
|
-
rows = [];
|
|
1956
|
-
for await (const row of executorQuery(scanPlan)) rows.push(row);
|
|
1957
|
-
}
|
|
1958
|
-
const withIncludes = await applyIncludes(rows, groupingKey);
|
|
1959
|
-
for (const row of projectRows(withIncludes)) yield row;
|
|
1960
|
-
})());
|
|
1961
|
-
}
|
|
1962
|
-
async first() {
|
|
1963
|
-
return this.take(1).all().first();
|
|
1964
|
-
}
|
|
1965
|
-
async aggregate(fn) {
|
|
1966
|
-
const spec = fn(createAggregateBuilder());
|
|
1967
|
-
assertValidAggregateSpec(spec, "aggregate()");
|
|
1968
|
-
const combined = this.#combinedFilterExpr();
|
|
1969
|
-
const ast = {
|
|
1970
|
-
kind: "aggregate",
|
|
1971
|
-
modelName: this.#modelName,
|
|
1972
|
-
aggregates: toAggregateRequests(spec),
|
|
1973
|
-
...combined !== void 0 ? { where: combined } : {}
|
|
1974
|
-
};
|
|
1975
|
-
const groupingKey = this.#newGroupingKey();
|
|
1976
|
-
if (Object.values(spec).every((selector) => selector.fn === "count")) {
|
|
1977
|
-
const scanPlan = this.#buildScanPlan(groupingKey);
|
|
1978
|
-
const total = await this.#executeNativeCount(scanPlan, ast);
|
|
1979
|
-
if (total !== null) {
|
|
1980
|
-
const result = {};
|
|
1981
|
-
for (const alias of Object.keys(spec)) result[alias] = total;
|
|
1982
|
-
return result;
|
|
1983
|
-
}
|
|
1984
|
-
}
|
|
1985
|
-
return computeAggregateSpec(spec, await this.#materialize(groupingKey, ast));
|
|
1986
|
-
}
|
|
1987
|
-
groupBy(...fields) {
|
|
1988
|
-
const combined = this.#combinedFilterExpr();
|
|
1989
|
-
const materialize = (ast) => this.#materialize(this.#newGroupingKey(), ast);
|
|
1990
|
-
return createGroupedAccessor({
|
|
1991
|
-
modelName: this.#modelName,
|
|
1992
|
-
by: fields,
|
|
1993
|
-
where: combined,
|
|
1994
|
-
materialize
|
|
1995
|
-
});
|
|
1996
|
-
}
|
|
1997
|
-
async create(data) {
|
|
1998
|
-
const record = data;
|
|
1999
|
-
if (hasNestedMutationCallbacks(this.#contract, this.#modelName, record)) return await executeNestedCreateMutation({
|
|
2000
|
-
executor: requireTransactionExecutor(this.#executor),
|
|
2001
|
-
contract: this.#contract,
|
|
2002
|
-
modelName: this.#modelName,
|
|
2003
|
-
data: record
|
|
2004
|
-
});
|
|
2005
|
-
const withDefaults = applyCreateDefaults(this.#contract.execution?.mutations.defaults, this.#storeName, record, createMutationDefaultsCache());
|
|
2006
|
-
assertEnumValues(this.#contract, this.#modelName, withDefaults);
|
|
2007
|
-
if (hasScalarFkFields(this.#contract, this.#modelName, withDefaults)) return await executeScalarCreateWithFkValidation({
|
|
2008
|
-
executor: requireTransactionExecutor(this.#executor),
|
|
2009
|
-
contract: this.#contract,
|
|
2010
|
-
modelName: this.#modelName,
|
|
2011
|
-
data: withDefaults
|
|
2012
|
-
});
|
|
2013
|
-
const groupingKey = this.#newGroupingKey();
|
|
2014
|
-
const meta = this.#planMeta(groupingKey);
|
|
2015
|
-
const plan = {
|
|
2016
|
-
meta,
|
|
2017
|
-
ast: {
|
|
2018
|
-
kind: "create",
|
|
2019
|
-
modelName: this.#modelName,
|
|
2020
|
-
data: withDefaults
|
|
2021
|
-
},
|
|
2022
|
-
idbPlan: {
|
|
2023
|
-
meta,
|
|
2024
|
-
kind: "add",
|
|
2025
|
-
storeName: this.#storeName,
|
|
2026
|
-
record: withDefaults
|
|
2027
|
-
}
|
|
2028
|
-
};
|
|
2029
|
-
for await (const row of this.#executor.query(plan)) return row;
|
|
2030
|
-
return withDefaults;
|
|
2031
|
-
}
|
|
2032
|
-
async findUnique(key) {
|
|
2033
|
-
const groupingKey = this.#newGroupingKey();
|
|
2034
|
-
const meta = this.#planMeta(groupingKey);
|
|
2035
|
-
const plan = {
|
|
2036
|
-
meta,
|
|
2037
|
-
ast: {
|
|
2038
|
-
kind: "findUnique",
|
|
2039
|
-
modelName: this.#modelName,
|
|
2040
|
-
key
|
|
2041
|
-
},
|
|
2042
|
-
idbPlan: {
|
|
2043
|
-
meta,
|
|
2044
|
-
kind: "key-get",
|
|
2045
|
-
storeName: this.#storeName,
|
|
2046
|
-
key
|
|
2047
|
-
}
|
|
2048
|
-
};
|
|
2049
|
-
for await (const row of this.#executor.query(plan)) return row;
|
|
2050
|
-
return null;
|
|
2051
|
-
}
|
|
2052
|
-
async delete(key) {
|
|
2053
|
-
if (hasEnforceableChildRelations(this.#contract, this.#modelName)) {
|
|
2054
|
-
await executeDeleteWithReferentialActions({
|
|
2055
|
-
executor: requireTransactionExecutor(this.#executor),
|
|
2056
|
-
contract: this.#contract,
|
|
2057
|
-
modelName: this.#modelName,
|
|
2058
|
-
key
|
|
2059
|
-
});
|
|
2060
|
-
return;
|
|
2061
|
-
}
|
|
2062
|
-
const groupingKey = this.#newGroupingKey();
|
|
2063
|
-
const meta = this.#planMeta(groupingKey);
|
|
2064
|
-
const plan = {
|
|
2065
|
-
meta,
|
|
2066
|
-
ast: {
|
|
2067
|
-
kind: "delete",
|
|
2068
|
-
modelName: this.#modelName,
|
|
2069
|
-
key
|
|
2070
|
-
},
|
|
2071
|
-
idbPlan: {
|
|
2072
|
-
meta,
|
|
2073
|
-
kind: "delete",
|
|
2074
|
-
storeName: this.#storeName,
|
|
2075
|
-
key
|
|
2076
|
-
}
|
|
2077
|
-
};
|
|
2078
|
-
await this.#executor.query(plan).toArray();
|
|
2079
|
-
}
|
|
2080
|
-
async update(patch) {
|
|
2081
|
-
const patchRecord = patch;
|
|
2082
|
-
if (hasNestedMutationCallbacks(this.#contract, this.#modelName, patchRecord)) return await executeNestedUpdateMutation({
|
|
2083
|
-
executor: requireTransactionExecutor(this.#executor),
|
|
2084
|
-
contract: this.#contract,
|
|
2085
|
-
modelName: this.#modelName,
|
|
2086
|
-
filters: this.#state.filters,
|
|
2087
|
-
data: patchRecord
|
|
2088
|
-
});
|
|
2089
|
-
return await executeScalarUpdateWithFkValidation({
|
|
2090
|
-
executor: requireTransactionExecutor(this.#executor),
|
|
2091
|
-
contract: this.#contract,
|
|
2092
|
-
modelName: this.#modelName,
|
|
2093
|
-
filters: this.#state.filters,
|
|
2094
|
-
data: patchRecord
|
|
2095
|
-
});
|
|
2096
|
-
}
|
|
2097
|
-
/**
|
|
2098
|
-
* Always routes through the transaction scope (`executeBulkUpdateWithFkValidation`),
|
|
2099
|
-
* unlike single-row `update()`'s plan-level fallback for the no-FK-field
|
|
2100
|
-
* case. A bulk scan-write's affected row set isn't knowable until it
|
|
2101
|
-
* actually runs — going through the transaction scope is what lets the
|
|
2102
|
-
* sync interceptor observe the real affected rows and write one outbox
|
|
2103
|
-
* event per row (see `SyncInterceptingTransactionScope#maybeTrack`'s
|
|
2104
|
-
* `scan-write` case), atomically with the write itself, instead of one
|
|
2105
|
-
* event for the whole batch with no way to recover which rows it covered.
|
|
2106
|
-
*/
|
|
2107
|
-
updateAll(patch) {
|
|
2108
|
-
const contract = this.#contract;
|
|
2109
|
-
const modelName = this.#modelName;
|
|
2110
|
-
const filters = this.#state.filters;
|
|
2111
|
-
const patchRecord = patch;
|
|
2112
|
-
const executor = requireTransactionExecutor(this.#executor);
|
|
2113
|
-
return new AsyncIterableResult((async function* () {
|
|
2114
|
-
const rows = await executeBulkUpdateWithFkValidation({
|
|
2115
|
-
executor,
|
|
2116
|
-
contract,
|
|
2117
|
-
modelName,
|
|
2118
|
-
filters,
|
|
2119
|
-
data: patchRecord
|
|
2120
|
-
});
|
|
2121
|
-
for (const row of rows) yield row;
|
|
2122
|
-
})());
|
|
2123
|
-
}
|
|
2124
|
-
async updateCount(patch) {
|
|
2125
|
-
return (await this.updateAll(patch).toArray()).length;
|
|
2126
|
-
}
|
|
2127
|
-
async upsert(args) {
|
|
2128
|
-
const keyPath = getKeyPath(this.#contract, this.#modelName);
|
|
2129
|
-
const whereExpr = shorthandToFilterExpr(args.where);
|
|
2130
|
-
const matches = (row) => whereExpr === void 0 || evaluateFilter(whereExpr, row);
|
|
2131
|
-
const meta = this.#planMeta(this.#newGroupingKey());
|
|
2132
|
-
const createRecord = args.create;
|
|
2133
|
-
const patchRecord = args.update;
|
|
2134
|
-
const storeName = this.#storeName;
|
|
2135
|
-
const executionDefaults = this.#contract.execution?.mutations.defaults;
|
|
2136
|
-
const exec = requireTransactionExecutor(this.#executor);
|
|
2137
|
-
const effectivePatch = applyUpdateDefaults(executionDefaults, storeName, patchRecord, createMutationDefaultsCache());
|
|
2138
|
-
const createWithDefaults = applyCreateDefaults(executionDefaults, storeName, createRecord, createMutationDefaultsCache());
|
|
2139
|
-
assertEnumValues(this.#contract, this.#modelName, effectivePatch);
|
|
2140
|
-
assertEnumValues(this.#contract, this.#modelName, createWithDefaults);
|
|
2141
|
-
const { storeNames: onUpdateStoreNames } = collectOnUpdateEnforcementStoreNames(this.#contract, this.#modelName, effectivePatch);
|
|
2142
|
-
return withMutationScope(exec, [.../* @__PURE__ */ new Set([
|
|
2143
|
-
storeName,
|
|
2144
|
-
...onUpdateStoreNames,
|
|
2145
|
-
...collectScalarFkStoreNames(this.#contract, this.#modelName, createWithDefaults),
|
|
2146
|
-
...collectScalarFkStoreNames(this.#contract, this.#modelName, effectivePatch)
|
|
2147
|
-
])], async (scope) => {
|
|
2148
|
-
const existing = (await scope.execute({
|
|
2149
|
-
meta,
|
|
2150
|
-
kind: "cursor-scan",
|
|
2151
|
-
storeName,
|
|
2152
|
-
filter: matches,
|
|
2153
|
-
take: 1
|
|
2154
|
-
}))[0];
|
|
2155
|
-
if (existing === void 0) {
|
|
2156
|
-
await validateScalarFks(scope, this.#contract, this.#modelName, createWithDefaults);
|
|
2157
|
-
return (await scope.execute({
|
|
2158
|
-
meta,
|
|
2159
|
-
kind: "add",
|
|
2160
|
-
storeName,
|
|
2161
|
-
record: createWithDefaults
|
|
2162
|
-
}))[0] ?? createWithDefaults;
|
|
2163
|
-
}
|
|
2164
|
-
await validateScalarFks(scope, this.#contract, this.#modelName, effectivePatch, existing);
|
|
2165
|
-
const key = extractKeyFromRow(existing, keyPath);
|
|
2166
|
-
await applyReferentialActionsForRowOnUpdate(scope, this.#contract, this.#modelName, existing, effectivePatch);
|
|
2167
|
-
return (await scope.execute({
|
|
2168
|
-
meta,
|
|
2169
|
-
kind: "update",
|
|
2170
|
-
storeName,
|
|
2171
|
-
key,
|
|
2172
|
-
patch: effectivePatch
|
|
2173
|
-
}))[0] ?? existing;
|
|
2174
|
-
});
|
|
2175
|
-
}
|
|
2176
|
-
createAll(data) {
|
|
2177
|
-
const defaultsCache = createMutationDefaultsCache();
|
|
2178
|
-
const executionDefaults = this.#contract.execution?.mutations.defaults;
|
|
2179
|
-
const records = data.map((d) => applyCreateDefaults(executionDefaults, this.#storeName, d, defaultsCache));
|
|
2180
|
-
if (records.some((row) => hasScalarFkFields(this.#contract, this.#modelName, row))) {
|
|
2181
|
-
const executor = requireTransactionExecutor(this.#executor);
|
|
2182
|
-
const contract = this.#contract;
|
|
2183
|
-
const modelName = this.#modelName;
|
|
2184
|
-
return new AsyncIterableResult((async function* () {
|
|
2185
|
-
const rows = await executeScalarCreateAllWithFkValidation({
|
|
2186
|
-
executor,
|
|
2187
|
-
contract,
|
|
2188
|
-
modelName,
|
|
2189
|
-
data: records
|
|
2190
|
-
});
|
|
2191
|
-
for (const row of rows) yield row;
|
|
2192
|
-
})());
|
|
2193
|
-
}
|
|
2194
|
-
const groupingKey = this.#newGroupingKey();
|
|
2195
|
-
const meta = this.#planMeta(groupingKey);
|
|
2196
|
-
const plan = {
|
|
2197
|
-
meta,
|
|
2198
|
-
ast: {
|
|
2199
|
-
kind: "createAll",
|
|
2200
|
-
modelName: this.#modelName,
|
|
2201
|
-
data: records
|
|
2202
|
-
},
|
|
2203
|
-
idbPlan: {
|
|
2204
|
-
meta,
|
|
2205
|
-
kind: "batch",
|
|
2206
|
-
storeNames: [this.#storeName],
|
|
2207
|
-
ops: records.map((record) => ({
|
|
2208
|
-
meta,
|
|
2209
|
-
kind: "add",
|
|
2210
|
-
storeName: this.#storeName,
|
|
2211
|
-
record
|
|
2212
|
-
}))
|
|
2213
|
-
}
|
|
2214
|
-
};
|
|
2215
|
-
const executorQuery = this.#executor.query.bind(this.#executor);
|
|
2216
|
-
const contract = this.#contract;
|
|
2217
|
-
const modelName = this.#modelName;
|
|
2218
|
-
return new AsyncIterableResult((async function* () {
|
|
2219
|
-
for (const record of records) assertEnumValues(contract, modelName, record);
|
|
2220
|
-
for await (const row of executorQuery(plan)) yield row;
|
|
2221
|
-
})());
|
|
2222
|
-
}
|
|
2223
|
-
async createCount(data) {
|
|
2224
|
-
return (await this.createAll(data).toArray()).length;
|
|
2225
|
-
}
|
|
2226
|
-
/**
|
|
2227
|
-
* Always routes through the transaction scope (`executeDeleteAllWithReferentialActions`),
|
|
2228
|
-
* not just when there are enforceable child relations to cascade — that
|
|
2229
|
-
* function already handles the no-relations case correctly (an empty
|
|
2230
|
-
* relation list is a no-op loop), and going through it unconditionally is
|
|
2231
|
-
* what lets the sync interceptor's transaction-scope tracking write one
|
|
2232
|
-
* outbox event per actually-deleted row instead of one lump event for
|
|
2233
|
-
* the whole batch with no way to know which rows it covered. See
|
|
2234
|
-
* `updateAll()`'s doc comment for the same reasoning.
|
|
2235
|
-
*/
|
|
2236
|
-
deleteAll() {
|
|
2237
|
-
const combined = this.#combinedFilterExpr();
|
|
2238
|
-
const filter = combined !== void 0 ? (row) => evaluateFilter(combined, row) : void 0;
|
|
2239
|
-
const contract = this.#contract;
|
|
2240
|
-
const modelName = this.#modelName;
|
|
2241
|
-
const executor = requireTransactionExecutor(this.#executor);
|
|
2242
|
-
return new AsyncIterableResult((async function* () {
|
|
2243
|
-
const rows = await executeDeleteAllWithReferentialActions({
|
|
2244
|
-
executor,
|
|
2245
|
-
contract,
|
|
2246
|
-
modelName,
|
|
2247
|
-
...filter !== void 0 ? { filter } : {}
|
|
2248
|
-
});
|
|
2249
|
-
for (const row of rows) yield row;
|
|
2250
|
-
})());
|
|
2251
|
-
}
|
|
2252
|
-
async deleteCount() {
|
|
2253
|
-
return (await this.deleteAll().toArray()).length;
|
|
2254
|
-
}
|
|
2255
|
-
count() {
|
|
2256
|
-
if (this.#includeRefinementMode) return createIncludeScalar(this.#state);
|
|
2257
|
-
return this.#countTerminal();
|
|
2258
|
-
}
|
|
2259
|
-
async #countTerminal() {
|
|
2260
|
-
const groupingKey = this.#newGroupingKey();
|
|
2261
|
-
const combined = this.#combinedFilterExpr();
|
|
2262
|
-
const fieldToIndexMap = typeof IDBKeyRange !== "undefined" ? buildFieldToIndexMap(this.#contract, this.#storeName) : void 0;
|
|
2263
|
-
if (fieldToIndexMap !== void 0) {
|
|
2264
|
-
const orHint = extractIndexOrHint(combined, fieldToIndexMap, getKeyPath(this.#contract, this.#modelName));
|
|
2265
|
-
if (orHint !== null) return clampCount((await this.#executeOrRows(orHint, groupingKey, combined)).length, this.#state.skip, this.#state.take);
|
|
2266
|
-
}
|
|
2267
|
-
const scanPlan = this.#buildScanPlan(groupingKey, fieldToIndexMap);
|
|
2268
|
-
const scanAst = scanPlan.ast;
|
|
2269
|
-
const ast = {
|
|
2270
|
-
kind: "count",
|
|
2271
|
-
modelName: this.#modelName,
|
|
2272
|
-
...scanAst?.kind === "findMany" && scanAst.where !== void 0 ? { where: scanAst.where } : {}
|
|
2273
|
-
};
|
|
2274
|
-
const nativeTotal = await this.#executeNativeCount(scanPlan, ast);
|
|
2275
|
-
if (nativeTotal !== null) return clampCount(nativeTotal, this.#state.skip, this.#state.take);
|
|
2276
|
-
const plan = {
|
|
2277
|
-
...scanPlan,
|
|
2278
|
-
ast
|
|
2279
|
-
};
|
|
2280
|
-
let n = 0;
|
|
2281
|
-
for await (const _ of this.#executor.query(plan)) n++;
|
|
2282
|
-
return n;
|
|
2283
|
-
}
|
|
2284
|
-
/**
|
|
2285
|
-
* Resolve an `include()` argument pair into an {@link IncludeEntry}: run the
|
|
2286
|
-
* optional refinement against a fresh refinement-mode child accessor, then
|
|
2287
|
-
* classify the result as a scalar count or a refined collection.
|
|
2288
|
-
*/
|
|
2289
|
-
#resolveIncludeEntry(relation, refineFn) {
|
|
2290
|
-
if (refineFn === void 0) return {
|
|
2291
|
-
kind: "collection",
|
|
2292
|
-
state: emptyAccessorState()
|
|
2293
|
-
};
|
|
2294
|
-
const rel = getRelation(this.#contract, this.#modelName, relation);
|
|
2295
|
-
const relatedModelName = rel?.to.model ?? relation;
|
|
2296
|
-
const refined = refineFn(new IdbStoreAccessorImpl(this.#contract, relatedModelName, this.#executor, emptyAccessorState(), this.#newGroupingKey, true));
|
|
2297
|
-
if (isIncludeScalar(refined)) {
|
|
2298
|
-
if (rel !== void 0 && rel.cardinality !== "1:N") throw new Error(`include('${relation}'): count() is only supported for to-many (1:N) relations`);
|
|
2299
|
-
return {
|
|
2300
|
-
kind: "scalar",
|
|
2301
|
-
fn: refined.fn,
|
|
2302
|
-
state: refined.state
|
|
2303
|
-
};
|
|
2304
|
-
}
|
|
2305
|
-
if (refined instanceof IdbStoreAccessorImpl) return {
|
|
2306
|
-
kind: "collection",
|
|
2307
|
-
state: refined.#state
|
|
2308
|
-
};
|
|
2309
|
-
throw new Error(`include('${relation}') refinement must return the collection (for where/orderBy/take/skip) or a count() selector`);
|
|
2310
|
-
}
|
|
2311
|
-
/**
|
|
2312
|
-
* Runs `scanPlan` as a native `count` plan when its cardinality is fully
|
|
2313
|
-
* determined by a key range (no in-memory filter) — returning the
|
|
2314
|
-
* *unpaginated* total — or `null` when it can't (the caller then falls back
|
|
2315
|
-
* to materializing). `ast` is attached so middleware sees the caller's
|
|
2316
|
-
* intent (`count` / `aggregate`) regardless of the physical plan.
|
|
2317
|
-
*/
|
|
2318
|
-
async #executeNativeCount(scanPlan, ast) {
|
|
2319
|
-
const body = scanPlan.idbPlan;
|
|
2320
|
-
if (body.kind !== "cursor-scan" || !isNativelyCountable(body)) return null;
|
|
2321
|
-
const nativePlan = {
|
|
2322
|
-
...scanPlan,
|
|
2323
|
-
ast,
|
|
2324
|
-
idbPlan: toCountPlan(body)
|
|
2325
|
-
};
|
|
2326
|
-
let total = 0;
|
|
2327
|
-
for await (const row of this.#executor.query(nativePlan)) total = row.count;
|
|
2328
|
-
return total;
|
|
2329
|
-
}
|
|
2330
|
-
/**
|
|
2331
|
-
* Materialise all rows matching the accumulated filters with no pagination —
|
|
2332
|
-
* used by `aggregate()` / `groupBy()`. The supplied `ast` is attached to the
|
|
2333
|
-
* scan plan so middleware can observe the aggregate intent.
|
|
2334
|
-
*/
|
|
2335
|
-
async #materialize(groupingKey, ast) {
|
|
2336
|
-
const combined = this.#combinedFilterExpr();
|
|
2337
|
-
const filter = combined !== void 0 ? (row) => evaluateFilter(combined, row) : void 0;
|
|
2338
|
-
const meta = this.#planMeta(groupingKey);
|
|
2339
|
-
const plan = {
|
|
2340
|
-
meta,
|
|
2341
|
-
ast,
|
|
2342
|
-
idbPlan: {
|
|
2343
|
-
meta,
|
|
2344
|
-
kind: "cursor-scan",
|
|
2345
|
-
storeName: this.#storeName,
|
|
2346
|
-
...filter !== void 0 ? { filter } : {}
|
|
2347
|
-
}
|
|
2348
|
-
};
|
|
2349
|
-
const rows = [];
|
|
2350
|
-
for await (const row of this.#executor.query(plan)) rows.push(row);
|
|
2351
|
-
return rows;
|
|
2352
|
-
}
|
|
2353
|
-
#buildScanPlan(groupingKey, fieldToIndexMap) {
|
|
2354
|
-
const combined = this.#combinedFilterExpr();
|
|
2355
|
-
const comparator = buildRowComparator(this.#state.orderBy);
|
|
2356
|
-
const meta = this.#planMeta(groupingKey);
|
|
2357
|
-
const ast = {
|
|
2358
|
-
kind: "findMany",
|
|
2359
|
-
modelName: this.#modelName,
|
|
2360
|
-
...combined !== void 0 ? { where: combined } : {},
|
|
2361
|
-
...this.#state.orderBy !== void 0 ? { orderBy: this.#state.orderBy } : {},
|
|
2362
|
-
...this.#state.skip !== void 0 ? { skip: this.#state.skip } : {},
|
|
2363
|
-
...this.#state.take !== void 0 ? { take: this.#state.take } : {}
|
|
2364
|
-
};
|
|
2365
|
-
let hint = null;
|
|
2366
|
-
if (typeof IDBKeyRange !== "undefined") hint = extractIndexEqualityHint(combined, fieldToIndexMap ?? buildFieldToIndexMap(this.#contract, this.#storeName), getKeyPath(this.#contract, this.#modelName));
|
|
2367
|
-
const remainingFilter = hint !== null ? hint.remainingFilter : combined;
|
|
2368
|
-
const filter = remainingFilter !== void 0 ? (row) => evaluateFilter(remainingFilter, row) : void 0;
|
|
2369
|
-
return {
|
|
2370
|
-
meta,
|
|
2371
|
-
ast,
|
|
2372
|
-
idbPlan: {
|
|
2373
|
-
meta,
|
|
2374
|
-
kind: "cursor-scan",
|
|
2375
|
-
storeName: this.#storeName,
|
|
2376
|
-
...hint?.indexName !== void 0 ? { indexName: hint.indexName } : {},
|
|
2377
|
-
...hint !== null ? { range: IDBKeyRange.only(hint.value) } : {},
|
|
2378
|
-
...filter !== void 0 ? { filter } : {},
|
|
2379
|
-
...comparator !== void 0 ? { comparator } : {},
|
|
2380
|
-
...this.#state.skip !== void 0 ? { skip: this.#state.skip } : {},
|
|
2381
|
-
...this.#state.take !== void 0 ? { take: this.#state.take } : {}
|
|
2382
|
-
}
|
|
2383
|
-
};
|
|
2384
|
-
}
|
|
2385
|
-
/**
|
|
2386
|
-
* Execute one cursor-scan per OR branch, union the results, deduplicate by
|
|
2387
|
-
* primary key, and apply `hint.remainingFilter` in-memory. Skip/take are
|
|
2388
|
-
* NOT applied here — the caller slices the array after union so pagination
|
|
2389
|
-
* is correct across branches.
|
|
2390
|
-
*/
|
|
2391
|
-
async #executeOrRows(hint, groupingKey, combined) {
|
|
2392
|
-
const meta = this.#planMeta(groupingKey);
|
|
2393
|
-
const storeName = this.#storeName;
|
|
2394
|
-
const keyPath = getKeyPath(this.#contract, this.#modelName);
|
|
2395
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2396
|
-
const rows = [];
|
|
2397
|
-
const ast = {
|
|
2398
|
-
kind: "findMany",
|
|
2399
|
-
modelName: this.#modelName,
|
|
2400
|
-
...combined !== void 0 ? { where: combined } : {}
|
|
2401
|
-
};
|
|
2402
|
-
const branchResults = await Promise.all(hint.branches.map(async (branch) => {
|
|
2403
|
-
const plan = {
|
|
2404
|
-
meta,
|
|
2405
|
-
ast,
|
|
2406
|
-
idbPlan: {
|
|
2407
|
-
meta,
|
|
2408
|
-
kind: "cursor-scan",
|
|
2409
|
-
storeName,
|
|
2410
|
-
...branch.indexName !== void 0 ? { indexName: branch.indexName } : {},
|
|
2411
|
-
range: IDBKeyRange.only(branch.value)
|
|
2412
|
-
}
|
|
2413
|
-
};
|
|
2414
|
-
const branchRows = [];
|
|
2415
|
-
for await (const row of this.#executor.query(plan)) branchRows.push(row);
|
|
2416
|
-
return branchRows;
|
|
2417
|
-
}));
|
|
2418
|
-
for (const branchRows of branchResults) for (const row of branchRows) {
|
|
2419
|
-
const pk = keyToken(extractKeyFromRow(row, keyPath));
|
|
2420
|
-
if (!seen.has(pk)) {
|
|
2421
|
-
seen.add(pk);
|
|
2422
|
-
rows.push(row);
|
|
2423
|
-
}
|
|
2424
|
-
}
|
|
2425
|
-
if (hint.remainingFilter === void 0) return rows;
|
|
2426
|
-
const { remainingFilter } = hint;
|
|
2427
|
-
return rows.filter((row) => evaluateFilter(remainingFilter, row));
|
|
2428
|
-
}
|
|
2429
|
-
/**
|
|
2430
|
-
* Combine all accumulated filter expressions with AND.
|
|
2431
|
-
*
|
|
2432
|
-
* Returns `undefined` when no filter has been installed so the driver can
|
|
2433
|
-
* skip building a row filter closure (a small perf and readability win on
|
|
2434
|
-
* `.all()` paths). Delegates to the shared {@link combineFilterExprs}.
|
|
2435
|
-
*/
|
|
2436
|
-
#combinedFilterExpr() {
|
|
2437
|
-
return combineFilterExprs(this.#state.filters);
|
|
2438
|
-
}
|
|
2439
|
-
async #applyIncludes(rows, groupingKey) {
|
|
2440
|
-
const relNames = Object.keys(this.#state.includes);
|
|
2441
|
-
if (relNames.length === 0) return rows;
|
|
2442
|
-
let result = rows;
|
|
2443
|
-
for (const relName of relNames) {
|
|
2444
|
-
const entry = this.#state.includes[relName];
|
|
2445
|
-
result = await loadRelation(relName, entry, result, this.#contract, this.#modelName, this.#executor, groupingKey);
|
|
2446
|
-
}
|
|
2447
|
-
return result;
|
|
2448
|
-
}
|
|
2449
|
-
/**
|
|
2450
|
-
* Apply a `.select()` projection (if any) to materialised rows. Keeps the
|
|
2451
|
-
* selected scalar fields plus every included relation key (which `include()`
|
|
2452
|
-
* attached during {@link #applyIncludes}); a no-op when nothing is selected.
|
|
2453
|
-
*/
|
|
2454
|
-
#projectRows(rows) {
|
|
2455
|
-
const selected = this.#state.selectedFields;
|
|
2456
|
-
if (selected === void 0) return rows;
|
|
2457
|
-
const keep = [...selected, ...Object.keys(this.#state.includes)];
|
|
2458
|
-
return rows.map((row) => {
|
|
2459
|
-
const out = {};
|
|
2460
|
-
for (const field of keep) if (field in row) out[field] = row[field];
|
|
2461
|
-
return out;
|
|
2462
|
-
});
|
|
2463
|
-
}
|
|
2464
|
-
#planMeta(groupingKey) {
|
|
2465
|
-
return {
|
|
2466
|
-
target: "idb",
|
|
2467
|
-
storageHash: this.#contract.storage.storageHash,
|
|
2468
|
-
lane: "idb-orm",
|
|
2469
|
-
annotations: { groupingKey }
|
|
2470
|
-
};
|
|
2471
|
-
}
|
|
2472
|
-
#clone(overrides) {
|
|
2473
|
-
return new IdbStoreAccessorImpl(this.#contract, this.#modelName, this.#executor, mergeAccessorState(this.#state, overrides), this.#newGroupingKey, this.#includeRefinementMode);
|
|
2474
|
-
}
|
|
2475
|
-
};
|
|
2476
|
-
//#endregion
|
|
2477
|
-
//#region src/core/idb-orm.ts
|
|
2478
|
-
/**
|
|
2479
|
-
* Create a typed IDB ORM client from a contract and executor.
|
|
2480
|
-
*
|
|
2481
|
-
* The client exposes one `IdbStoreAccessor` per entry in `contract.roots`.
|
|
2482
|
-
* Only roots-declared stores are accessible at the top level — other stores
|
|
2483
|
-
* can be reached via `.include()` on any accessor.
|
|
2484
|
-
*
|
|
2485
|
-
* @example
|
|
2486
|
-
* ```ts
|
|
2487
|
-
* import { idbOrm } from "@prisma-idb/client-idb/orm";
|
|
2488
|
-
* import { createIdbRuntime } from "@prisma-idb/runtime-idb/runtime";
|
|
2489
|
-
* import contract from "./prisma/idb-contract";
|
|
2490
|
-
*
|
|
2491
|
-
* const runtime = createIdbRuntime({ adapter, driver });
|
|
2492
|
-
* const db = idbOrm({ contract, executor: runtime });
|
|
2493
|
-
*
|
|
2494
|
-
* // Typed query builder:
|
|
2495
|
-
* const alice = await db.users.where({ email: "alice@example.com" }).first();
|
|
2496
|
-
* const postsWithAuthor = await db.posts.include("author").all();
|
|
2497
|
-
* ```
|
|
2498
|
-
*/
|
|
2499
|
-
function idbOrm(options) {
|
|
2500
|
-
const { contract, executor } = options;
|
|
2501
|
-
let _key = 0;
|
|
2502
|
-
const newGroupingKey = () => `idb-op-${++_key}`;
|
|
2503
|
-
const client = {};
|
|
2504
|
-
for (const [rootKey, ref] of Object.entries(contract.roots)) client[rootKey] = new IdbStoreAccessorImpl(contract, ref.model, executor, void 0, newGroupingKey);
|
|
2505
|
-
return client;
|
|
2506
|
-
}
|
|
2507
|
-
//#endregion
|
|
2508
|
-
export { createRelationMutator as a, withMutationScope as c, getStoreName as d, keyEquals as f, hasNestedMutationCallbacks as i, extractKeyFromRow as l, applyReferentialActionsForRow as n, isRelationMutationCallback as o, keyToken as p, collectDeleteStoreNames as r, isRelationMutationDescriptor as s, idbOrm as t, getKeyPath as u };
|
|
1194
|
+
export { keyToken as A, assertEnumValues as C, getRelation as D, getKeyPath as E, getStoreName as O, createMutationDefaultsCache as S, fieldValueToken as T, requireTransactionExecutor as _, collectScalarFkStoreNames as a, applyCreateDefaults as b, executeDeleteWithReferentialActions as c, executeScalarCreateAllWithFkValidation as d, executeScalarCreateWithFkValidation as f, hasScalarFkFields as g, hasNestedMutationCallbacks as h, collectOnUpdateEnforcementStoreNames as i, keyEquals$1 as k, executeNestedCreateMutation as l, hasEnforceableChildRelations as m, applyReferentialActionsForRowOnUpdate as n, executeBulkUpdateWithFkValidation as o, executeScalarUpdateWithFkValidation as p, collectDeleteStoreNames as r, executeDeleteAllWithReferentialActions as s, applyReferentialActionsForRow as t, executeNestedUpdateMutation as u, validateScalarFks as v, extractKeyFromRow as w, applyUpdateDefaults as x, withMutationScope as y };
|
|
2509
1195
|
|
|
2510
|
-
//# sourceMappingURL=
|
|
1196
|
+
//# sourceMappingURL=mutation-executor-SJqTuSbb.mjs.map
|