@powersync/react 0.0.0-dev-20260827080125 → 0.0.0-dev-20261020125654
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 +15 -0
- package/lib/QueryStore.d.ts +3 -3
- package/lib/QueryStore.js.map +1 -1
- package/lib/hooks/PowerSyncContext.d.ts +4 -2
- package/lib/hooks/PowerSyncContext.js +7 -1
- package/lib/hooks/PowerSyncContext.js.map +1 -1
- package/lib/hooks/streams.d.ts +4 -3
- package/lib/hooks/streams.js +11 -10
- package/lib/hooks/streams.js.map +1 -1
- package/lib/hooks/suspense/suspense-utils.js +2 -2
- package/lib/hooks/suspense/suspense-utils.js.map +1 -1
- package/lib/hooks/suspense/useSingleSuspenseQuery.js +3 -6
- package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +1 -1
- package/lib/hooks/suspense/useWatchedSuspenseQuery.js +1 -4
- package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +1 -1
- package/lib/hooks/useStatus.d.ts +7 -1
- package/lib/hooks/useStatus.js +11 -6
- package/lib/hooks/useStatus.js.map +1 -1
- package/lib/hooks/watched/QueryRunner.d.ts +79 -0
- package/lib/hooks/watched/QueryRunner.js +340 -0
- package/lib/hooks/watched/QueryRunner.js.map +1 -0
- package/lib/hooks/watched/useQuery.js +14 -40
- package/lib/hooks/watched/useQuery.js.map +1 -1
- package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +1 -1
- package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -1
- package/lib/hooks/watched/watch-types.d.ts +22 -3
- package/lib/hooks/watched/watch-utils.d.ts +3 -15
- package/lib/hooks/watched/watch-utils.js +5 -31
- package/lib/hooks/watched/watch-utils.js.map +1 -1
- package/lib/index.d.ts +2 -2
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/package.json +11 -9
- package/src/QueryStore.ts +4 -4
- package/src/hooks/PowerSyncContext.ts +9 -3
- package/src/hooks/streams.ts +14 -20
- package/src/hooks/suspense/suspense-utils.ts +4 -4
- package/src/hooks/suspense/useSingleSuspenseQuery.ts +4 -7
- package/src/hooks/suspense/useWatchedSuspenseQuery.ts +1 -4
- package/src/hooks/useStatus.ts +21 -7
- package/src/hooks/watched/QueryRunner.ts +455 -0
- package/src/hooks/watched/useQuery.ts +15 -41
- package/src/hooks/watched/useWatchedQuerySubscription.ts +2 -2
- package/src/hooks/watched/watch-types.ts +23 -3
- package/src/hooks/watched/watch-utils.ts +8 -54
- package/src/index.ts +2 -2
- package/lib/hooks/watched/useSingleQuery.d.ts +0 -6
- package/lib/hooks/watched/useSingleQuery.js +0 -59
- package/lib/hooks/watched/useSingleQuery.js.map +0 -1
- package/lib/hooks/watched/useWatchedQuery.d.ts +0 -13
- package/lib/hooks/watched/useWatchedQuery.js +0 -81
- package/lib/hooks/watched/useWatchedQuery.js.map +0 -1
- package/src/hooks/watched/useSingleQuery.ts +0 -67
- package/src/hooks/watched/useWatchedQuery.ts +0 -93
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BaseListener,
|
|
3
|
+
BaseObserver,
|
|
4
|
+
CommonPowerSyncDatabase,
|
|
5
|
+
DifferentialWatchedQuery,
|
|
6
|
+
DifferentialWatchedQueryComparator,
|
|
7
|
+
WatchedQueryState
|
|
8
|
+
} from '@powersync/common';
|
|
9
|
+
import {
|
|
10
|
+
AdditionalOptions,
|
|
11
|
+
DifferentialHookOptions,
|
|
12
|
+
FetchReason,
|
|
13
|
+
QueryResult,
|
|
14
|
+
ReadonlyQueryResult
|
|
15
|
+
} from './watch-types.js';
|
|
16
|
+
import { WatchCompatibleQueryWithParams } from './watch-utils.js';
|
|
17
|
+
|
|
18
|
+
// We want to generate readonly results, but declare mutable results when useQuery is used without differential hooks
|
|
19
|
+
// for backwards compatibility.
|
|
20
|
+
type Result<RowType> = QueryResult<RowType> | ReadonlyQueryResult<RowType>;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The configured state a {@link QueryRunner} is in.
|
|
24
|
+
*
|
|
25
|
+
* Creating these instances has no side effects (in particular, doesn't start database queries) and can be done in
|
|
26
|
+
* renders.
|
|
27
|
+
*/
|
|
28
|
+
export type RunnerConfig<RowType> =
|
|
29
|
+
// No PowerSync database in context, reported as error.
|
|
30
|
+
| { kind: 'missing-db' }
|
|
31
|
+
// Query included sync streams that have not synced yet
|
|
32
|
+
| { kind: 'waiting-for-streams' }
|
|
33
|
+
| { kind: 'compile-error'; error: Error }
|
|
34
|
+
| QueryConfig<RowType>;
|
|
35
|
+
|
|
36
|
+
interface QueryConfig<RowType> {
|
|
37
|
+
kind: 'query';
|
|
38
|
+
db: CommonPowerSyncDatabase;
|
|
39
|
+
query: WatchCompatibleQueryWithParams<RowType[]>;
|
|
40
|
+
sql: string;
|
|
41
|
+
parameters: ReadonlyArray<any>;
|
|
42
|
+
stringifiedParams: string; // For efficient comparisons
|
|
43
|
+
runOnce: boolean;
|
|
44
|
+
rowComparator: DifferentialWatchedQueryComparator<RowType> | undefined;
|
|
45
|
+
throttleMs: number | undefined;
|
|
46
|
+
reportFetching: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function configEquals<RowType>(a: RunnerConfig<RowType>, b: RunnerConfig<RowType>): boolean {
|
|
50
|
+
if (a === b) return true;
|
|
51
|
+
|
|
52
|
+
switch (a.kind) {
|
|
53
|
+
case 'missing-db':
|
|
54
|
+
case 'waiting-for-streams':
|
|
55
|
+
return a.kind == b.kind;
|
|
56
|
+
case 'compile-error':
|
|
57
|
+
// compile() runs on every render, so a failing query throws a new error each time.
|
|
58
|
+
return b.kind == 'compile-error' && a.error.message == b.error.message;
|
|
59
|
+
case 'query':
|
|
60
|
+
return (
|
|
61
|
+
b.kind == 'query' &&
|
|
62
|
+
a.db === b.db &&
|
|
63
|
+
a.sql == b.sql &&
|
|
64
|
+
a.stringifiedParams == b.stringifiedParams &&
|
|
65
|
+
a.runOnce == b.runOnce &&
|
|
66
|
+
// We don't compare rowComparator by reference, since it's typically an inline object changed on every rerender.
|
|
67
|
+
// Only toggling between differential and regular queries is considered a re-run worthy chamge.
|
|
68
|
+
!!a.rowComparator == !!b.rowComparator &&
|
|
69
|
+
a.throttleMs == b.throttleMs &&
|
|
70
|
+
a.reportFetching == b.reportFetching
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const _loadingState: QueryResult<never> = { isLoading: true, isFetching: false, data: [], error: undefined };
|
|
76
|
+
|
|
77
|
+
function idleResultFor<RowType>(config: RunnerConfig<RowType>): Result<RowType> {
|
|
78
|
+
switch (config.kind) {
|
|
79
|
+
case 'missing-db':
|
|
80
|
+
return { isLoading: false, isFetching: false, data: [], error: new Error('PowerSync not configured.') };
|
|
81
|
+
case 'waiting-for-streams':
|
|
82
|
+
return _loadingState;
|
|
83
|
+
case 'compile-error':
|
|
84
|
+
return { isLoading: false, isFetching: false, data: [], error: config.error };
|
|
85
|
+
case 'query':
|
|
86
|
+
// Single queries always report fetching while they run.
|
|
87
|
+
const isFetching = config.runOnce || config.reportFetching;
|
|
88
|
+
return {
|
|
89
|
+
isLoading: true,
|
|
90
|
+
isFetching,
|
|
91
|
+
data: [],
|
|
92
|
+
error: undefined,
|
|
93
|
+
fetchReason: isFetching ? 'initial' : undefined
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Resolves the inputs of `useQuery` into a comparable {@link RunnerConfig}.
|
|
100
|
+
*
|
|
101
|
+
* This is pure (apart from compiling the query) and can run while rendering.
|
|
102
|
+
*/
|
|
103
|
+
export function resolveConfig<RowType>(
|
|
104
|
+
db: CommonPowerSyncDatabase | null,
|
|
105
|
+
query: WatchCompatibleQueryWithParams<RowType[]>,
|
|
106
|
+
options: AdditionalOptions & DifferentialHookOptions<RowType>,
|
|
107
|
+
streamsHaveSynced: boolean
|
|
108
|
+
): RunnerConfig<RowType> {
|
|
109
|
+
if (db == null) {
|
|
110
|
+
return { kind: 'missing-db' };
|
|
111
|
+
}
|
|
112
|
+
if (!streamsHaveSynced) {
|
|
113
|
+
return { kind: 'waiting-for-streams' };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
let sql: string;
|
|
117
|
+
let parameters: ReadonlyArray<any>;
|
|
118
|
+
try {
|
|
119
|
+
const compiled = query.compile();
|
|
120
|
+
sql = compiled.sql;
|
|
121
|
+
parameters = compiled.parameters;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
return { kind: 'compile-error', error: error as Error };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
kind: 'query',
|
|
128
|
+
db,
|
|
129
|
+
query,
|
|
130
|
+
sql,
|
|
131
|
+
parameters,
|
|
132
|
+
stringifiedParams: query.stringifiedParameters ?? JSON.stringify(parameters),
|
|
133
|
+
runOnce: options.runQueryOnce == true,
|
|
134
|
+
rowComparator: options.rowComparator,
|
|
135
|
+
throttleMs: options.throttleMs,
|
|
136
|
+
reportFetching: options.reportFetching ?? true
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface QueryRunnerListener extends BaseListener {
|
|
141
|
+
onChange(): void;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* An imperative store backing the `useQuery` hook. There is always one instance of this per `useQuery` hook.
|
|
146
|
+
*
|
|
147
|
+
* On every render, {@link resultFor} checks for config changes and returns the current result. Configuration changes
|
|
148
|
+
* are not applied during renders. Instead, {@link configure} is used to apply configuration changes in a commit. This
|
|
149
|
+
* ensures multiple {@link resultFor} calls in uncommited renders are cheap and don't trigger queries.
|
|
150
|
+
*
|
|
151
|
+
* Work is only active while at least one listener is registered.
|
|
152
|
+
*/
|
|
153
|
+
export class QueryRunner<RowType> extends BaseObserver<QueryRunnerListener> {
|
|
154
|
+
private config: RunnerConfig<RowType> | null = null;
|
|
155
|
+
private idleResult: Result<RowType> = _loadingState;
|
|
156
|
+
/**
|
|
157
|
+
* The active work, only non-null while we have listeners.
|
|
158
|
+
*/
|
|
159
|
+
private work: QueryWork<RowType> | null = null;
|
|
160
|
+
/**
|
|
161
|
+
* A cached result for a config that hasn't been applied yet, so that repeated renders return a stable object.
|
|
162
|
+
*/
|
|
163
|
+
private uncommitedConfigChange: {
|
|
164
|
+
config: RunnerConfig<RowType>;
|
|
165
|
+
snapshot: Result<RowType>;
|
|
166
|
+
result: Result<RowType>;
|
|
167
|
+
isOptimisticStateChange: boolean;
|
|
168
|
+
} | null = null;
|
|
169
|
+
|
|
170
|
+
readonly subscribe = (onChange: () => void): (() => void) => {
|
|
171
|
+
const listener = { onChange } satisfies QueryRunnerListener;
|
|
172
|
+
|
|
173
|
+
const unregister = this.registerListener(listener);
|
|
174
|
+
if (this.listeners.size == 1) {
|
|
175
|
+
this.startWork();
|
|
176
|
+
this.notifyListeners();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return () => {
|
|
180
|
+
unregister();
|
|
181
|
+
if (this.listeners.size == 0) {
|
|
182
|
+
this.work?.dispose();
|
|
183
|
+
this.work = null;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
readonly getSnapshot = (): Result<RowType> => {
|
|
189
|
+
return this.work?.result ?? this.idleResult;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Returns the result to render for the given config, without changing the runner.
|
|
194
|
+
*
|
|
195
|
+
* If the config has already been applied, this is the current snapshot. Otherwise, it's the result we expect to
|
|
196
|
+
* report right after {@link configure} applies it, so that changed inputs are reflected in the same render (even if
|
|
197
|
+
* that render is ultimately dropped).
|
|
198
|
+
*/
|
|
199
|
+
resultFor(config: RunnerConfig<RowType>, snapshot: Result<RowType>): Result<RowType> {
|
|
200
|
+
if (this.config != null && configEquals(this.config, config)) {
|
|
201
|
+
return snapshot;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const pending = this.uncommitedConfigChange;
|
|
205
|
+
if (pending != null && pending.snapshot === snapshot && configEquals(pending.config, config)) {
|
|
206
|
+
return pending.result;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// A re-render has changed the query, and we'll start running that query in a useEffect hook calling configure.
|
|
210
|
+
// For now, optimistically return the loading state that query would start.
|
|
211
|
+
const fromWork = this.work?.pendingResultFor(config);
|
|
212
|
+
const result = fromWork ?? idleResultFor(config);
|
|
213
|
+
this.uncommitedConfigChange = { config, snapshot, result, isOptimisticStateChange: fromWork == null };
|
|
214
|
+
return result;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Applies the inputs of a committed render to this runner. This does nothing if they haven't changed.
|
|
219
|
+
*
|
|
220
|
+
* This modifies state and should not run during a render.
|
|
221
|
+
*/
|
|
222
|
+
configure(next: RunnerConfig<RowType>) {
|
|
223
|
+
if (this.config != null && configEquals(this.config, next)) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const pending = this.uncommitedConfigChange;
|
|
228
|
+
this.config = next;
|
|
229
|
+
this.idleResult =
|
|
230
|
+
pending != null && pending.isOptimisticStateChange && configEquals(pending.config, next)
|
|
231
|
+
? // We already returned this as an optimistic state in a previous resultFor call. Use the same result to not
|
|
232
|
+
// cause another render.
|
|
233
|
+
pending.result
|
|
234
|
+
: idleResultFor(next);
|
|
235
|
+
this.uncommitedConfigChange = null;
|
|
236
|
+
|
|
237
|
+
if (this.work == null || !this.work.tryUpdate(next)) {
|
|
238
|
+
this.work?.dispose();
|
|
239
|
+
this.work = null;
|
|
240
|
+
if (this.listeners.size > 0) {
|
|
241
|
+
this.startWork();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
this.notifyListeners();
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private startWork() {
|
|
249
|
+
const config = this.config;
|
|
250
|
+
if (config == null || config.kind != 'query') {
|
|
251
|
+
// In waiting or error state, don't run anything.
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const emit = () => this.notifyListeners();
|
|
256
|
+
this.work = new (config.runOnce ? SingleQueryWork : WatchedQueryWork)(config, this.idleResult, emit);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private notifyListeners() {
|
|
260
|
+
this.iterateListeners((l) => l.onChange?.());
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Active work to run a query (once or watched).
|
|
266
|
+
*/
|
|
267
|
+
interface QueryWork<RowType> {
|
|
268
|
+
readonly result: Result<RowType>;
|
|
269
|
+
/**
|
|
270
|
+
* If {@link tryUpdate} would accept the config, returns the result to report until it's applied. Must be pure.
|
|
271
|
+
*/
|
|
272
|
+
pendingResultFor(config: RunnerConfig<RowType>): Result<RowType> | null;
|
|
273
|
+
/**
|
|
274
|
+
* Attempts to apply the new config to this work without restarting it.
|
|
275
|
+
*/
|
|
276
|
+
tryUpdate(config: RunnerConfig<RowType>): boolean;
|
|
277
|
+
dispose(): void;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
class SingleQueryWork<RowType> implements QueryWork<RowType> {
|
|
281
|
+
result: QueryResult<RowType>;
|
|
282
|
+
private abortController: AbortController | null = null;
|
|
283
|
+
private disposed = false;
|
|
284
|
+
|
|
285
|
+
constructor(
|
|
286
|
+
private readonly config: QueryConfig<RowType>,
|
|
287
|
+
initial: Result<RowType>,
|
|
288
|
+
private readonly emit: () => void
|
|
289
|
+
) {
|
|
290
|
+
this.result = {
|
|
291
|
+
...(initial as QueryResult<RowType>),
|
|
292
|
+
isFetching: true,
|
|
293
|
+
fetchReason: 'initial',
|
|
294
|
+
refresh: this.refresh
|
|
295
|
+
};
|
|
296
|
+
this.run();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
readonly refresh = async (signal?: AbortSignal) => {
|
|
300
|
+
if (this.disposed) return;
|
|
301
|
+
await this.run(signal);
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
private setResult(update: Partial<QueryResult<RowType>>) {
|
|
305
|
+
this.result = { ...this.result, ...update };
|
|
306
|
+
this.emit();
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
private async run(outerSignal?: AbortSignal) {
|
|
310
|
+
this.abortController?.abort();
|
|
311
|
+
const controller = (this.abortController = new AbortController());
|
|
312
|
+
const signal = controller.signal;
|
|
313
|
+
const isAborted = () => signal.aborted || outerSignal?.aborted == true;
|
|
314
|
+
|
|
315
|
+
if (!this.result.isLoading || !this.result.isFetching || this.result.error) {
|
|
316
|
+
this.setResult({ isLoading: true, isFetching: true, error: undefined, fetchReason: 'initial' });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const { query, sql, parameters, db } = this.config;
|
|
320
|
+
try {
|
|
321
|
+
const data = await query.execute({ sql, parameters: [...parameters], db });
|
|
322
|
+
if (isAborted()) return;
|
|
323
|
+
this.setResult({ isLoading: false, isFetching: false, data, error: undefined, fetchReason: undefined });
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (isAborted()) return;
|
|
326
|
+
this.setResult({ isLoading: false, isFetching: false, data: [], error: error as Error, fetchReason: undefined });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
pendingResultFor(): null {
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
tryUpdate(): boolean {
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
dispose(): void {
|
|
339
|
+
this.abortController?.abort();
|
|
340
|
+
this.abortController = null;
|
|
341
|
+
this.disposed = true;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
class WatchedQueryWork<RowType> implements QueryWork<RowType> {
|
|
346
|
+
result: Result<RowType>;
|
|
347
|
+
private readonly watch: DifferentialWatchedQuery<RowType>;
|
|
348
|
+
private readonly disposeListener: () => void;
|
|
349
|
+
/**
|
|
350
|
+
* Set after calling `updateSettings` until the watched query starts applying the new settings. We report
|
|
351
|
+
* `isFetching` in the meantime so that the hook doesn't briefly appear settled with stale data.
|
|
352
|
+
*/
|
|
353
|
+
private pendingUpdate = false;
|
|
354
|
+
/**
|
|
355
|
+
* Set by {@link tryUpdate} until the updated query has produced its first result. Until then, `data` still holds the
|
|
356
|
+
* previous query's rows, which is reported as `fetchReason: 'settings-changed'`.
|
|
357
|
+
*/
|
|
358
|
+
private awaitingUpdatedResult = false;
|
|
359
|
+
private reportFetching: boolean;
|
|
360
|
+
|
|
361
|
+
constructor(
|
|
362
|
+
private config: QueryConfig<RowType>,
|
|
363
|
+
initial: Result<RowType>,
|
|
364
|
+
private readonly emit: () => void
|
|
365
|
+
) {
|
|
366
|
+
this.result = initial;
|
|
367
|
+
this.reportFetching = config.reportFetching;
|
|
368
|
+
|
|
369
|
+
const { db, query, rowComparator, throttleMs, reportFetching } = config;
|
|
370
|
+
const customQuery = db.customQuery(query);
|
|
371
|
+
this.watch = rowComparator
|
|
372
|
+
? customQuery.differentialWatch({ rowComparator, reportFetching, throttleMs })
|
|
373
|
+
: customQuery.watch({ reportFetching, throttleMs });
|
|
374
|
+
|
|
375
|
+
this.disposeListener = this.watch.registerListener({
|
|
376
|
+
onStateChange: (state) => {
|
|
377
|
+
if (this.awaitingUpdatedResult && !this.pendingUpdate && !state.isFetching) {
|
|
378
|
+
// The first completed fetch after the new settings were applied is the updated query's result.
|
|
379
|
+
this.awaitingUpdatedResult = false;
|
|
380
|
+
}
|
|
381
|
+
this.result = this.mapState(state);
|
|
382
|
+
this.emit();
|
|
383
|
+
},
|
|
384
|
+
settingsWillUpdate: () => {
|
|
385
|
+
// The watched query sets isFetching itself after this event, so we stop overriding it. We don't emit
|
|
386
|
+
// here because the state may not reflect that yet, the next onStateChange delivers the updated state.
|
|
387
|
+
this.pendingUpdate = false;
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
private mapState(state: WatchedQueryState<ReadonlyArray<Readonly<RowType>>>): Result<RowType> {
|
|
393
|
+
// The state object may be mutated by the watched query, so we copy it into a fresh snapshot.
|
|
394
|
+
const isFetching = state.isFetching || (this.pendingUpdate && this.reportFetching);
|
|
395
|
+
return {
|
|
396
|
+
data: state.data as RowType[],
|
|
397
|
+
isLoading: state.isLoading,
|
|
398
|
+
isFetching,
|
|
399
|
+
error: state.error ?? undefined,
|
|
400
|
+
fetchReason: this.fetchReasonFor(state.isLoading, isFetching)
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private fetchReasonFor(isLoading: boolean, isFetching: boolean): FetchReason | undefined {
|
|
405
|
+
if (!isFetching) return undefined;
|
|
406
|
+
if (isLoading) return 'initial';
|
|
407
|
+
return this.awaitingUpdatedResult ? 'settings-changed' : 'tables-changed';
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
private canUpdate(config: RunnerConfig<RowType>): config is QueryConfig<RowType> {
|
|
411
|
+
return (
|
|
412
|
+
config.kind == 'query' &&
|
|
413
|
+
!config.runOnce &&
|
|
414
|
+
config.db === this.config.db &&
|
|
415
|
+
!!config.rowComparator == !!this.config.rowComparator
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
pendingResultFor(config: RunnerConfig<RowType>): Result<RowType> | null {
|
|
420
|
+
if (!this.canUpdate(config)) {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Keep the previous data while the updated query runs.
|
|
425
|
+
const isFetching = this.result.isFetching || config.reportFetching;
|
|
426
|
+
return {
|
|
427
|
+
...this.result,
|
|
428
|
+
isFetching,
|
|
429
|
+
fetchReason: !isFetching ? undefined : this.result.isLoading ? 'initial' : 'settings-changed'
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
tryUpdate(config: RunnerConfig<RowType>): boolean {
|
|
434
|
+
if (!this.canUpdate(config)) {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
this.config = config;
|
|
439
|
+
this.reportFetching = config.reportFetching;
|
|
440
|
+
this.pendingUpdate = true;
|
|
441
|
+
this.awaitingUpdatedResult = true;
|
|
442
|
+
this.watch.updateSettings({
|
|
443
|
+
query: config.query,
|
|
444
|
+
throttleMs: config.throttleMs,
|
|
445
|
+
reportFetching: config.reportFetching
|
|
446
|
+
});
|
|
447
|
+
this.result = this.mapState(this.watch.state);
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
dispose(): void {
|
|
452
|
+
this.disposeListener();
|
|
453
|
+
this.watch.close();
|
|
454
|
+
}
|
|
455
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { type CompilableQuery } from '@powersync/common';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { useContext, useEffect, useRef, useSyncExternalStore } from 'react';
|
|
3
|
+
import { PowerSyncContext } from '../PowerSyncContext.js';
|
|
4
|
+
import { useAllSyncStreamsHaveSynced } from '../streams.js';
|
|
5
|
+
import { QueryRunner, resolveConfig } from './QueryRunner.js';
|
|
5
6
|
import { AdditionalOptions, DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types.js';
|
|
6
7
|
import { constructCompatibleQuery } from './watch-utils.js';
|
|
7
|
-
import { useAllSyncStreamsHaveSynced } from '../streams.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* A hook to access the results of a watched query.
|
|
@@ -57,43 +57,17 @@ export function useQuery<RowType = any>(
|
|
|
57
57
|
parameters: any[] = [],
|
|
58
58
|
options: AdditionalOptions & DifferentialHookOptions<RowType> = {}
|
|
59
59
|
) {
|
|
60
|
-
const powerSync =
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
..._loadingState,
|
|
64
|
-
isLoading: false,
|
|
65
|
-
error: new Error('PowerSync not configured.')
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
const { parsedQuery, queryChanged } = constructCompatibleQuery(query, parameters, options);
|
|
69
|
-
const streamsHaveSynced = useAllSyncStreamsHaveSynced(powerSync, options?.streams);
|
|
70
|
-
const runOnce = options?.runQueryOnce == true;
|
|
71
|
-
const single = useSingleQuery<RowType>({
|
|
72
|
-
query: parsedQuery,
|
|
73
|
-
powerSync,
|
|
74
|
-
queryChanged,
|
|
75
|
-
active: runOnce && streamsHaveSynced
|
|
76
|
-
});
|
|
77
|
-
const watched = useWatchedQuery<RowType>({
|
|
78
|
-
query: parsedQuery,
|
|
79
|
-
powerSync,
|
|
80
|
-
queryChanged,
|
|
81
|
-
options: {
|
|
82
|
-
reportFetching: options.reportFetching,
|
|
83
|
-
throttleMs: options.throttleMs,
|
|
84
|
-
// Maintains backwards compatibility with previous versions
|
|
85
|
-
// Differentiation is opt-in by default
|
|
86
|
-
// We emit new data for each table change by default.
|
|
87
|
-
rowComparator: options.rowComparator
|
|
88
|
-
},
|
|
89
|
-
active: !runOnce && streamsHaveSynced
|
|
90
|
-
});
|
|
60
|
+
const powerSync = useContext(PowerSyncContext);
|
|
61
|
+
const parsedQuery = constructCompatibleQuery(query, parameters);
|
|
62
|
+
const streamsHaveSynced = useAllSyncStreamsHaveSynced(null, options.streams);
|
|
91
63
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
64
|
+
const runnerRef = useRef<QueryRunner<RowType> | null>(null);
|
|
65
|
+
const runner = (runnerRef.current ??= new QueryRunner<RowType>());
|
|
66
|
+
const config = resolveConfig(powerSync, parsedQuery, options, streamsHaveSynced);
|
|
95
67
|
|
|
96
|
-
|
|
97
|
-
}
|
|
68
|
+
const snapshot = useSyncExternalStore(runner.subscribe, runner.getSnapshot, runner.getSnapshot);
|
|
98
69
|
|
|
99
|
-
|
|
70
|
+
// Apply the inputs once this render has been committed, so that discarded renders don't start running queries.
|
|
71
|
+
useEffect(() => runner.configure(config));
|
|
72
|
+
return runner.resultFor(config, snapshot);
|
|
73
|
+
}
|
|
@@ -21,7 +21,7 @@ export const useWatchedQuerySubscription = <
|
|
|
21
21
|
>(
|
|
22
22
|
query: Query
|
|
23
23
|
): Query['state'] => {
|
|
24
|
-
return useNullableWatchedQuerySubscription(query)
|
|
24
|
+
return useNullableWatchedQuerySubscription(query)!;
|
|
25
25
|
};
|
|
26
26
|
|
|
27
27
|
/**
|
|
@@ -31,7 +31,7 @@ export const useNullableWatchedQuerySubscription = <
|
|
|
31
31
|
ResultType = unknown,
|
|
32
32
|
Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>
|
|
33
33
|
>(
|
|
34
|
-
query:
|
|
34
|
+
query: WatchedQuery<ResultType> | null
|
|
35
35
|
): Query['state'] | undefined => {
|
|
36
36
|
const [output, setOutputState] = React.useState(query?.state);
|
|
37
37
|
|
|
@@ -7,9 +7,9 @@ export interface HookWatchOptions extends Omit<SQLOnChangeOptions, 'signal'> {
|
|
|
7
7
|
*
|
|
8
8
|
* When set, `useQuery` will subscribe to those streams (and automatically handle unsubscribing from them, too).
|
|
9
9
|
*
|
|
10
|
-
* If {@link QuerySyncStreamOptions} is set on a stream, `useQuery` will remain in a loading state until
|
|
11
|
-
* is marked as {@link SyncSubscriptionDescription.hasSynced}. This ensures the query is not missing rows
|
|
12
|
-
* been downloaded.
|
|
10
|
+
* If {@link QuerySyncStreamOptions.waitForStream} is set on a stream, `useQuery` will remain in a loading state until
|
|
11
|
+
* that stream is marked as {@link SyncSubscriptionDescription.hasSynced}. This ensures the query is not missing rows
|
|
12
|
+
* that haven't been downloaded.
|
|
13
13
|
* Note however that after an initial sync, the query will not block itself while new rows are downloading. Instead,
|
|
14
14
|
* consistent sync snapshots will be made available as they've been processed by PowerSync.
|
|
15
15
|
*/
|
|
@@ -56,6 +56,16 @@ export interface DifferentialHookOptions<RowType> extends HookWatchOptions {
|
|
|
56
56
|
rowComparator?: DifferentialWatchedQueryComparator<RowType>;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Why a `useQuery` hook is currently fetching.
|
|
61
|
+
*
|
|
62
|
+
* - `'initial'`: the first load of this query, `isLoading` is true as well.
|
|
63
|
+
* - `'tables-changed'`: a table the query depends on changed and the same query is re-running. `data` is still current.
|
|
64
|
+
* - `'settings-changed'`: the SQL, parameters or options changed. `data` still holds the previous query's rows until the
|
|
65
|
+
* updated query has produced its first result.
|
|
66
|
+
*/
|
|
67
|
+
export type FetchReason = 'initial' | 'tables-changed' | 'settings-changed';
|
|
68
|
+
|
|
59
69
|
export type ReadonlyQueryResult<RowType> = {
|
|
60
70
|
readonly data: ReadonlyArray<Readonly<RowType>>;
|
|
61
71
|
/**
|
|
@@ -67,6 +77,11 @@ export type ReadonlyQueryResult<RowType> = {
|
|
|
67
77
|
*/
|
|
68
78
|
readonly isFetching: boolean;
|
|
69
79
|
readonly error: Error | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Why the query is running while `isFetching` is true, `undefined` otherwise. `'settings-changed'` means the
|
|
82
|
+
* SQL, parameters or options changed and `data` still holds the previous query's rows until the new result arrives.
|
|
83
|
+
*/
|
|
84
|
+
readonly fetchReason?: FetchReason;
|
|
70
85
|
/**
|
|
71
86
|
* Function used to run the query again.
|
|
72
87
|
*/
|
|
@@ -84,6 +99,11 @@ export type QueryResult<RowType> = {
|
|
|
84
99
|
*/
|
|
85
100
|
isFetching: boolean;
|
|
86
101
|
error: Error | undefined;
|
|
102
|
+
/**
|
|
103
|
+
* Why the query is running while `isFetching` is true, `undefined` otherwise. `'settings-changed'` means the
|
|
104
|
+
* SQL, parameters or options changed and `data` still holds the previous query's rows until the new result arrives.
|
|
105
|
+
*/
|
|
106
|
+
fetchReason?: FetchReason;
|
|
87
107
|
/**
|
|
88
108
|
* Function used to run the query again.
|
|
89
109
|
*/
|
|
@@ -1,54 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CompilableQuery, WatchCompatibleQuery } from '@powersync/common';
|
|
2
2
|
import React from 'react';
|
|
3
|
-
import {
|
|
4
|
-
import { AdditionalOptions } from './watch-types.js';
|
|
3
|
+
import { usePowerSyncOrNull } from '../PowerSyncContext.js';
|
|
5
4
|
|
|
6
|
-
export
|
|
7
|
-
query: WatchCompatibleQuery<DataType>;
|
|
8
|
-
powerSync: AbstractPowerSyncDatabase;
|
|
9
|
-
queryChanged: boolean;
|
|
10
|
-
active: boolean;
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
interface WatchCompatibleQueryWithParams<T> extends WatchCompatibleQuery<T> {
|
|
5
|
+
export interface WatchCompatibleQueryWithParams<T> extends WatchCompatibleQuery<T> {
|
|
14
6
|
stringifiedParameters?: string;
|
|
15
7
|
}
|
|
16
8
|
|
|
17
|
-
export const
|
|
18
|
-
|
|
19
|
-
try {
|
|
20
|
-
_compiled = query.compile();
|
|
21
|
-
} catch (error) {
|
|
22
|
-
return false; // If compilation fails, we assume the query has changed
|
|
23
|
-
}
|
|
24
|
-
const compiled = _compiled!;
|
|
25
|
-
|
|
26
|
-
const stringifiedParams = query.stringifiedParameters ?? JSON.stringify(compiled.parameters);
|
|
27
|
-
const stringifiedOptions = JSON.stringify(options);
|
|
28
|
-
|
|
29
|
-
const previousQueryRef = React.useRef({ sqlStatement: compiled.sql, stringifiedParams, stringifiedOptions });
|
|
30
|
-
|
|
31
|
-
if (
|
|
32
|
-
previousQueryRef.current.sqlStatement !== compiled.sql ||
|
|
33
|
-
previousQueryRef.current.stringifiedParams != stringifiedParams ||
|
|
34
|
-
previousQueryRef.current.stringifiedOptions != stringifiedOptions
|
|
35
|
-
) {
|
|
36
|
-
previousQueryRef.current.sqlStatement = compiled.sql;
|
|
37
|
-
previousQueryRef.current.stringifiedParams = stringifiedParams;
|
|
38
|
-
previousQueryRef.current.stringifiedOptions = stringifiedOptions;
|
|
39
|
-
|
|
40
|
-
return true;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
return false;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
export const constructCompatibleQuery = <RowType>(
|
|
47
|
-
query: string | CompilableQuery<RowType>,
|
|
48
|
-
parameters: any[] = [],
|
|
49
|
-
options: AdditionalOptions
|
|
50
|
-
) => {
|
|
51
|
-
const powerSync = usePowerSync()!;
|
|
9
|
+
export const constructCompatibleQuery = <RowType>(query: string | CompilableQuery<RowType>, parameters: any[] = []) => {
|
|
10
|
+
const powerSync = usePowerSyncOrNull();
|
|
52
11
|
const stringifiedParameters = React.useMemo(() => JSON.stringify(parameters), [parameters]);
|
|
53
12
|
|
|
54
13
|
const parsedQuery = React.useMemo<WatchCompatibleQueryWithParams<RowType[]>>(() => {
|
|
@@ -58,8 +17,8 @@ export const constructCompatibleQuery = <RowType>(
|
|
|
58
17
|
sql: query,
|
|
59
18
|
parameters
|
|
60
19
|
}),
|
|
61
|
-
execute: () => powerSync
|
|
62
|
-
// Setting this is a small optimization that avoids
|
|
20
|
+
execute: () => powerSync!.getAll(query, parameters),
|
|
21
|
+
// Setting this is a small optimization that avoids QueryRunner recomputing the JSON representation.
|
|
63
22
|
stringifiedParameters
|
|
64
23
|
};
|
|
65
24
|
} else {
|
|
@@ -79,10 +38,5 @@ export const constructCompatibleQuery = <RowType>(
|
|
|
79
38
|
}
|
|
80
39
|
}, [query, powerSync, stringifiedParameters]);
|
|
81
40
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return {
|
|
85
|
-
parsedQuery,
|
|
86
|
-
queryChanged
|
|
87
|
-
};
|
|
41
|
+
return parsedQuery;
|
|
88
42
|
};
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export
|
|
1
|
+
export { usePowerSync, PowerSyncContext } from './hooks/PowerSyncContext.js';
|
|
2
2
|
export { SuspenseQueryResult } from './hooks/suspense/SuspenseQueryResult.js';
|
|
3
3
|
export { useSuspenseQuery } from './hooks/suspense/useSuspenseQuery.js';
|
|
4
4
|
export { useWatchedQuerySuspenseSubscription } from './hooks/suspense/useWatchedQuerySuspenseSubscription.js';
|
|
@@ -6,4 +6,4 @@ export { useAllSyncStreamsHaveSynced, useSyncStream, UseSyncStreamOptions } from
|
|
|
6
6
|
export { useStatus } from './hooks/useStatus.js';
|
|
7
7
|
export { useQuery } from './hooks/watched/useQuery.js';
|
|
8
8
|
export { useWatchedQuerySubscription } from './hooks/watched/useWatchedQuerySubscription.js';
|
|
9
|
-
export { AdditionalOptions, QuerySyncStreamOptions } from './hooks/watched/watch-types.js';
|
|
9
|
+
export { AdditionalOptions, FetchReason, QuerySyncStreamOptions } from './hooks/watched/watch-types.js';
|