@pgxsinkit/react 0.2.7 → 0.5.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.
@@ -1,8 +1,7 @@
1
- import type { LiveQuery, LiveQueryResults } from "@electric-sql/pglite/live";
2
1
  import { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
3
2
 
4
3
  import {
5
- type ClientPGlite,
4
+ type PgwasmClient,
6
5
  type LiveRowsSubscription,
7
6
  type MutationListOptions,
8
7
  type MutationSummaryDetail,
@@ -11,13 +10,14 @@ import {
11
10
  syncDebug,
12
11
  } from "@pgxsinkit/client";
13
12
  import type { MutationSummary, SyncTableName, SyncTableRegistry } from "@pgxsinkit/contracts";
13
+ import type { LiveQuery, LiveQueryResults } from "@pgxsinkit/pgwasm/live";
14
14
 
15
15
  import { liveFieldAliases, remapAliasedLiveRow, remapLiveRow, type SelectedFields } from "./remap-live-row";
16
16
 
17
17
  /**
18
18
  * Minimal interface satisfied by every Drizzle select/query builder.
19
19
  * Calling `.toSQL()` extracts the SQL string and positional params without
20
- * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the
20
+ * executing the query, so they can be fed into pgwasm's live query API. `_.selectedFields` is the
21
21
  * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys
22
22
  * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.
23
23
  */
@@ -43,12 +43,12 @@ interface LiveRowsState<TRows> {
43
43
  }
44
44
 
45
45
  /**
46
- * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).
46
+ * The raw direct-pgwasm subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).
47
47
  * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the
48
48
  * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.
49
49
  */
50
50
  function subscribeRawPglite<TRow extends Record<string, unknown>>(
51
- pglite: ClientPGlite,
51
+ pglite: PgwasmClient,
52
52
  query: string,
53
53
  params: unknown[],
54
54
  onRows: (rows: TRow[]) => void,
@@ -63,6 +63,13 @@ function subscribeRawPglite<TRow extends Record<string, unknown>>(
63
63
  });
64
64
  }
65
65
 
66
+ /**
67
+ * Shared "no subscription yet" rows. The hooks DERIVE their return value during render, so this has to be
68
+ * one stable identity — a fresh `[]` per render would defeat the memoised return object and re-fire every
69
+ * consumer effect that depends on `rows`.
70
+ */
71
+ const EMPTY_ROWS: never[] = [];
72
+
66
73
  const EMPTY_MUTATION_SUMMARY: MutationSummary = {
67
74
  pendingCount: 0,
68
75
  sendingCount: 0,
@@ -108,56 +115,65 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
108
115
  * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a
109
116
  * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.
110
117
  * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.
118
+ *
119
+ * `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
120
+ * `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
121
+ * (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
122
+ * loading" policy already applied across a query change.
111
123
  */
112
124
  function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(
113
125
  query: string,
114
126
  options?: {
115
127
  params?: readonly unknown[];
116
128
  ready?: boolean;
117
- /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */
118
- pglite?: ClientPGlite;
129
+ /** Explicit pgwasm instance — overrides the context client. Useful in tests or multi-db scenarios. */
130
+ pgwasm?: PgwasmClient;
119
131
  },
120
132
  ): { rows: TRow[]; loading: boolean; error: Error | null } {
121
133
  const contextClient = useContext(SyncClientContext);
122
- // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query
134
+ // An explicit `pglite` override keeps the raw direct-pgwasm path (tests/multi-db); otherwise the query
123
135
  // runs through the client's live-rows seam, so this hook works against the worker-attached client too
124
136
  // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).
125
- const overridePglite = options?.pglite;
137
+ const overridePglite = options?.pgwasm;
126
138
  const ready = options?.ready ?? true;
127
139
 
128
140
  const paramsKey = JSON.stringify(options?.params ?? []);
129
141
  const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);
130
142
 
131
- const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({
132
- rows: [],
133
- loading: ready,
143
+ const canRun = ready && (overridePglite != null || contextClient != null);
144
+ // The run token: ONE object whose identity changes exactly when the subscription inputs change, and
145
+ // `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every
146
+ // snapshot the effect writes, so `loading` is derived during render ("does the snapshot belong to the
147
+ // current run?") instead of being written synchronously from the effect.
148
+ const run = useMemo(
149
+ () => (canRun ? { query, params: stableParams, client: contextClient, pglite: overridePglite } : null),
150
+ [canRun, query, stableParams, contextClient, overridePglite],
151
+ );
152
+
153
+ const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: TRow[]; error: Error | null }>({
154
+ run: null,
155
+ rows: EMPTY_ROWS,
134
156
  error: null,
135
157
  });
136
158
 
137
159
  useEffect(() => {
138
- const canRun = ready && (overridePglite != null || contextClient != null);
139
- if (!canRun) {
140
- setState({ rows: [], loading: ready, error: null });
141
- return;
142
- }
160
+ if (run == null) return;
143
161
 
144
162
  let active = true;
145
163
  let subscription: LiveRowsSubscription<TRow> | undefined;
146
164
 
147
- setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
148
-
149
165
  const onRows = (rows: TRow[]) => {
150
166
  if (active) {
151
167
  syncDebug("live query updated → re-render", { rows: rows.length });
152
- setState({ rows, loading: false, error: null });
168
+ setSnapshot({ run, rows, error: null });
153
169
  }
154
170
  };
155
171
 
156
- // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`
172
+ // The raw-pgwasm override subscribes directly (unchanged); the seam path is the SAME `pglite.live`
157
173
  // wrapper the in-process client exposes, so behaviour is identical when no override is given.
158
- const subscribe = overridePglite
159
- ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)
160
- : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>
174
+ const subscribe = run.pglite
175
+ ? subscribeRawPglite<TRow>(run.pglite, run.query, run.params, onRows)
176
+ : run.client!.subscribeLiveRows<Record<string, unknown>>({ sql: run.query, params: run.params }, (rows) =>
161
177
  onRows(rows as TRow[]),
162
178
  );
163
179
 
@@ -168,11 +184,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
168
184
  return;
169
185
  }
170
186
  subscription = registered as LiveRowsSubscription<TRow>;
171
- setState({ rows: registered.initialRows as TRow[], loading: false, error: null });
187
+ setSnapshot({ run, rows: registered.initialRows as TRow[], error: null });
172
188
  })
173
189
  .catch((error: unknown) => {
174
190
  if (active) {
175
- setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });
191
+ setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });
176
192
  }
