@pgxsinkit/react 0.1.32 → 0.1.36

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.
@@ -0,0 +1,18 @@
1
+ /** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */
2
+ export type SelectedFields = Record<string, unknown>;
3
+ /**
4
+ * Map a raw PGlite live-query row onto a Drizzle select's field keys.
5
+ *
6
+ * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which
7
+ * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`
8
+ * produces SQL `select "assignee_id"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.
9
+ * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it
10
+ * by name using the select's field metadata:
11
+ *
12
+ * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;
13
+ * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;
14
+ * - a nested selection object recurses;
15
+ * - with no field map (a raw query) the row is returned unchanged.
16
+ */
17
+ export declare function remapLiveRow(selectedFields: SelectedFields | undefined, row: Record<string, unknown>): Record<string, unknown>;
18
+ //# sourceMappingURL=remap-live-row.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remap-live-row.d.ts","sourceRoot":"","sources":["../src/remap-live-row.ts"],"names":[],"mappings":"AAEA,6GAA6G;AAC7G,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAErD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAC1B,cAAc,EAAE,cAAc,GAAG,SAAS,EAC1C,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC3B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAezB"}
package/package.json CHANGED
@@ -1,10 +1,15 @@
1
1
  {
2
2
  "name": "@pgxsinkit/react",
3
- "version": "0.1.32",
3
+ "version": "0.1.36",
4
+ "keywords": [
5
+ "tanstack-intent"
6
+ ],
7
+ "license": "MIT",
4
8
  "files": [
5
9
  "dist",
6
10
  "src",
7
- "README.md"
11
+ "README.md",
12
+ "skills"
8
13
  ],
9
14
  "type": "module",
10
15
  "main": "./dist/index.js",
@@ -22,12 +27,12 @@
22
27
  "build": "bun --cwd ../.. run build:public-packages"
23
28
  },
24
29
  "dependencies": {
25
- "@pgxsinkit/client": "0.1.32",
26
- "@pgxsinkit/contracts": "0.1.32"
30
+ "@pgxsinkit/client": "0.1.36",
31
+ "@pgxsinkit/contracts": "0.1.36"
27
32
  },
28
33
  "peerDependencies": {
29
- "@electric-sql/pglite": "0.5.2",
30
- "drizzle-orm": "1.0.0-rc.2",
34
+ "@electric-sql/pglite": "0.5.4",
35
+ "drizzle-orm": "1.0.0-rc.4",
31
36
  "react": ">=19.2.7"
32
37
  },
