@hyper-fetch/db 0.0.0-stage → 10.2.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 +180 -2
- package/__tests__/e2e/db.e2e.spec.ts +269 -0
- package/__tests__/features/connection/connection.spec.ts +23 -0
- package/__tests__/features/model/live-query.model.spec.ts +320 -0
- package/__tests__/features/operators/operators.spec.ts +113 -0
- package/__tests__/features/runtime/runtime.spec.ts +185 -0
- package/__tests__/features/serializer/serializer.spec.ts +73 -0
- package/__tests__/features/store/store.spec.ts +147 -0
- package/__tests__/features/types/db.types.spec.ts +337 -0
- package/__tests__/integration/audit.spec.ts +639 -0
- package/__tests__/integration/competitors.spec.ts +393 -0
- package/__tests__/integration/convergence.model.spec.ts +162 -0
- package/__tests__/integration/edge-cases.spec.ts +465 -0
- package/__tests__/integration/errors.spec.ts +178 -0
- package/__tests__/integration/infinite.model.spec.ts +142 -0
- package/__tests__/integration/infinite.spec.ts +290 -0
- package/__tests__/integration/inspect.spec.ts +103 -0
- package/__tests__/integration/joins-many.spec.ts +177 -0
- package/__tests__/integration/joins.spec.ts +179 -0
- package/__tests__/integration/key-loaders.spec.ts +196 -0
- package/__tests__/integration/links.spec.ts +105 -0
- package/__tests__/integration/mutations.spec.ts +337 -0
- package/__tests__/integration/normalize.spec.ts +80 -0
- package/__tests__/integration/offline.spec.ts +479 -0
- package/__tests__/integration/queries.spec.ts +513 -0
- package/__tests__/integration/races.spec.ts +127 -0
- package/__tests__/integration/server-operators.spec.ts +123 -0
- package/__tests__/integration/ssr.spec.ts +111 -0
- package/__tests__/integration/syncs.spec.ts +564 -0
- package/__tests__/integration/transactions.spec.ts +344 -0
- package/__tests__/integration/windows.spec.ts +192 -0
- package/__tests__/tsconfig.json +11 -0
- package/__tests__/type-budget/budget.fixture.ts +2476 -0
- package/__tests__/type-budget/tsconfig.json +4 -0
- package/__tests__/utils/fixtures.ts +225 -0
- package/__tests__/utils/random.ts +19 -0
- package/__tests__/vitest.setup.ts +11 -0
- package/dist/collection/collection.d.ts +111 -0
- package/dist/collection/collection.d.ts.map +1 -0
- package/dist/collection/collection.types.d.ts +316 -0
- package/dist/collection/collection.types.d.ts.map +1 -0
- package/dist/collection/resource.types.d.ts +77 -0
- package/dist/collection/resource.types.d.ts.map +1 -0
- package/dist/db/collection.runtime.d.ts +98 -0
- package/dist/db/collection.runtime.d.ts.map +1 -0
- package/dist/db/db.d.ts +154 -0
- package/dist/db/db.d.ts.map +1 -0
- package/dist/db/db.runtime.d.ts +114 -0
- package/dist/db/db.runtime.d.ts.map +1 -0
- package/dist/db/db.types.d.ts +162 -0
- package/dist/db/db.types.d.ts.map +1 -0
- package/dist/graphql/connection.d.ts +25 -0
- package/dist/graphql/connection.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +4220 -0
- package/dist/index.mjs.map +1 -0
- package/dist/mutation/mutation.d.ts +136 -0
- package/dist/mutation/mutation.d.ts.map +1 -0
- package/dist/mutation/mutation.errors.d.ts +6 -0
- package/dist/mutation/mutation.errors.d.ts.map +1 -0
- package/dist/mutation/mutation.utils.d.ts +35 -0
- package/dist/mutation/mutation.utils.d.ts.map +1 -0
- package/dist/operators/operators.d.ts +33 -0
- package/dist/operators/operators.d.ts.map +1 -0
- package/dist/operators/operators.types.d.ts +68 -0
- package/dist/operators/operators.types.d.ts.map +1 -0
- package/dist/operators/operators.utils.d.ts +19 -0
- package/dist/operators/operators.utils.d.ts.map +1 -0
- package/dist/persistence/persistence.d.ts +42 -0
- package/dist/persistence/persistence.d.ts.map +1 -0
- package/dist/persistence/serializer.d.ts +23 -0
- package/dist/persistence/serializer.d.ts.map +1 -0
- package/dist/persistence/snapshot.d.ts +29 -0
- package/dist/persistence/snapshot.d.ts.map +1 -0
- package/dist/persistence/tabs.d.ts +53 -0
- package/dist/persistence/tabs.d.ts.map +1 -0
- package/dist/query/infinite-query.d.ts +59 -0
- package/dist/query/infinite-query.d.ts.map +1 -0
- package/dist/query/live-query.d.ts +85 -0
- package/dist/query/live-query.d.ts.map +1 -0
- package/dist/query/planner.d.ts +57 -0
- package/dist/query/planner.d.ts.map +1 -0
- package/dist/query/query.d.ts +155 -0
- package/dist/query/query.d.ts.map +1 -0
- package/dist/query/query.types.d.ts +71 -0
- package/dist/query/query.types.d.ts.map +1 -0
- package/dist/schema/schema.types.d.ts +33 -0
- package/dist/schema/schema.types.d.ts.map +1 -0
- package/dist/store/store.d.ts +76 -0
- package/dist/store/store.d.ts.map +1 -0
- package/dist/store/store.types.d.ts +27 -0
- package/dist/store/store.types.d.ts.map +1 -0
- package/dist/subset/base-subset.d.ts +66 -0
- package/dist/subset/base-subset.d.ts.map +1 -0
- package/dist/subset/key-subset.d.ts +23 -0
- package/dist/subset/key-subset.d.ts.map +1 -0
- package/dist/subset/list-subset.d.ts +63 -0
- package/dist/subset/list-subset.d.ts.map +1 -0
- package/dist/sync/sync.d.ts +42 -0
- package/dist/sync/sync.d.ts.map +1 -0
- package/dist/utils/request.utils.d.ts +11 -0
- package/dist/utils/request.utils.d.ts.map +1 -0
- package/package.json +71 -4
- package/project.json +4 -0
- package/scripts/docs-typescript.mjs +24 -0
- package/scripts/type-budget.mjs +37 -0
- package/src/collection/collection.ts +330 -0
- package/src/collection/collection.types.ts +383 -0
- package/src/collection/resource.types.ts +114 -0
- package/src/db/collection.runtime.ts +572 -0
- package/src/db/db.runtime.ts +537 -0
- package/src/db/db.ts +451 -0
- package/src/db/db.types.ts +157 -0
- package/src/graphql/connection.ts +23 -0
- package/src/index.ts +16 -0
- package/src/mutation/mutation.errors.ts +7 -0
- package/src/mutation/mutation.ts +776 -0
- package/src/mutation/mutation.utils.ts +58 -0
- package/src/operators/operators.ts +90 -0
- package/src/operators/operators.types.ts +67 -0
- package/src/operators/operators.utils.ts +169 -0
- package/src/persistence/persistence.ts +168 -0
- package/src/persistence/serializer.ts +123 -0
- package/src/persistence/snapshot.ts +76 -0
- package/src/persistence/tabs.ts +86 -0
- package/src/query/infinite-query.ts +206 -0
- package/src/query/live-query.ts +552 -0
- package/src/query/planner.ts +199 -0
- package/src/query/query.ts +319 -0
- package/src/query/query.types.ts +90 -0
- package/src/schema/schema.types.ts +29 -0
- package/src/store/store.ts +300 -0
- package/src/store/store.types.ts +17 -0
- package/src/subset/base-subset.ts +169 -0
- package/src/subset/key-subset.ts +44 -0
- package/src/subset/list-subset.ts +328 -0
- package/src/sync/sync.ts +99 -0
- package/src/utils/request.utils.ts +67 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +71 -0
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import type { RowKey } from "../collection/collection.types";
|
|
2
|
+
import type { CollectionRuntime } from "../db/collection.runtime";
|
|
3
|
+
import { evaluate } from "../operators/operators.utils";
|
|
4
|
+
import type { Row } from "../store/store.types";
|
|
5
|
+
import type { SubsetObserver } from "../subset/base-subset";
|
|
6
|
+
import type { KeySubset } from "../subset/key-subset";
|
|
7
|
+
import type { ListSubset } from "../subset/list-subset";
|
|
8
|
+
import type { QueryPlan } from "./planner";
|
|
9
|
+
import { planQuery } from "./planner";
|
|
10
|
+
import type { QueryDefinition, QueryExplanation, QueryState } from "./query.types";
|
|
11
|
+
|
|
12
|
+
const isSameState = (left: QueryState<unknown>, right: QueryState<unknown>) => {
|
|
13
|
+
return (
|
|
14
|
+
left.data === right.data &&
|
|
15
|
+
left.status === right.status &&
|
|
16
|
+
left.error === right.error &&
|
|
17
|
+
left.stale === right.stale &&
|
|
18
|
+
left.isFetching === right.isFetching &&
|
|
19
|
+
left.hasNextPage === right.hasNextPage
|
|
20
|
+
);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type JoinDefinition = NonNullable<QueryDefinition["joins"]>[number];
|
|
24
|
+
|
|
25
|
+
const EMPTY_ROWS: Row[] = [];
|
|
26
|
+
|
|
27
|
+
/** Joined values are the same row, or arrays of the same rows */
|
|
28
|
+
const sameJoined = (left: unknown, right: unknown) => {
|
|
29
|
+
if (Array.isArray(left) && Array.isArray(right)) {
|
|
30
|
+
return left.length === right.length && left.every((item, index) => item === right[index]);
|
|
31
|
+
}
|
|
32
|
+
return left === right;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const sameItems = (left: unknown, right: unknown[]) => {
|
|
36
|
+
return (
|
|
37
|
+
Array.isArray(left) && left.length === right.length && left.every((item, index) => Object.is(item, right[index]))
|
|
38
|
+
);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The running form of a query: it attaches to the loaded subset that serves it, keeps its result current as rows
|
|
43
|
+
* change and tells its subscribers. Queries with the same definition share one live query.
|
|
44
|
+
*/
|
|
45
|
+
export class LiveQuery implements SubsetObserver {
|
|
46
|
+
readonly plan: QueryPlan;
|
|
47
|
+
private listeners = new Set<() => void>();
|
|
48
|
+
private source: ListSubset | undefined;
|
|
49
|
+
private keySubset: KeySubset | undefined;
|
|
50
|
+
private answeredLocally = false;
|
|
51
|
+
/** The subset a query that nothing subscribes to reads, see `getSource` */
|
|
52
|
+
private peeked: ListSubset | undefined;
|
|
53
|
+
private sorted: RowKey[] = [];
|
|
54
|
+
private members = new Set<RowKey>();
|
|
55
|
+
private selections = new Map<RowKey, { row: Row; joined: unknown[]; value: unknown }>();
|
|
56
|
+
/** Key subsets that load the joined rows, by `collection:key` */
|
|
57
|
+
private joinSubsets = new Map<string, KeySubset>();
|
|
58
|
+
/** Live queries that load the rows of one-to-many joins, by join name */
|
|
59
|
+
private joinQueries = new Map<string, { key: string; unsubscribe: () => void }>();
|
|
60
|
+
/** The rows of each one-to-many join by the value of its `on` field, built when first read */
|
|
61
|
+
private childIndex = new Map<string, Map<unknown, Row[]>>();
|
|
62
|
+
private state: QueryState<unknown> = {
|
|
63
|
+
data: undefined,
|
|
64
|
+
status: "loading",
|
|
65
|
+
error: null,
|
|
66
|
+
stale: false,
|
|
67
|
+
isFetching: false,
|
|
68
|
+
hasNextPage: false,
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
constructor(
|
|
72
|
+
readonly collection: CollectionRuntime,
|
|
73
|
+
readonly definition: QueryDefinition,
|
|
74
|
+
readonly key: string,
|
|
75
|
+
) {
|
|
76
|
+
this.plan = planQuery({
|
|
77
|
+
collectionName: collection.name,
|
|
78
|
+
config: collection.config,
|
|
79
|
+
definition,
|
|
80
|
+
notation: collection.db.notation,
|
|
81
|
+
});
|
|
82
|
+
this.state = this.computeState();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The current state. A query nobody subscribes to is computed from the rows the db holds right now. */
|
|
86
|
+
getState = () => {
|
|
87
|
+
if (!this.isActive()) {
|
|
88
|
+
this.rebuild();
|
|
89
|
+
}
|
|
90
|
+
return this.state;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
subscribe = (listener: () => void) => {
|
|
94
|
+
this.listeners.add(listener);
|
|
95
|
+
if (this.listeners.size === 1) {
|
|
96
|
+
this.attach();
|
|
97
|
+
}
|
|
98
|
+
return () => {
|
|
99
|
+
this.listeners.delete(listener);
|
|
100
|
+
if (this.listeners.size === 0) {
|
|
101
|
+
this.detach();
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** Whether anything subscribes to the query */
|
|
107
|
+
isActive = () => this.listeners.size > 0;
|
|
108
|
+
|
|
109
|
+
/** How many listeners subscribe to the query */
|
|
110
|
+
get subscriberCount() {
|
|
111
|
+
return this.listeners.size;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
refetch = (): Promise<void> => {
|
|
115
|
+
return (this.source ?? this.keySubset)?.load() ?? Promise.resolve();
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** How the query's loader pages: by cursor, by a growing `limit`, or not at all */
|
|
119
|
+
getPaging = (): "cursor" | "limit" | "none" => {
|
|
120
|
+
if (this.plan.kind !== "list") {
|
|
121
|
+
return "none";
|
|
122
|
+
}
|
|
123
|
+
const loader = this.collection.config.loaders[this.plan.loaderIndex];
|
|
124
|
+
if (loader.cursor) {
|
|
125
|
+
return "cursor";
|
|
126
|
+
}
|
|
127
|
+
return loader.limit ? "limit" : "none";
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
fetchNextPage = (): Promise<void> => {
|
|
131
|
+
return this.source?.loadNext() ?? Promise.resolve();
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/** Refetches the query's subset when it is stale, after focus or reconnect */
|
|
135
|
+
revalidate = () => {
|
|
136
|
+
(this.source ?? this.keySubset)?.revalidate();
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
explain = (): QueryExplanation => {
|
|
140
|
+
const { plan } = this;
|
|
141
|
+
const subset = this.source ?? this.keySubset;
|
|
142
|
+
const syncs = (subset?.subscriptions ?? []).map((subscription) => ({
|
|
143
|
+
type: subscription.sync.type,
|
|
144
|
+
topic: subscription.listener.topic,
|
|
145
|
+
}));
|
|
146
|
+
if (plan.kind === "error") {
|
|
147
|
+
return { kind: "error", sent: [], local: [], answeredLocally: false, syncs, error: plan.error };
|
|
148
|
+
}
|
|
149
|
+
if (plan.kind === "local") {
|
|
150
|
+
return {
|
|
151
|
+
kind: "local",
|
|
152
|
+
sent: [],
|
|
153
|
+
local: this.definition.where ? [this.definition.where] : [],
|
|
154
|
+
answeredLocally: true,
|
|
155
|
+
syncs,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
if (plan.kind === "one") {
|
|
159
|
+
return {
|
|
160
|
+
kind: "one",
|
|
161
|
+
loader: plan.loaderIndex,
|
|
162
|
+
sent: [],
|
|
163
|
+
local: [],
|
|
164
|
+
answeredLocally: plan.loaderIndex === undefined,
|
|
165
|
+
syncs,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const container = this.source ? undefined : this.collection.findContainingSubset(plan);
|
|
169
|
+
const answeredLocally = this.source ? this.answeredLocally : Boolean(container && container.id !== plan.subsetId);
|
|
170
|
+
return { kind: "list", loader: plan.loaderIndex, sent: plan.sent, local: plan.local, answeredLocally, syncs };
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/** Rows changed: update membership and order of just those rows */
|
|
174
|
+
onRowsChanged = (keys: Iterable<RowKey>) => {
|
|
175
|
+
if (this.plan.kind === "error" || !this.isActive()) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
// Most writes touch rows a query does not show, so those queries do no further work
|
|
179
|
+
const touched = [...keys].filter((key) => this.members.has(key) || this.isMember(key));
|
|
180
|
+
if (touched.length === 0) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const compare = this.getComparator();
|
|
184
|
+
touched.forEach((key) => {
|
|
185
|
+
if (this.members.has(key)) {
|
|
186
|
+
this.sorted.splice(this.sorted.indexOf(key), 1);
|
|
187
|
+
this.members.delete(key);
|
|
188
|
+
}
|
|
189
|
+
if (this.isMember(key)) {
|
|
190
|
+
this.insertSorted(key, compare);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
this.syncJoins();
|
|
194
|
+
this.emit();
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
/** The subset's rows or status changed */
|
|
198
|
+
onSubsetChange = () => {
|
|
199
|
+
this.collection.db.markQueryDirty(this);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/** Recomputes the whole result */
|
|
203
|
+
rebuild = () => {
|
|
204
|
+
this.childIndex.clear();
|
|
205
|
+
this.peeked = this.peekSource();
|
|
206
|
+
// A list query without a subset to read shows nothing yet
|
|
207
|
+
const readable = this.plan.kind !== "list" || this.getSource() !== undefined;
|
|
208
|
+
if (this.plan.kind !== "error") {
|
|
209
|
+
const compare = this.getComparator();
|
|
210
|
+
this.members = new Set(readable ? this.collection.store.keys().filter((key) => this.isMember(key)) : []);
|
|
211
|
+
this.sorted = [...this.members].toSorted(compare);
|
|
212
|
+
}
|
|
213
|
+
if (this.isActive()) {
|
|
214
|
+
this.syncJoins();
|
|
215
|
+
}
|
|
216
|
+
this.emit();
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
private attach = () => {
|
|
220
|
+
const { plan, collection } = this;
|
|
221
|
+
if (plan.kind === "one") {
|
|
222
|
+
if (plan.loaderIndex !== undefined) {
|
|
223
|
+
this.keySubset = collection.getKeySubset(collection.resolveKey(plan.key), plan.loaderIndex);
|
|
224
|
+
this.keySubset.attach(this);
|
|
225
|
+
if (!collection.store.get(collection.resolveKey(plan.key)) || !this.keySubset.isFresh()) {
|
|
226
|
+
this.keySubset.revalidate();
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
} else if (plan.kind === "list") {
|
|
230
|
+
const container = collection.findContainingSubset(plan);
|
|
231
|
+
this.answeredLocally = Boolean(container && container.id !== plan.subsetId);
|
|
232
|
+
this.source = this.answeredLocally ? container : collection.getListSubset(plan, this.definition);
|
|
233
|
+
this.source!.attach(this);
|
|
234
|
+
if (!this.answeredLocally) {
|
|
235
|
+
this.source!.revalidate();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
this.rebuild();
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
private detach = () => {
|
|
242
|
+
this.collection.db.releaseLater(this);
|
|
243
|
+
this.source?.detach(this);
|
|
244
|
+
this.keySubset?.detach(this);
|
|
245
|
+
this.joinSubsets.forEach((subset) => subset.detach(this));
|
|
246
|
+
this.joinSubsets.clear();
|
|
247
|
+
this.joinQueries.forEach((entry) => entry.unsubscribe());
|
|
248
|
+
this.joinQueries.clear();
|
|
249
|
+
this.source = undefined;
|
|
250
|
+
this.keySubset = undefined;
|
|
251
|
+
this.answeredLocally = false;
|
|
252
|
+
this.members.clear();
|
|
253
|
+
this.sorted = [];
|
|
254
|
+
this.selections.clear();
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
private getComparator = () => this.collection.createComparator(this.definition.orderBy, this.getSource());
|
|
258
|
+
|
|
259
|
+
private insertSorted = (key: RowKey, compare: (left: RowKey, right: RowKey) => number) => {
|
|
260
|
+
let low = 0;
|
|
261
|
+
let high = this.sorted.length;
|
|
262
|
+
while (low < high) {
|
|
263
|
+
const middle = (low + high) >>> 1;
|
|
264
|
+
if (compare(this.sorted[middle], key) <= 0) {
|
|
265
|
+
low = middle + 1;
|
|
266
|
+
} else {
|
|
267
|
+
high = middle;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
this.sorted.splice(low, 0, key);
|
|
271
|
+
this.members.add(key);
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
private isMember = (key: RowKey): boolean => {
|
|
275
|
+
const { plan, collection, definition } = this;
|
|
276
|
+
const row = collection.store.get(key);
|
|
277
|
+
if (!row) {
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
if (plan.kind === "one") {
|
|
281
|
+
return key === collection.resolveKey(plan.key);
|
|
282
|
+
}
|
|
283
|
+
if (definition.where && !evaluate(definition.where, row)) {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
if (plan.kind === "local") {
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
const source = this.getSource()!;
|
|
290
|
+
const plannedLoader = collection.config.loaders[(plan as Extract<QueryPlan, { kind: "list" }>).loaderIndex];
|
|
291
|
+
const fixed = plannedLoader.fixed ?? {};
|
|
292
|
+
if (!Object.keys(fixed).every((field) => evaluate({ op: "eq", field, value: fixed[field] }, row))) {
|
|
293
|
+
return false;
|
|
294
|
+
}
|
|
295
|
+
// Pages and server-only operators hold exactly what the backend returned
|
|
296
|
+
if (source.ownsOnly) {
|
|
297
|
+
return source.holds(key);
|
|
298
|
+
}
|
|
299
|
+
return !source.excluded.has(key);
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
/** The joined value of a row: the row with that key, or every row whose `on` field holds the value */
|
|
303
|
+
private resolveJoin = (join: JoinDefinition, row: Row) => {
|
|
304
|
+
const value = row[join.field];
|
|
305
|
+
if (!join.on) {
|
|
306
|
+
return this.collection.db.collections.get(join.collection)!.store.get(value as RowKey);
|
|
307
|
+
}
|
|
308
|
+
return this.getChildren(join).get(value) ?? EMPTY_ROWS;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
private getChildren = (join: JoinDefinition) => {
|
|
312
|
+
const existing = this.childIndex.get(join.name);
|
|
313
|
+
if (existing) {
|
|
314
|
+
return existing;
|
|
315
|
+
}
|
|
316
|
+
const { store } = this.collection.db.collections.get(join.collection)!;
|
|
317
|
+
const index = new Map<unknown, Row[]>();
|
|
318
|
+
store.keys().forEach((childKey) => {
|
|
319
|
+
const child = store.get(childKey)!;
|
|
320
|
+
const value = child[join.on!];
|
|
321
|
+
index.set(value, [...(index.get(value) ?? []), child]);
|
|
322
|
+
});
|
|
323
|
+
this.childIndex.set(join.name, index);
|
|
324
|
+
return index;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
private hasInnerJoins = () => (this.definition.joins ?? []).some((join) => join.type === "inner");
|
|
328
|
+
|
|
329
|
+
/** Whether a row has every row its inner joins need */
|
|
330
|
+
private passesInnerJoins = (key: RowKey) => {
|
|
331
|
+
const row = this.collection.store.get(key)!;
|
|
332
|
+
return (this.definition.joins ?? []).every((join) => {
|
|
333
|
+
if (join.type !== "inner") {
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
const joined = this.resolveJoin(join, row);
|
|
337
|
+
return Array.isArray(joined) ? joined.length > 0 : joined !== undefined;
|
|
338
|
+
});
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
private select = (key: RowKey) => {
|
|
342
|
+
const row = this.collection.store.get(key)!;
|
|
343
|
+
const joins = this.definition.joins ?? [];
|
|
344
|
+
const joined = joins.map((join) => this.resolveJoin(join, row));
|
|
345
|
+
const cached = this.selections.get(key);
|
|
346
|
+
const sameJoins = Boolean(cached?.joined.every((item, index) => sameJoined(item, joined[index])));
|
|
347
|
+
if (cached && cached.row === row && sameJoins) {
|
|
348
|
+
return cached.value;
|
|
349
|
+
}
|
|
350
|
+
const { select } = this.definition;
|
|
351
|
+
// A change to a field the query does not select keeps the result, so components that read it do not render
|
|
352
|
+
if (
|
|
353
|
+
cached &&
|
|
354
|
+
select &&
|
|
355
|
+
sameJoins &&
|
|
356
|
+
Object.values(select).every((field) => Object.is(cached.row[field], row[field]))
|
|
357
|
+
) {
|
|
358
|
+
this.selections.set(key, { ...cached, row });
|
|
359
|
+
return cached.value;
|
|
360
|
+
}
|
|
361
|
+
const selected = select
|
|
362
|
+
? Object.fromEntries(Object.entries(select).map(([output, field]) => [output, row[field]]))
|
|
363
|
+
: row;
|
|
364
|
+
const value =
|
|
365
|
+
joins.length > 0
|
|
366
|
+
? { ...selected, ...Object.fromEntries(joins.map(({ name }, index) => [name, joined[index]])) }
|
|
367
|
+
: selected;
|
|
368
|
+
this.selections.set(key, { row, joined, value });
|
|
369
|
+
return value;
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
/** Whether the query reads rows of a collection, its own or a joined one */
|
|
373
|
+
dependsOn = (collection: CollectionRuntime) => {
|
|
374
|
+
return (this.definition.joins ?? []).some((join) => join.collection === collection.name);
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
/** Rows of a joined collection changed: results that point at them select again */
|
|
378
|
+
onJoinedRowsChanged = () => {
|
|
379
|
+
this.childIndex.clear();
|
|
380
|
+
this.syncJoins();
|
|
381
|
+
this.emit();
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
/** Attaches the key subsets that load the joined rows of the current result and releases the others */
|
|
385
|
+
private syncJoins = () => {
|
|
386
|
+
const needed = new Map<string, { collection: CollectionRuntime; key: RowKey }>();
|
|
387
|
+
// Local queries never load, so they read the joined rows the db holds
|
|
388
|
+
const joins = this.definition.local ? [] : (this.definition.joins ?? []);
|
|
389
|
+
this.syncChildQueries(joins.filter((join) => join.on));
|
|
390
|
+
joins
|
|
391
|
+
.filter((join) => !join.on)
|
|
392
|
+
.forEach(({ collection: name, field }) => {
|
|
393
|
+
const collection = this.collection.db.collections.get(name)!;
|
|
394
|
+
this.members.forEach((member) => {
|
|
395
|
+
const key = this.collection.store.get(member)![field] as RowKey | null | undefined;
|
|
396
|
+
if (key !== null && key !== undefined) {
|
|
397
|
+
needed.set(`${name}:${String(key)}`, { collection, key });
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
});
|
|
401
|
+
this.joinSubsets.forEach((subset, id) => {
|
|
402
|
+
if (!needed.has(id)) {
|
|
403
|
+
subset.detach(this);
|
|
404
|
+
this.joinSubsets.delete(id);
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
needed.forEach(({ collection, key }, id) => {
|
|
408
|
+
const loaderIndex = collection.config.loaders.findIndex((loader) => loader.kind !== "list");
|
|
409
|
+
if (this.joinSubsets.has(id) || loaderIndex === -1) {
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
const subset = collection.getKeySubset(key, loaderIndex);
|
|
413
|
+
subset.attach(this);
|
|
414
|
+
subset.revalidate();
|
|
415
|
+
this.joinSubsets.set(id, subset);
|
|
416
|
+
});
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Loads the rows of one-to-many joins: one query of the joined collection for the values of the whole result, when
|
|
421
|
+
* one of its list loaders can send `inArray` on the joined field. Otherwise the join reads the rows the db holds.
|
|
422
|
+
*/
|
|
423
|
+
private syncChildQueries = (joins: JoinDefinition[]) => {
|
|
424
|
+
// A query's joins never change, so `detach` releases these queries
|
|
425
|
+
joins.forEach((join) => {
|
|
426
|
+
const values = [
|
|
427
|
+
...new Set(
|
|
428
|
+
[...this.members]
|
|
429
|
+
.map((member) => this.collection.store.get(member)![join.field])
|
|
430
|
+
.filter((value) => value !== null && value !== undefined),
|
|
431
|
+
),
|
|
432
|
+
].toSorted();
|
|
433
|
+
const definition: QueryDefinition = {
|
|
434
|
+
collection: join.collection,
|
|
435
|
+
where: { op: "inArray", field: join.on!, value: values },
|
|
436
|
+
orderBy: [],
|
|
437
|
+
local: false,
|
|
438
|
+
};
|
|
439
|
+
const query = this.collection.db.getLiveQuery(definition);
|
|
440
|
+
const current = this.joinQueries.get(join.name);
|
|
441
|
+
if (current?.key === query.key) {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
current?.unsubscribe();
|
|
445
|
+
this.joinQueries.delete(join.name);
|
|
446
|
+
const sendsValues =
|
|
447
|
+
query.plan.kind === "list" && query.plan.sent.some((node) => node.op === "inArray" && node.field === join.on);
|
|
448
|
+
if (values.length > 0 && sendsValues) {
|
|
449
|
+
this.joinQueries.set(join.name, { key: query.key, unsubscribe: query.subscribe(() => {}) });
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
private buildList = () => {
|
|
455
|
+
const { plan, definition } = this;
|
|
456
|
+
const paginated = plan.kind === "list" && plan.paginated;
|
|
457
|
+
const included = this.hasInnerJoins() ? this.sorted.filter(this.passesInnerJoins) : this.sorted;
|
|
458
|
+
const keys = definition.limit !== undefined && !paginated ? included.slice(0, definition.limit) : included;
|
|
459
|
+
const items = keys.map((key) => this.select(key));
|
|
460
|
+
[...this.selections.keys()].forEach((key) => {
|
|
461
|
+
if (!this.members.has(key)) {
|
|
462
|
+
this.selections.delete(key);
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
return sameItems(this.state.data, items) ? this.state.data : items;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
private computeState = (): QueryState<unknown> => {
|
|
469
|
+
const { plan, collection } = this;
|
|
470
|
+
const { db } = collection;
|
|
471
|
+
const base = { error: null as unknown, stale: false, isFetching: false, hasNextPage: false };
|
|
472
|
+
|
|
473
|
+
if (plan.kind === "error") {
|
|
474
|
+
return { ...base, data: undefined, status: "error", error: plan.error };
|
|
475
|
+
}
|
|
476
|
+
// While persisted rows are restored, a query has nothing reliable to show, unless a server rendered it: hydrated
|
|
477
|
+
// subsets are loaded, so the first render matches the server's
|
|
478
|
+
if (!db.isReady && !this.getSource()?.hasLoaded && !(plan.kind === "one" && this.members.size > 0)) {
|
|
479
|
+
return { ...base, data: undefined, status: "loading" };
|
|
480
|
+
}
|
|
481
|
+
if (plan.kind === "local") {
|
|
482
|
+
return { ...base, data: this.buildList(), status: "ready" };
|
|
483
|
+
}
|
|
484
|
+
if (plan.kind === "one") {
|
|
485
|
+
const subset = this.keySubset;
|
|
486
|
+
const key = collection.resolveKey(plan.key);
|
|
487
|
+
const row = this.members.has(key) && this.passesInnerJoins(key) ? this.select(key) : undefined;
|
|
488
|
+
let status: QueryState<unknown>["status"] = "loading";
|
|
489
|
+
if (row || !subset || subset.hasLoaded) {
|
|
490
|
+
status = "ready";
|
|
491
|
+
} else if (subset.error) {
|
|
492
|
+
status = "error";
|
|
493
|
+
}
|
|
494
|
+
return {
|
|
495
|
+
data: row,
|
|
496
|
+
status,
|
|
497
|
+
error: subset?.error ?? null,
|
|
498
|
+
stale: subset ? !subset.isFresh() : false,
|
|
499
|
+
isFetching: subset?.isLoading ?? false,
|
|
500
|
+
hasNextPage: false,
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
const source = this.getSource();
|
|
504
|
+
if (!source) {
|
|
505
|
+
return { ...base, data: undefined, status: "loading" };
|
|
506
|
+
}
|
|
507
|
+
let status: QueryState<unknown>["status"] = "loading";
|
|
508
|
+
if (source.hasLoaded) {
|
|
509
|
+
status = "ready";
|
|
510
|
+
} else if (source.error) {
|
|
511
|
+
status = "error";
|
|
512
|
+
}
|
|
513
|
+
return {
|
|
514
|
+
data: status === "ready" ? this.buildList() : undefined,
|
|
515
|
+
status,
|
|
516
|
+
error: source.error,
|
|
517
|
+
stale: !source.isFresh(),
|
|
518
|
+
isFetching: source.isLoading,
|
|
519
|
+
hasNextPage: plan.paginated && source.hasMore,
|
|
520
|
+
};
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* The subset that serves a list query. Before anything subscribes, such as on a component's first render, it is the
|
|
525
|
+
* loaded subset that would serve it, read without attaching to it or loading it.
|
|
526
|
+
*/
|
|
527
|
+
private getSource = () => this.source ?? this.peeked;
|
|
528
|
+
|
|
529
|
+
private peekSource = () => {
|
|
530
|
+
const { collection, plan } = this;
|
|
531
|
+
if (this.source || plan.kind !== "list") {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
return collection.findContainingSubset(plan) ?? collection.listSubsets.get(plan.subsetId);
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
private emit = () => {
|
|
538
|
+
const next = this.computeState();
|
|
539
|
+
if (isSameState(this.state, next)) {
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
this.state = next;
|
|
543
|
+
this.listeners.forEach((listener) => {
|
|
544
|
+
// A listener that throws, such as a broken component, is reported and never stops the others
|
|
545
|
+
try {
|
|
546
|
+
listener();
|
|
547
|
+
} catch (error) {
|
|
548
|
+
this.collection.db.emitError({ type: "subscriber", error, collection: this.collection.name });
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
};
|
|
552
|
+
}
|