177
193
  });
178
194
 
@@ -180,14 +196,22 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
180
196
  active = false;
181
197
  subscription?.unsubscribe();
182
198
  };
183
- }, [contextClient, overridePglite, query, ready, stableParams]);
199
+ }, [run]);
200
+
201
+ // Derived, never stored: a snapshot is authoritative only for the run it was tagged with. Holding the
202
+ // previous run's rows until the new one settles is exactly what the old synchronous
203
+ // `setState({ rows: prev.rows, loading: true })` did; no client (or `ready: false`) reads as no rows.
204
+ const settled = run != null && snapshot.run === run;
205
+ const rows = run == null ? EMPTY_ROWS : snapshot.rows;
206
+ const loading = ready && !settled;
207
+ const error = settled ? snapshot.error : null;
184
208
 
185
- return state;
209
+ return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);
186
210
  }
187
211
 
188
212
  function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(
189
213
  query: string,
190
- options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },
214
+ options?: { params?: readonly unknown[]; ready?: boolean; pgwasm?: PgwasmClient },
191
215
  ): { row: TRow | null; loading: boolean; error: Error | null } {
192
216
  const { rows, loading, error } = useLiveRows<TRow>(query, options);
193
217
  return { row: rows[0] ?? null, loading, error };
@@ -200,6 +224,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
200
224
  * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional
201
225
  * `use`), activates + hydrates them, and only then subscribes the live query — so it is never