33
38
  "repository": {
@@ -0,0 +1,74 @@
1
+ ---
2
+ name: react
3
+ description: >-
4
+ Load when wiring @pgxsinkit/react into a React app — createSyncClientHooks and the reactive read hooks
5
+ (useLiveRows, useLiveRow, useLiveDrizzleRows, useLiveDrizzleRow) plus SyncClientProvider /
6
+ useSyncClient. Teaches that live reads are event-driven off PGlite's live.query (they fire on commit,
7
+ not on a poll), that useLiveDrizzleRows remaps snake_case columns back to the builder's field keys
8
+ while raw useLiveRows returns underlying column names, the { rows, loading, error } contract, and that
9
+ writes go through client.tables.<t> (not the hooks) and flush on enqueue. Load before building React
10
+ components that read or write synced data.
11
+ metadata:
12
+ type: framework
13
+ framework: react
14
+ library: "@pgxsinkit/react"
15
+ library_version: "0.1.32"
16
+ source: https://pgxsinkit.github.io/
17
+ requires:
18
+ - react
19
+ ---
20
+
21
+ # Using @pgxsinkit/react
22
+
23
+ Create one set of registry-typed hooks at module scope and provide the client at the root:
24
+
25
+ ```ts
26
+ export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows } =
27
+ createSyncClientHooks<typeof registry>();
28
+ ```
29
+
30
+ Wrap your tree in `<SyncClientProvider client={client}>`; components then read the local store
31
+ reactively and write through the client.
32
+
33
+ ## Reads are reactive and event-driven (not polled)
34
+
35
+ The live hooks register a PGlite `live.query`. When the sync engine applies a change to PGlite, the live
36
+ query re-runs and the hook re-renders — **on commit, not on an interval**. Do not add a `setInterval` to
37
+ "refresh" a live query; it is already reactive, and polling PGlite is actively harmful (every query is
38
+ ~50ms of WASM work on one thread — see the `operating` skill).
39
+
40
+ Every read hook returns `{ rows, loading, error }` (singular variants return `{ row, ... }`). Pass
41
+ `ready: false` to defer a query until a dependency is available.
42
+
43
+ ## Prefer `useLiveDrizzleRows` for typed, correctly-keyed rows
44
+
45
+ PGlite returns rows keyed by the underlying **snake_case** column names. `useLiveDrizzleRows` takes a
46
+ Drizzle select builder and **remaps** those back to the builder's (camelCase) field keys, so the rows
47
+ match the inferred type with no casts:
48
+
49
+ ```ts
50
+ const { rows } = useLiveDrizzleRows((c) => c.drizzle.select().from(c.views.todos), []);
51
+ ```
52
+
53
+ Raw `useLiveRows(sql, { params })` does **no** remap — its rows carry the raw DB column names. Use it for
54
+ ad-hoc SQL where you control the column names; prefer `useLiveDrizzleRows` for typed reads. The Drizzle
55
+ builder is rebuilt when the `deps` array changes (same contract as `useEffect`).
56
+
57
+ ## Writes go through `client.tables`, not the hooks
58
+
59
+ The read hooks are read-only. Mutate via `client.tables.<table>.create/update/delete` (or
60
+ `useSyncClient()` inside a component). Each call stages an optimistic local write (the live query
61
+ re-renders this frame) and **flushes on enqueue** — the optimistic overlay clears when the server value
62
+ streams back through Electric. See the `core` skill for the write model and `operating` for convergence
63
+ cadence and the `globalThis.__pgxsinkitDebug` latency instrumentation.
64
+
65
+ ## Common mistakes
66
+
67
+ - Expecting `useLiveRows` to return camelCase keys — it returns raw DB column names; use
68
+ `useLiveDrizzleRows` for remapped, typed rows.
69
+ - Polling PGlite (`setInterval` re-reads) to "watch" data — the hooks are already reactive, and polling
70
+ saturates the single WASM thread.
71
+ - Mutating local tables directly instead of through `client.tables.<t>` (the one write path).
72
+ - Reading before the client is ready instead of gating with `ready: false`.
73
+
74
+ Reference: <https://pgxsinkit.github.io/>.
@@ -1,16 +1,50 @@
1
1
  import type { LiveQuery, LiveQueryResults } from "@electric-sql/pglite/live";
2
2
  import { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
3
3
 
4
- import type { ClientPGlite, SyncClient } from "@pgxsinkit/client";
5
- import type { SyncTableRegistry } from "@pgxsinkit/contracts";
4
+ import { type ClientPGlite, type LiveRowsSubscription, type SyncClient, syncDebug } from "@pgxsinkit/client";
5
+ import type { SyncTableName, SyncTableRegistry } from "@pgxsinkit/contracts";
6
+
7
+ import { remapLiveRow, type SelectedFields } from "./remap-live-row";
6
8
 
7
9
  /**
8
10
  * Minimal interface satisfied by every Drizzle select/query builder.
9
11
  * Calling `.toSQL()` extracts the SQL string and positional params without
10
- * executing the query, so they can be fed into PGlite's live query API.
12
+ * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the
13
+ * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys
14
+ * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.
11
15
  */
12
16
  interface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {
13
17
  toSQL(): { sql: string; params: unknown[] };
18
+ readonly _?: { readonly selectedFields?: SelectedFields };
19
+ }
20
+
21
+ /** Reactive read result. `hydrating` is true while a lazy relation the query reads is being activated. */
22
+ interface LiveRowsState<TRows> {
23
+ rows: TRows;
24
+ loading: boolean;
25
+ hydrating: boolean;
26
+ error: Error | null;
27
+ }
28
+
29
+ /**
30
+ * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).
31
+ * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the
32
+ * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.
33
+ */
34
+ function subscribeRawPglite<TRow extends Record<string, unknown>>(
35
+ pglite: ClientPGlite,
36
+ query: string,
37
+ params: unknown[],
38
+ onRows: (rows: TRow[]) => void,
39
+ ): Promise<LiveRowsSubscription<TRow>> {
40
+ return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {
41
+ const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);
42
+ registered.subscribe(listener);
43
+ return {
44
+ initialRows: registered.initialResults.rows,
45
+ unsubscribe: () => void registered.unsubscribe(listener),
46
+ };
47
+ });
14
48
  }
15
49
 
16
50
  /**
@@ -18,7 +52,7 @@ interface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLik
18
52
  * `SyncTableRegistry` type. Call this once at the module level in your app:
19
53
  *
20
54
  * ```ts
21
- * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows } =
55
+ * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =
22
56
  * createSyncClientHooks<typeof mySyncRegistry>();
23
57
  * ```
24
58
  */
@@ -41,6 +75,12 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
41
75
 
42
76
  // ─── Raw SQL live hooks ───────────────────────────────────────────────────
43
77
 
78
+ /**
79
+ * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the
80
+ * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a
81
+ * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.
82
+ * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.
83
+ */
44
84
  function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(
45
85
  query: string,
46
86
  options?: {
@@ -51,7 +91,10 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
51
91
  },
52
92
  ): { rows: TRow[]; loading: boolean; error: Error | null } {
53
93
  const contextClient = useContext(SyncClientContext);
54
- const pglite = options?.pglite ?? contextClient?.pglite;
94
+ // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query
95
+ // runs through the client's live-rows seam, so this hook works against the worker-attached client too
96
+ // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).
97
+ const overridePglite = options?.pglite;
55
98
  const ready = options?.ready ?? true;
56
99
 
57
100
  const paramsKey = JSON.stringify(options?.params ?? []);
@@ -64,44 +107,52 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
64
107
  });
65
108
 
66
109
  useEffect(() => {
67
- if (!ready || pglite == null) {
110
+ const canRun = ready && (overridePglite != null || contextClient != null);
111
+ if (!canRun) {
68
112
  setState({ rows: [], loading: ready, error: null });
69
113
  return;
70
114
  }
71
115
 
72
116
  let active = true;
73
- let liveQuery: LiveQuery<TRow> | undefined;
74
- let listener: ((results: LiveQueryResults<TRow>) => void) | undefined;
117
+ let subscription: LiveRowsSubscription<TRow> | undefined;
75
118
 
76
119
  setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
77
120
 
78
- void pglite.live
79
- .query<TRow>(query, stableParams)
80
- .then((registered: LiveQuery<TRow>) => {
81
- if (!active) return registered.unsubscribe();
82
- liveQuery = registered;
83
- setState({ rows: registered.initialResults.rows, loading: false, error: null });
84
- listener = (results) => {
85
- if (active) setState({ rows: results.rows, loading: false, error: null });
86
- };
87
- registered.subscribe(listener);
88
- return undefined;
121
+ const onRows = (rows: TRow[]) => {
122
+ if (active) {
123
+ syncDebug("live query updated → re-render", { rows: rows.length });
124
+ setState({ rows, loading: false, error: null });
125
+ }
126
+ };
127
+
128
+ // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`
129
+ // wrapper the in-process client exposes, so behaviour is identical when no override is given.
130
+ const subscribe = overridePglite
131
+ ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)
132
+ : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>
133
+ onRows(rows as TRow[]),
134
+ );
135
+
136
+ void subscribe
137
+ .then((registered) => {
138
+ if (!active) {
139
+ registered.unsubscribe();
140
+ return;
141
+ }
142
+ subscription = registered as LiveRowsSubscription<TRow>;
143
+ setState({ rows: registered.initialRows as TRow[], loading: false, error: null });
89
144
  })
90
145
  .catch((error: unknown) => {
91
146
  if (active) {
92
- setState({
93
- rows: [],
94
- loading: false,
95
- error: error instanceof Error ? error : new Error(String(error)),
96
- });
147
+ setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });
97
148
  }
98
149
  });
99
150
 
100
151
  return () => {
101
152
  active = false;
102
- if (liveQuery) void liveQuery.unsubscribe(listener);
153
+ subscription?.unsubscribe();
103
154
  };
104
- }, [pglite, query, ready, stableParams]);
155
+ }, [contextClient, overridePglite, query, ready, stableParams]);
105
156
 