202
226
  * registered against an un-hydrated lazy relation (ADR-0021).
227
+ *
228
+ * `loading`/`hydrating`/`rows` are derived from which subscription the latest snapshot belongs to, so a
229
+ * `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
230
+ * (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
231
+ * loading" policy already applied across a query change.
203
232
  */
204
233
  function useGuardedDrizzleLive<TRows extends readonly unknown[]>(
205
234
  buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,
@@ -228,22 +257,39 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
228
257
 
229
258
  const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;
230
259
 
231
- const [state, setState] = useState<LiveRowsState<TRows>>({
232
- rows: [] as unknown as TRows,
233
- loading: ready,
234
- hydrating: ready,
260
+ // The run token: ONE object whose identity changes exactly when the subscription must be rebuilt, and
261
+ // `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every
262
+ // snapshot the effect writes, so `loading`/`hydrating` are derived during render instead of being
263
+ // written synchronously from the effect. `keepAliveMs` rides along inside the token precisely because
264
+ // it is NOT a dep: it is read at subscribe time and never resubscribes (ADR-0040 decision 4, above).
265
+ const run = useMemo(
266
+ () =>
267
+ ready && contextClient != null && queryInfo != null
268
+ ? { client: contextClient, queryInfo, useList, keepAliveMs }
269
+ : null,
270
+ // sqlKey/useKey are stable JSON snapshots; queryInfo/useList/keepAliveMs are captured in the token.
271
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo
272
+ [contextClient, sqlKey, useKey, ready],
273
+ );
274
+
275
+ const [snapshot, setSnapshot] = useState<{
276
+ run: typeof run;
277
+ rows: TRows;
278
+ hydrated: boolean;
279
+ error: Error | null;
280
+ }>({
281
+ run: null,
282
+ rows: EMPTY_ROWS as unknown as TRows,
283
+ hydrated: false,
235
284
  error: null,
236
285
  });
237
286
 
238
287
  useEffect(() => {
239
- if (!ready || contextClient == null || queryInfo == null) {
240
- setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });
241
- return;
242
- }
288
+ if (run == null) return;
243
289
 
244
- const { sql, selectedFields } = queryInfo;
290
+ const { sql, selectedFields } = run.queryInfo;
245
291
  // Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a
246
- // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's
292
+ // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise pgwasm's
247
293
  // live query refuses it (`column "title" specified more than once`) and same-named columns collapse.
248
294
  // With `fields` the rows come back keyed by those aliases, so map by alias; without a field map (a raw
249
295
  // query) the seam leaves the SQL unwrapped and rows stay name-keyed (`remapLiveRow`).
@@ -258,8 +304,6 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
258
304
  let active = true;
259
305
  let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;
260
306
 
261
- setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));
262
-
263
307
  // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams
264
308
  // started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never
265
309
  // registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process
@@ -272,23 +316,30 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
272
316
  // promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it
273
317
  // refreshes the live query against the caught-up store before resolving), so clearing `hydrating`
274
318
  // here can never present zero rows as "empty" while the catch-up rows are still in flight.
275
- void contextClient
276
- .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })
319
+ void run.client
320
+ .prepareQuery({ sql: sql.sql, ...(run.useList ? { use: run.useList } : {}) })
277
321
  .then(() => {
278
322
  if (!active) return undefined;
279
- return contextClient
323
+ return run.client
280
324
  .subscribeLiveRows<Record<string, unknown>>(
281
325
  {
282
326
  sql: sql.sql,
283
327
  params: sql.params,
284
328
  ...(fields ? { fields } : {}),
285
- ...(useList ? { use: useList } : {}),
286
- ...(keepAliveMs != null ? { keepAliveMs } : {}),
329
+ ...(run.useList ? { use: run.useList } : {}),
330
+ ...(run.keepAliveMs != null ? { keepAliveMs: run.keepAliveMs } : {}),
287
331
  },
288
332
  (rows) => {
289
333
  if (active) {
290
334
  syncDebug("live query updated → re-render", { rows: rows.length });
291
- setState((prev) => ({ rows: mapRows(rows), loading: false, hydrating: prev.hydrating, error: null }));
335
+ // A diff can land before the initial snapshot, so carry `hydrated` over only when the
336
+ // previous snapshot belongs to THIS run — otherwise it is the previous run's flag.
337
+ setSnapshot((prev) => ({
338
+ run,
339
+ rows: mapRows(rows),
340
+ hydrated: prev.run === run ? prev.hydrated : false,
341
+ error: null,
342
+ }));
292
343
  }
293
344
  },
294
345
  )
@@ -304,15 +355,17 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
304
355
  rows: registered.initialRows.length,
305
356
  hydrating: registered.hydrated != null,
306
357
  });