106
157
  return state;
107
158
  }
@@ -117,69 +168,93 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
117
168
  // ─── Drizzle typed live hooks ─────────────────────────────────────────────
118
169
 
119
170
  /**
120
- * Reactive query using a Drizzle select builder. The builder is re-created
121
- * whenever `deps` changes (same contract as `useEffect`).
122
- *
123
- * ```ts
124
- * const { rows } = useLiveDrizzleRows(
125
- * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),
126
- * [],
127
- * );
128
- * // rows is fully typed from the view definition — no casts needed
129
- * ```
171
+ * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,
172
+ * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional
173
+ * `use`), activates + hydrates them, and only then subscribes the live query — so it is never
174
+ * registered against an un-hydrated lazy relation (ADR-0021).
130
175
  */
131
- function useLiveDrizzleRows<TRows extends readonly unknown[]>(
176
+ function useGuardedDrizzleLive<TRows extends readonly unknown[]>(
132
177
  buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,
133
178
  deps: DependencyList,
134
- options?: { ready?: boolean },
135
- ): { rows: TRows; loading: boolean; error: Error | null } {
179
+ options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[] },
180
+ ): LiveRowsState<TRows> {
136
181
  const contextClient = useContext(SyncClientContext);
137
182
  const ready = options?.ready ?? true;
183
+ const useList = options?.use;
184
+ const useKey = useList != null ? JSON.stringify(useList) : "";
138
185
 
139
- const sqlObj = useMemo(
140
- () => (contextClient != null ? buildQuery(contextClient).toSQL() : null),
186
+ const queryInfo = useMemo(
187
+ () => {
188
+ if (contextClient == null) return null;
189
+ const query = buildQuery(contextClient);
190
+ return { sql: query.toSQL(), selectedFields: query._?.selectedFields };
191
+ },
141
192
  // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.
142
193
  // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design
143
194
  [contextClient, ...deps],
144
195
  );
145
196
 
146
- const sqlKey = sqlObj != null ? JSON.stringify(sqlObj) : null;
197
+ const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;
147
198
 
148
- const [state, setState] = useState<{ rows: TRows; loading: boolean; error: Error | null }>({
199
+ const [state, setState] = useState<LiveRowsState<TRows>>({
149
200
  rows: [] as unknown as TRows,
150
201
  loading: ready,
202
+ hydrating: ready,
151
203
  error: null,
152
204
  });
153
205
 
154
206
  useEffect(() => {
155
- if (!ready || contextClient == null || sqlObj == null) {
156
- setState({ rows: [] as unknown as TRows, loading: ready, error: null });
207
+ if (!ready || contextClient == null || queryInfo == null) {
208
+ setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });
157
209
  return;
158
210
  }
159
211
 
212
+ const { sql, selectedFields } = queryInfo;
213
+ // PGlite's live query returns rows keyed by the underlying (snake_case) column names; remap them
214
+ // back to the Drizzle select's field keys so the rows match the builder's inferred (camelCase) type.
215
+ const mapRows = (rows: readonly unknown[]): TRows =>
216
+ rows.map((row) => remapLiveRow(selectedFields, row as Record<string, unknown>)) as unknown as TRows;
217
+
160
218
  let active = true;
161
- let liveQuery: LiveQuery<TRows[number]> | undefined;
162
- let listener: ((results: LiveQueryResults<TRows[number]>) => void) | undefined;
219
+ let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;
163
220
 
164
- setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
221
+ setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));
165
222
 
166
- void contextClient.pglite.live
167
- .query<TRows[number]>(sqlObj.sql, sqlObj.params)
168
- .then((registered: LiveQuery<TRows[number]>) => {
169
- if (!active) return registered.unsubscribe();
170
- liveQuery = registered;
171
- setState({ rows: registered.initialResults.rows as unknown as TRows, loading: false, error: null });
172
- listener = (results) => {
173
- if (active) setState({ rows: results.rows as unknown as TRows, loading: false, error: null });
174
- };
175
- registered.subscribe(listener);
176
- return undefined;
223
+ // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), activate + hydrate them,
224
+ // THEN subscribe via the client's live-rows seam — so a query is never registered against an
225
+ // un-hydrated lazy relation (ADR-0021), and the same hook drives both the in-process client (seam over
226
+ // `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).
227
+ void contextClient
228
+ .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })
229
+ .then(() => {
230
+ if (!active) return undefined;
231
+ setState((prev) => ({ rows: prev.rows, loading: true, hydrating: false, error: null }));
232
+ return contextClient
233
+ .subscribeLiveRows<Record<string, unknown>>(
234
+ { sql: sql.sql, params: sql.params, ...(useList ? { use: useList } : {}) },
235
+ (rows) => {
236
+ if (active) {
237
+ syncDebug("live query updated → re-render", { rows: rows.length });
238
+ setState({ rows: mapRows(rows), loading: false, hydrating: false, error: null });
239
+ }
240
+ },
241
+ )
242
+ .then((registered) => {
243
+ if (!active) {
244
+ registered.unsubscribe();
245
+ return undefined;
246
+ }
247
+ subscription = registered;
248
+ setState({ rows: mapRows(registered.initialRows), loading: false, hydrating: false, error: null });
249
+ return undefined;
250
+ });
177
251
  })
178
252
  .catch((error: unknown) => {
179
253
  if (active) {
180
254
  setState({
181
255
  rows: [] as unknown as TRows,
182
256
  loading: false,
257
+ hydrating: false,
183
258
  error: error instanceof Error ? error : new Error(String(error)),
184
259
  });
185
260
  }
@@ -187,22 +262,82 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
187
262
 
188
263
  return () => {
189
264
  active = false;
190
- if (liveQuery) void liveQuery.unsubscribe(listener);
265
+ subscription?.unsubscribe();
191
266
  };
192
- // sqlKey is a stable JSON snapshot of sql+params; sqlObj is captured inside the effect from sqlKey
193
- // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey is the stable proxy for sqlObj
194
- }, [contextClient, sqlKey, ready]);
267
+ // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.
268
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo
269
+ }, [contextClient, sqlKey, useKey, ready]);
195
270
 
196
271
  return state;
197
272
  }