307
- setState((prev) => ({
358
+ // No `hydrated` promise ⇒ every referenced group was already caught up at subscribe time, so
359
+ // this first snapshot IS the hydrated one (the steady-state fast path).
360
+ setSnapshot({
361
+ run,
308
362
  rows: mapRows(registered.initialRows),
309
- loading: false,
310
- hydrating: registered.hydrated != null ? prev.hydrating : false,
363
+ hydrated: registered.hydrated == null,
311
364
  error: null,
312
- }));
365
+ });
313
366
  if (registered.hydrated) {
314
367
  void registered.hydrated.then(() => {
315
- if (active) setState((prev) => ({ ...prev, hydrating: false }));
368
+ if (active) setSnapshot((prev) => (prev.run === run ? { ...prev, hydrated: true } : prev));
316
369
  });
317
370
  }
318
371
  return undefined;
@@ -320,10 +373,10 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
320
373
  })
321
374
  .catch((error: unknown) => {
322
375
  if (active) {
323
- setState({
324
- rows: [] as unknown as TRows,
325
- loading: false,
326
- hydrating: false,
376
+ setSnapshot({
377
+ run,
378
+ rows: EMPTY_ROWS as unknown as TRows,
379
+ hydrated: true,
327
380
  error: error instanceof Error ? error : new Error(String(error)),
328
381
  });
329
382
  }
@@ -333,11 +386,19 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
333
386
  active = false;
334
387
  subscription?.unsubscribe();
335
388
  };
336
- // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.
337
- // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo
338
- }, [contextClient, sqlKey, useKey, ready]);
339
-
340
- return state;
389
+ }, [run]);
390
+
391
+ // Derived, never stored: a snapshot is authoritative only for the run it was tagged with, and it is
392
+ // "hydrated" only once the subscription's `hydrated` promise resolved (or there was none to await).
393
+ // A failed run settles hydrated so an error is not reported as a permanent catch-up, and with no run
394
+ // there is nothing catching up, so `hydrating` is false (`loading` alone reports the missing client).
395
+ const settled = run != null && snapshot.run === run;
396
+ const rows = run == null ? (EMPTY_ROWS as unknown as TRows) : snapshot.rows;
397
+ const loading = ready && !settled;
398
+ const hydrating = run != null && !(settled && snapshot.hydrated);
399
+ const error = settled ? snapshot.error : null;
400
+
401
+ return useMemo(() => ({ rows, loading, hydrating, error }), [rows, loading, hydrating, error]);
341
402
  }
342
403
 
343
404
  /**
@@ -419,6 +480,10 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
419
480
  * EVERY writable journal, folded to one {@link MutationSummary}. ONE subscription drives a global sync
420
481
  * indicator — no `hydrating` flag, because journals are local and never network-hydrated. Cheap enough to
421
482
  * mount permanently (ADR-0040 dedup: one registration regardless of subscriber count).
483
+ *
484
+ * `loading` and `summary` are derived from which subscription the latest snapshot belongs to, so a
485
+ * `ready: false → true` interlude keeps the previous summary while it re-subscribes (`loading: true`)
486
+ * instead of briefly reporting the zero summary.
422
487
  */
423
488
  function useMutationSummary(options?: { ready?: boolean }): {
424
489
  summary: MutationSummary;
@@ -428,25 +493,25 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
428
493
  const client = useContext(SyncClientContext);
429
494
  const ready = options?.ready ?? true;
430
495
 
431
- const [state, setState] = useState<{ summary: MutationSummary; loading: boolean; error: Error | null }>({
496
+ // The run token (see `useLiveRows`): the client is the only subscription input, wrapped so that a
497
+ // `ready` flip yields a fresh identity — otherwise the pre-flip snapshot would read as settled.
498
+ const run = useMemo(() => (ready && client != null ? { client } : null), [ready, client]);
499
+
500
+ const [snapshot, setSnapshot] = useState<{ run: typeof run; summary: MutationSummary; error: Error | null }>({
501
+ run: null,
432
502
  summary: EMPTY_MUTATION_SUMMARY,
433
- loading: ready,
434
503
  error: null,
435
504
  });
436
505
 
437
506
  useEffect(() => {
438
- if (!ready || client == null) {
439
- setState({ summary: EMPTY_MUTATION_SUMMARY, loading: ready, error: null });
440
- return;
441
- }
507
+ if (run == null) return;
442
508
 
443
509
  let active = true;
444
510
  let subscription: MutationSummarySubscription | undefined;
445
- setState((prev) => ({ summary: prev.summary, loading: true, error: null }));
446
511
 
447
- void client.mutations
512
+ void run.client.mutations
448
513
  .subscribeSummary((summary) => {
449
- if (active) setState({ summary, loading: false, error: null });
514
+ if (active) setSnapshot({ run, summary, error: null });
450
515
  })
451
516
  .then((registered) => {
452
517
  if (!active) {
@@ -454,13 +519,13 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
454
519
  return;
455
520
  }
456
521
  subscription = registered;
457
- setState({ summary: registered.initial, loading: false, error: null });
522
+ setSnapshot({ run, summary: registered.initial, error: null });
458
523
  })
459
524
  .catch((error: unknown) => {
460
525
  if (active) {
461
- setState({
526
+ setSnapshot({
527
+ run,
462
528
  summary: EMPTY_MUTATION_SUMMARY,
463
- loading: false,
464
529
  error: error instanceof Error ? error : new Error(String(error)),
465
530
  });
466
531
  }
@@ -470,9 +535,15 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
470
535
  active = false;
471
536
  subscription?.unsubscribe();
472
537
  };
473
- }, [client, ready]);
538
+ }, [run]);
474
539
 
475
- return state;
540
+ // Derived, never stored — see `useLiveRows`.
541
+ const settled = run != null && snapshot.run === run;
542
+ const summary = run == null ? EMPTY_MUTATION_SUMMARY : snapshot.summary;
543
+ const loading = ready && !settled;
544
+ const error = settled ? snapshot.error : null;
545
+
546
+ return useMemo(() => ({ summary, loading, error }), [summary, loading, error]);
476
547
  }
477
548
 
478
549
  /**
@@ -480,6 +551,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
480
551
  * every writable table, filtered by `table` / `entityKey` / `statuses` / `limit`, ordered newest-first.
481
552
  * Route/feature-scoped — mount it where a diagnostics view is open, not app-wide (prefer
482
553
  * {@link useMutationSummary} for a global indicator). No `hydrating` flag (journals are local).
554
+ *
555
+ * `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
556
+ * `ready: false → true` interlude with unchanged filters keeps the previous rows while it re-subscribes
557
+ * (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
558
+ * loading" policy already applied across a filter change.
483
559
  */
484
560
  function useMutationList(options?: MutationListOptions<TRegistry> & { ready?: boolean }): {
485
561
  rows: MutationSummaryDetail[];
@@ -497,25 +573,29 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
497
573
  [filtersKey],
498
574
  );
499
575
 
500
- const [state, setState] = useState<{ rows: MutationSummaryDetail[]; loading: boolean; error: Error | null }>({
501
- rows: [],
502
- loading: ready,
576
+ // The run token (see `useLiveRows`): the client and the JSON-stable filters are the only subscription
577
+ // inputs, so its identity changes exactly when the subscription must be rebuilt — which lets `loading`
578
+ // be derived during render instead of written synchronously from the effect.
579
+ const run = useMemo(
580
+ () => (ready && client != null ? { client, filters: stableFilters } : null),
581
+ [ready, client, stableFilters],
582
+ );
583
+
584
+ const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: MutationSummaryDetail[]; error: Error | null }>({
585
+ run: null,
586
+ rows: EMPTY_ROWS,
503
587
  error: null,
504
588
  });
505
589
 
506
590
  useEffect(() => {
507
- if (!ready || client == null) {
508
- setState({ rows: [], loading: ready, error: null });
509
- return;
510
- }
591
+ if (run == null) return;
511
592
 
512
593
  let active = true;
513
594
  let subscription: { unsubscribe: () => void } | undefined;
514
- setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
515
595
 
516
- void client.mutations
517
- .subscribe(stableFilters, (rows) => {
518
- if (active) setState({ rows, loading: false, error: null });
596
+ void run.client.mutations
597
+ .subscribe(run.filters, (rows) => {
598
+ if (active) setSnapshot({ run, rows, error: null });
519
599
  })
520
600
  .then((registered) => {
521
601
  if (!active) {
@@ -523,11 +603,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
523
603
  return;
524
604
  }
525
605
  subscription = registered;
526
- setState({ rows: registered.initial, loading: false, error: null });
606
+ setSnapshot({ run, rows: registered.initial, error: null });
527
607
  })
528
608
  .catch((error: unknown) => {
529
609
  if (active) {
530
- setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });
610
+ setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });
531
611
  }
532
612
  });
533
613
 
@@ -535,11 +615,15 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
535
615
  active = false;
536
616
  subscription?.unsubscribe();
537
617
  };
538
- // stableFilters is the JSON-stable proxy for the filter inputs.
539
- // oxlint-disable-next-line react-hooks/exhaustive-deps -- filtersKey is the stable proxy for stableFilters
540
- }, [client, ready, filtersKey]);
618
+ }, [run]);
619
+
620
+ // Derived, never stored — see `useLiveRows`.
621
+ const settled = run != null && snapshot.run === run;
622
+ const rows = run == null ? EMPTY_ROWS : snapshot.rows;
623
+ const loading = ready && !settled;
624
+ const error = settled ? snapshot.error : null;
541
625
 