198
273
 
274
+ /**
275
+ * Reactive query using a Drizzle select builder. The builder is re-created
276
+ * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and
277
+ * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,
278
+ * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,
279
+ * not a requirement (ADR-0021).
280
+ *
281
+ * ```ts
282
+ * const { rows } = useLiveDrizzleRows(
283
+ * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),
284
+ * [],
285
+ * );
286
+ * // rows is fully typed from the view definition — no casts needed
287
+ * ```
288
+ */
289
+ function useLiveDrizzleRows<TRows extends readonly unknown[]>(
290
+ buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,
291
+ deps: DependencyList,
292
+ options?: { ready?: boolean },
293
+ ): LiveRowsState<TRows> {
294
+ return useGuardedDrizzleLive(buildQuery, deps, options);
295
+ }
296
+
199
297
  function useLiveDrizzleRow<TRows extends readonly unknown[]>(
200
298
  buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,
201
299
  deps: DependencyList,
202
300
  options?: { ready?: boolean },
203
- ): { row: TRows[number] | null; loading: boolean; error: Error | null } {
204
- const { rows, loading, error } = useLiveDrizzleRows(buildQuery, deps, options);
205
- return { row: rows[0] ?? null, loading, error };
301
+ ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {
302
+ const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);
303
+ return { row: rows[0] ?? null, loading, hydrating, error };
304
+ }
305
+
306
+ /**
307
+ * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`
308
+ * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they
309
+ * are guaranteed activated before it subscribes. The non-live counterpart of
310
+ * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,
311
+ * which auto-detect every relation and need no `use`.
312
+ *
313
+ * ```ts
314
+ * const { rows, hydrating } = useLiveQueryRaw({
315
+ * use: ["archive"],
316
+ * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),
317
+ * deps: [recentIds],
318
+ * });
319
+ * ```
320
+ */
321
+ function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {
322
+ use?: readonly SyncTableName<TRegistry>[];
323
+ build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;
324
+ deps?: DependencyList;
325
+ ready?: boolean;
326
+ }): LiveRowsState<TRows> {
327
+ return useGuardedDrizzleLive(args.build, args.deps ?? [], {
328
+ ...(args.ready != null ? { ready: args.ready } : {}),
329
+ ...(args.use ? { use: args.use } : {}),
330
+ });
331
+ }
332
+
333
+ function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {
334
+ use?: readonly SyncTableName<TRegistry>[];
335
+ build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;
336
+ deps?: DependencyList;
337
+ ready?: boolean;
338
+ }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {
339
+ const { rows, loading, hydrating, error } = useLiveQueryRaw(args);
340
+ return { row: rows[0] ?? null, loading, hydrating, error };
206
341
  }