542
- return state;
626
+ return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);
543
627
  }
544
628
 
545
629
  return {
@@ -4,9 +4,9 @@ import { Column, is, SQL } from "drizzle-orm";
4
4
  export type SelectedFields = Record<string, unknown>;
5
5
 
6
6
  /**
7
- * Map a raw PGlite live-query row onto a Drizzle select's field keys.
7
+ * Map a raw pgwasm live-query row onto a Drizzle select's field keys.
8
8
  *
9
- * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which
9
+ * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into pgwasm's `live.query`, which
10
10
  * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`
11
11
  * produces SQL `select "assignee_id"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.
12
12
  * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it
@@ -41,7 +41,7 @@ export function remapLiveRow(
41
41
  //
42
42
  // Reading by the underlying column NAME (as `remapLiveRow` does) is unsound when a JOIN's tables share a
43
43
  // column name — `select({ courseTitle: course.title, moduleTitle: module.title })` compiles to a SELECT
44
- // with two `title` output columns. PGlite's `live` extension MATERIALISES the query and fails hard
44
+ // with two `title` output columns. pgwasm's `live` extension MATERIALISES the query and fails hard
45
45
  // (`column "title" specified more than once`); even a plain query would silently collapse both `title`s
46
46
  // into one value. The seam (`client.subscribeLiveRows`) fixes this by wrapping the query with a POSITIONAL
47
47
  // column-alias-list when it is handed `fields` — the unique aliases below — so every output column is