207
342
 
208
343
  return {
@@ -212,5 +347,7 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
212
347
  useLiveRow,
213
348
  useLiveDrizzleRows,
214
349
  useLiveDrizzleRow,
350
+ useLiveQueryRaw,
351
+ useLiveQueryRawRow,
215
352
  };
216
353
  }
@@ -0,0 +1,38 @@
1
+ import { Column, is, SQL } from "drizzle-orm";
2
+
3
+ /** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */
4
+ export type SelectedFields = Record<string, unknown>;
5
+
6
+ /**
7
+ * Map a raw PGlite live-query row onto a Drizzle select's field keys.
8
+ *
9
+ * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which
10
+ * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`
11
+ * produces SQL `select "assignee_id"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.
12
+ * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it
13
+ * by name using the select's field metadata:
14
+ *
15
+ * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;
16
+ * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;
17
+ * - a nested selection object recurses;
18
+ * - with no field map (a raw query) the row is returned unchanged.
19
+ */
20
+ export function remapLiveRow(
21
+ selectedFields: SelectedFields | undefined,
22
+ row: Record<string, unknown>,
23
+ ): Record<string, unknown> {
24
+ if (selectedFields == null) return row;
25
+ const out: Record<string, unknown> = {};
26
+ for (const [key, field] of Object.entries(selectedFields)) {
27
+ if (is(field, Column)) {
28
+ out[key] = row[field.name];
29
+ } else if (is(field, SQL) || is(field, SQL.Aliased)) {
30
+ out[key] = row[key];
31
+ } else if (field != null && typeof field === "object") {
32
+ out[key] = remapLiveRow(field as SelectedFields, row);
33
+ } else {
34
+ out[key] = row[key];
35
+ }
36
+ }
37
+ return out;
38
+ }