@pgxsinkit/client 0.1.51 → 0.1.53

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/src/sync/apply.ts CHANGED
@@ -2,10 +2,10 @@
2
2
  // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
3
  import type { ChangeMessage, Row } from "@electric-sql/client";
4
4
  import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
- import { and, eq, fillPlaceholders, sql } from "drizzle-orm";
5
+ import { and, eq, fillPlaceholders, type SQL, sql } from "drizzle-orm";
6
6
  import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
7
7
 
8
- import { quoteIdentifier } from "@pgxsinkit/contracts";
8
+ import { quoteIdentifier, type SyncColumnType } from "@pgxsinkit/contracts";
9
9
 
10
10
  import type { ApplyTarget } from "../local-tables";
11
11
  import { generateCopyData } from "./copy";
@@ -38,6 +38,54 @@ function targetColumn(target: ApplyTarget, name: string): PgColumn {
38
38
  return column;
39
39
  }
40
40
 
41
+ /**
42
+ * True when any of `colNames` is a GENERATED ALWAYS identity column on the target table. Drizzle-orm's
43
+ * insert builder EXCLUDES a generated-always identity column from the rendered INSERT even when the value
44
+ * is supplied (its type error points at `.overridingSystemValue()`), so a plain `.values()` would silently
45
+ * drop such a column — fatal for a GENERATED ALWAYS identity PK (the synced row loses its key and dies on
46
+ * NOT NULL). Detected from the Drizzle column metadata (`generatedIdentity.type === "always"`, mirroring
47
+ * drizzle's own `shouldDisableInsert`). `byDefault` identity is deliberately NOT matched: drizzle already
48
+ * renders those, so the OVERRIDING clause is neither needed nor wanted for them.
49
+ */
50
+ function hasGeneratedIdentityColumn(target: ApplyTarget, colNames: readonly string[]): boolean {
51
+ return colNames.some((name) => {
52
+ const column = target.columnByName[name] as (PgColumn & { generatedIdentity?: { type?: string } }) | undefined;
53
+ return column?.generatedIdentity !== undefined && column.generatedIdentity.type !== "byDefault";
54
+ });
55
+ }
56
+
57
+ /**
58
+ * `db.insert(target.table)`, upgraded to `INSERT … OVERRIDING SYSTEM VALUE` when the applied columns carry
59
+ * a GENERATED ALWAYS identity column ({@link hasGeneratedIdentityColumn}). For a synced cache the SERVER's
60
+ * identity values are authoritative — the local row must carry the server id verbatim, never a
61
+ * locally-generated one — so OVERRIDING SYSTEM VALUE is the semantically correct clause (and it makes
62
+ * drizzle re-include the column it would otherwise drop). Tables without a generated column get a plain
63
+ * insert, so the clause is emitted only where it is required. (The local synced table renders the identity
64
+ * PK as a PLAIN column — the generator emits `getSQLType()` with no identity clause — and PGlite accepts
65
+ * OVERRIDING SYSTEM VALUE against a plain column as a no-op, so this is safe there too.)
66
+ */
67
+ function insertInto(db: ReturnType<typeof drizzleOverPg>, target: ApplyTarget, colNames: readonly string[]) {
68
+ const builder = db.insert(target.table);
69
+ return hasGeneratedIdentityColumn(target, colNames) ? builder.overridingSystemValue() : builder;
70
+ }
71
+
72
+ /**
73
+ * The SQL cast type for a synced column inside a `json_to_recordset` record definition (or a `::` cast).
74
+ * A base/array type is used verbatim ({@link SyncColumnType} contracts `sqlType` to be cast-usable); an
75
+ * ENUM column's `sqlType` is the enum TYPE NAME — a user identifier — so it must be identifier-quoted (an
76
+ * unquoted mixed-case enum name folds to lowercase and fails to resolve) and schema-qualified into the
77
+ * SAME schema the local-schema generator creates the enum in (the synced table's own schema), so the cast
78
+ * resolves without depending on search_path. `[]` is appended for an array column, as for base types.
79
+ */
80
+ function castTypeFor(column: SyncColumnType, tableSchema: string | undefined): string {
81
+ const base = column.isEnum
82
+ ? tableSchema
83
+ ? `${quoteIdentifier(tableSchema)}.${quoteIdentifier(column.sqlType)}`
84
+ : quoteIdentifier(column.sqlType)
85
+ : column.sqlType;
86
+ return `${base}${column.isArray ? "[]" : ""}`;
87
+ }
88
+
41
89
  export interface ApplyMessageToTableOptions {
42
90
  pg: PGliteInterface | Transaction;
43
91
  target: ApplyTarget;
@@ -52,9 +100,25 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
52
100
  switch (message.headers.operation) {
53
101
  case "insert": {
54
102
  if (debug) console.log("inserting", data);
55
- // Apply exactly what Electric sent: an `insert` is a new row (post-truncate or first send), so
56
- // it is a plain INSERT. A genuine primary-key collision must surface, never be silently upserted.
57
- return await db.insert(target.table).values(toDriverRow(target, data) as never);
103
+ const columns = Object.keys(data);
104
+ const insert = insertInto(db, target, columns).values(toDriverRow(target, data) as never);
105
+ if (target.applyMode === "upsert") {
106
+ // ADR-0045 declared exception: this table legitimately receives locally-derived provisional rows
107
+ // (e.g. written by a local trigger), so the server's authoritative CDC insert is applied
108
+ // idempotently — same semantics as `applyUpsertsToTable` — rather than colliding on the pk.
109
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
110
+ if (nonPkColumns.length > 0) {
111
+ return await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
112
+ }
113
+ // Target the pk explicitly so a pk-only conflict is a no-op ONLY on the primary key.
114
+ return await insert.onConflictDoNothing({ target: conflictTarget });
115
+ }
116
+ // Default (`applyMode: "insert"`): apply exactly what Electric sent as a plain INSERT — an `insert`
117
+ // is a new row (post-truncate or first send). A genuine primary-key collision must surface, never
118
+ // be silently upserted (ADR-0014), UNLESS the table declared `applyMode: "upsert"` (handled above).
119
+ // `insertInto` adds OVERRIDING SYSTEM VALUE when the row carries a GENERATED ALWAYS identity column,
120
+ // so the server's authoritative id is preserved rather than silently dropped by the builder.
121
+ return await insert;
58
122
  }
59
123
 
60
124
  case "update": {
@@ -107,8 +171,7 @@ function renderInsert(
107
171
  const placeholderRows = Array.from({ length: rowCount }, (_, r) =>
108
172
  Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),
109
173
  );
110
- const rendered = db
111
- .insert(target.table)
174
+ const rendered = insertInto(db, target, colNames)
112
175
  .values(placeholderRows as never)
113
176
  .toSQL();
114
177
  const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };
@@ -249,6 +312,29 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
249
312
  if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);
250
313
  }
251
314
 
315
+ /**
316
+ * The `ON CONFLICT (pk)` upsert spec for a keyed apply — shared by {@link applyUpsertsToTable} (ADR-0024
317
+ * move-ins / snapshot-acceptance) and the per-message `applyMode: "upsert"` CDC-insert path (ADR-0045),
318
+ * so the two can never drift on conflict semantics. The conflict target is the primary-key columns; the
319
+ * conflict SET refreshes every non-pk column to `excluded.<col>` (the standard conflict pseudo-relation,
320
+ * authored via `sql.identifier` so the column stays a quoted BARE identifier, not table-qualified). A
321
+ * pk-only table yields an empty `nonPkColumns` — the caller then uses `DO NOTHING` targeted at the pk
322
+ * (never a bare `ON CONFLICT DO NOTHING`, which would swallow conflicts on any unique constraint).
323
+ */
324
+ function upsertConflictSpec(
325
+ target: ApplyTarget,
326
+ columns: readonly string[],
327
+ ): { conflictTarget: PgColumn[]; conflictSet: Record<string, unknown>; nonPkColumns: string[] } {
328
+ const pkSet = new Set(target.primaryKey);
329
+ const nonPkColumns = columns.filter((column) => !pkSet.has(column));
330
+ const conflictTarget = target.primaryKey.map((column) => targetColumn(target, column));
331
+ const conflictSet: Record<string, unknown> = {};
332
+ for (const column of nonPkColumns) {
333
+ conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;
334
+ }
335
+ return { conflictTarget, conflictSet, nonPkColumns };
336
+ }
337
+
252
338
  /**
253
339
  * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the
254
340
  * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent
@@ -267,17 +353,7 @@ export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkK
267
353
  if (!firstRow) return;
268
354
 
269
355
  const columns = Object.keys(firstRow);
270
- const pkSet = new Set(primaryKey);
271
- const nonPkColumns = columns.filter((column) => !pkSet.has(column));
272
-
273
- const conflictTarget = primaryKey.map((column) => targetColumn(target, column));
274
- // `DO UPDATE SET col = excluded.col` for every non-pk column; `excluded.<col>` is the standard
275
- // conflict pseudo-relation reference, authored via `sql.identifier` so the column stays a quoted bare
276
- // identifier (not table-qualified). A pk-only table has nothing to refresh → `DO NOTHING`.
277
- const conflictSet: Record<string, unknown> = {};
278
- for (const column of nonPkColumns) {
279
- conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;
280
- }
356
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
281
357
 
282
358
  const perRow = columns.length;
283
359
  const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));
@@ -285,7 +361,9 @@ export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkK
285
361
 
286
362
  for (let i = 0; i < data.length; i += rowsPerBatch) {
287
363
  const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));
288
- const insert = db.insert(target.table).values(batch as never);
364
+ // A move-in row carries the server's authoritative values incl. any GENERATED ALWAYS identity PK, so
365
+ // `insertInto` adds OVERRIDING SYSTEM VALUE where needed (same hazard as the CDC/bulk insert paths).
366
+ const insert = insertInto(db, target, columns).values(batch as never);
289
367
  if (nonPkColumns.length > 0) {
290
368
  await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
291
369
  } else {
@@ -312,13 +390,49 @@ interface JsonRecordsetColumn {
312
390
  */
313
391
  function jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {
314
392
  const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);
393
+ const { schema } = getTableConfig(target.table);
315
394
  return target.columnTypes
316
395
  .filter((column) => present(column.name))
317
- .map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` }));
396
+ .map((column) => ({ name: column.name, castType: castTypeFor(column, schema) }));
397
+ }
398
+
399
+ /**
400
+ * The `ON CONFLICT (pk)` clause for the json-recordset upsert path (ADR-0045 initial-load tier) — the
401
+ * tier-② mirror of {@link upsertConflictSpec}, authored entirely as interpolated `sql.identifier`
402
+ * fragments (no raw identifier text): the conflict target is `target.primaryKey`, and the SET list
403
+ * refreshes every non-pk recordset column to `excluded.<col>`. A pk-only table has nothing to refresh →
404
+ * `DO NOTHING` targeted at the pk (never a bare `ON CONFLICT DO NOTHING`, which would swallow conflicts on
405
+ * any unique constraint — same rule as `upsertConflictSpec`).
406
+ */
407
+ function jsonConflictClause(target: ApplyTarget, columns: JsonRecordsetColumn[]): SQL {
408
+ const pkSet = new Set(target.primaryKey);
409
+ const nonPkColumns = columns.map((column) => column.name).filter((name) => !pkSet.has(name));
410
+ const conflictTarget = sql.join(
411
+ target.primaryKey.map((name) => sql`${sql.identifier(name)}`),
412
+ sql`, `,
413
+ );
414
+ if (nonPkColumns.length === 0) {
415
+ return sql`ON CONFLICT (${conflictTarget}) DO NOTHING`;
416
+ }
417
+ const setList = sql.join(
418
+ nonPkColumns.map((name) => sql`${sql.identifier(name)} = excluded.${sql.identifier(name)}`),
419
+ sql`, `,
420
+ );
421
+ return sql`ON CONFLICT (${conflictTarget}) DO UPDATE SET ${setList}`;
318
422
  }
319
423
 
320
- export async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
321
- if (debug) console.log("applying messages with json_to_recordset");
424
+ /**
425
+ * Shared `json_to_recordset` bulk-apply engine for the initial-load tier — one statement, ONE bound param
426
+ * per 10k-row batch (the ADR-0014 remedy for the batched-INSERT param bound). `conflict` is `undefined`
427
+ * for the strict CDC insert ({@link applyMessagesToTableWithJson}) and the `ON CONFLICT (pk)` clause for
428
+ * the ADR-0045 upsert form ({@link applyUpsertsToTableWithJson}); both share the recordDef and batching so
429
+ * the two can never drift.
430
+ */
431
+ async function applyMessagesToTableWithJsonImpl(
432
+ { pg, target, messages, debug }: BulkApplyMessagesToTableOptions,
433
+ conflict: SQL | undefined,
434
+ ) {
435
+ if (debug) console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
322
436
 
323
437
  const data: Row<unknown>[] = messages.map((message) => message.value);
324
438
  const firstRow = data[0];
@@ -331,23 +445,46 @@ export async function applyMessagesToTableWithJson({ pg, target, messages, debug
331
445
  // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,
332
446
  // NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`
333
447
  // record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and
334
- // type names there, which no tier-①/② builder expresses.
448
+ // type names there, which no tier-①/② builder expresses. The optional ON CONFLICT clause, in contrast,
449
+ // is a fully tier-② `sql.identifier` fragment (see {@link jsonConflictClause}).
335
450
  const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
451
+ const conflictClause = conflict ? sql` ${conflict}` : sql``;
336
452
  const db = drizzleOverPg(pg);
337
453
 
338
454
  const max = 10_000;
339
455
  for (let i = 0; i < data.length; i += max) {
340
456
  const batch = data.slice(i, i + max);
341
457
  await db.execute(
342
- sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,
458
+ sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})${conflictClause}`,
343
459
  );
344
460
  }
345
461
 
346
462
  if (debug) {
347
- console.log(`Inserted ${messages.length} rows using json_to_recordset`);
463
+ console.log(`${conflict ? "Upserted" : "Inserted"} ${messages.length} rows using json_to_recordset`);
348
464
  }
349
465
  }
350
466
 
467
+ export async function applyMessagesToTableWithJson(options: BulkApplyMessagesToTableOptions) {
468
+ return applyMessagesToTableWithJsonImpl(options, undefined);
469
+ }
470
+
471
+ /**
472
+ * The `json_to_recordset` **upsert** applier — the ADR-0045 initial-load tier for an `applyMode: "upsert"`
473
+ * table. Identical bulk shape to {@link applyMessagesToTableWithJson} (one statement, one bound param per
474
+ * batch) but with the `ON CONFLICT (pk) DO UPDATE`/`DO NOTHING` clause appended, so a snapshot for a table
475
+ * that already holds locally-derived provisional rows applies idempotently without the 23505 collision the
476
+ * strict path would raise. This is the bulk CEILING for upsert-mode tables: COPY (the faster tier) has no
477
+ * conflict clause, so the initial path downgrades a COPY-eligible upsert table to json rather than
478
+ * param-bound `applyUpsertsToTable` (~31k bound params/statement for a wide table — the very cost this
479
+ * path avoids).
480
+ */
481
+ export async function applyUpsertsToTableWithJson(options: BulkApplyMessagesToTableOptions) {
482
+ const firstRow = options.messages[0]?.value;
483
+ if (!firstRow) return;
484
+ const columns = jsonRecordsetColumns(options.target, firstRow);
485
+ return applyMessagesToTableWithJsonImpl(options, jsonConflictClause(options.target, columns));
486
+ }
487
+
351
488
  /**
352
489
  * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to
353
490
  * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by
@@ -418,12 +555,13 @@ const JSON_RECORDSET_BATCH = 10_000;
418
555
  */
419
556
  function recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {
420
557
  const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
558
+ const { schema } = getTableConfig(target.table);
421
559
  return columnNames.map((name) => {
422
560
  const column = byName.get(name);
423
561
  if (!column) {
424
562
  throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);
425
563
  }
426
- return { name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` };
564
+ return { name, castType: castTypeFor(column, schema) };
427
565
  });
428
566
  }
429
567
 
package/src/sync/index.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  applyMessagesToTableWithCopy,
21
21
  applyMessagesToTableWithJson,
22
22
  applyUpsertsToTable,
23
+ applyUpsertsToTableWithJson,
23
24
  } from "./apply";
24
25
  import { drizzleOverPg } from "./drizzle-executor";
25
26
  import {
@@ -499,12 +500,33 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
499
500
  messages = remainingMessages;
500
501
 
501
502
  if (initialInserts.length > 0) {
502
- await insertMethods[shapeMethod]({
503
- pg: tx,
504
- target,
505
- messages: initialInserts,
506
- debug,
507
- });
503
+ if (target.applyMode === "upsert") {
504
+ // ADR-0045: the initial bulk-insert fast path's appliers (json/copy/insert) are all
505
+ // plain-INSERT appliers with no conflict clause. A local trigger can already have created
506
+ // rows before this snapshot applies — even on a fresh store, because another table's
507
+ // apply in the same catch-up can fire the trigger — so route through an idempotent
508
+ // upsert applier instead, keeping the `useInsert` bookkeeping identical. A json- or
509
+ // COPY-classified table takes the set-based `json_to_recordset` upsert (COPY itself has
510
+ // no ON CONFLICT clause, so json is the bulk ceiling — and it keeps the performance a
511
+ // param-bound `applyUpsertsToTable` would lose on a large snapshot). A table classified
512
+ // `insert` is so BECAUSE a column is not json-safe — it must take the batched-VALUES
513
+ // upsert, never the json cast.
514
+ const applyInitialUpserts =
515
+ shapeMethod === "insert" ? applyUpsertsToTable : applyUpsertsToTableWithJson;
516
+ await applyInitialUpserts({
517
+ pg: tx,
518
+ target,
519
+ messages: initialInserts,
520
+ debug,
521
+ });
522
+ } else {
523
+ await insertMethods[shapeMethod]({
524
+ pg: tx,
525
+ target,
526
+ messages: initialInserts,
527
+ debug,
528
+ });
529
+ }
508
530
 
509
531
  useInsert.set(shapeName, true);
510
532
  }
@@ -529,11 +551,13 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
529
551
  });
530
552
  }
531
553
  if (folded.inserts.length > 0) {
532
- if (snapshotModeAtPeek.get(shapeName)) {
554
+ if (snapshotModeAtPeek.get(shapeName) || target.applyMode === "upsert") {
533
555
  // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery
534
556
  // loops can re-deliver these exact snapshot rows, possibly in a later commit after this
535
557
  // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same
536
558
  // posture as a move-in, rather than failing the commit on a PK collision.
559
+ // ADR-0045: a table declaring `applyMode: "upsert"` also folds its CDC inserts through the
560
+ // idempotent applier, because a local trigger may already have created the provisional row.
537
561
  await applyUpsertsToTable({
538
562
  pg: tx,
539
563
  target,
@@ -4,10 +4,14 @@
4
4
  // stays the single auth owner: it pushes its token at attach and on `notifyAuthChanged`, and answers the
5
5
  // worker's expiry pull-requests via `getToken`.
6
6
  //
7
- // One-shot Drizzle reads (`query`/`queryRaw`/…), local `pglite`/`ensureSynced`/`destroy` are NOT proxied in
8
- // S2 (the mandated attach surface is the write API + live rows + readiness) — they throw a clear
9
- // not-supported error. Query BUILDING still works on the tab: `drizzle`/`views` are the same build-only
10
- // handles `createSyncClient` exposes, compiled to SQL here and executed in the worker.
7
+ // One-shot Drizzle reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) ARE proxied (ADR-0032 decision 4):
8
+ // `drizzle`/`views` here are a real Drizzle database over a bridge executor whose `query` routes each read to
9
+ // the worker's `guardedQuery` RPC, so awaiting a builder runs the ADR-0041 read gate + the ADR-0021
10
+ // lazy-group guard worker-side and Drizzle's own result mapping (relational/nested included) runs on the tab.
11
+ // `ensureSynced` (async lazy-activation) is a plain RPC to the shared engine. The only members that stay
12
+ // unsupported are the genuinely tab-local ones — `pglite` (no local store), `destroy`/`dropReadCache` (store
13
+ // lifecycle the worker owns), and `isSynced` (a SYNCHRONOUS activation-STARTED peek the tab's cached per-group
14
+ // catch-up readiness cannot answer, and a sync method cannot be an RPC) — each throwing a clear error saying why.
11
15
 
12
16
  import type { Results } from "@electric-sql/pglite";
13
17
 
@@ -25,6 +29,7 @@ import type { DiagnosticExportOptions, DiagnosticExportResult } from "../export-
25
29
  import type { StoreExportOptions, StoreExportResult } from "../export-store";
26
30
  import {
27
31
  buildRegistryReadHandles,
32
+ type ClientPGlite,
28
33
  ClientDisposedError,
29
34
  createMutationsApi,
30
35
  type LiveQueryDiagnostics,
@@ -48,6 +53,7 @@ import {
48
53
  type BridgePort,
49
54
  type BridgeTransferable,
50
55
  type ExportArtefactWire,
56
+ type GuardedQueryWireArgs,
51
57
  identityCodec,
52
58
  isBridgeEnvelope,
53
59
  type LiveDiffPayload,
@@ -128,7 +134,10 @@ export interface AttachSyncClientOptions<TRegistry extends SyncTableRegistry> {
128
134
 
129
135
  /**
130
136
  * The worker-attached client: `SyncClient`'s shape, worker-proxied, plus `notifyAuthChanged` (re-push the
131
- * token after an app auth-state change, ADR-0032 decision 3). The unsupported one-shot-read members throw.
137
+ * token after an app auth-state change, ADR-0032 decision 3). One-shot Drizzle reads
138
+ * (`query`/`queryRow`/`queryRaw`/`queryRawRow`) and `ensureSynced` ARE proxied to the worker; the members
139
+ * that throw are the structurally unproxiable ones — `pglite`, `destroy`, `dropReadCache`, `isSynced`, and
140
+ * `drizzle.transaction()`.
132
141
  */
133
142
  export type AttachedSyncClient<TRegistry extends SyncTableRegistry> = SyncClient<TRegistry> & {
134
143
  notifyAuthChanged: () => void;
@@ -614,13 +623,60 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
614
623
  };
615
624
 
616
625
  // ─── Assembled client ────────────────────────────────────────────────────────────────────────────
617
- const { drizzle, views } = buildRegistryReadHandles(options.registry);
618
626
  const notSupported = (name: string) => (): never => {
619
627
  throw new Error(
620
- `[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`,
628
+ `[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local PGlite. ` +
629
+ `Direct store access (client.pglite) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` +
630
+ `implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` +
631
+ `(ensureSynced), and the write API ARE proxied to the worker.`,
621
632
  );
622
633
  };
623
634
 
635
+ // A tab has no local store to run a read transaction against — every bridge executor's `transaction` throws.
636
+ const noBridgeTransaction = (): never => {
637
+ throw new Error(
638
+ "[pgxsinkit] client.drizzle.transaction() is not available on a worker-attached client: a read " +
639
+ "transaction needs a local PGlite the tab does not have. Use one-shot reads (client.query) instead.",
640
+ );
641
+ };
642
+ // The ONE encoder of the `guardedQuery` positional wire tuple ({@link GuardedQueryWireArgs}): both tab-side
643
+ // senders (the bridge executor below and `guardedRawQuery`) route through this so the shape is written once
644
+ // and shares its contract with the worker-side decoder (`defineSyncWorker` types the decode against the same
645
+ // type). The optional trailing `use` is appended only when present — never a spread of `undefined`.
646
+ const guardedQueryArgs = (
647
+ sql: string,
648
+ params: unknown[] | undefined,
649
+ rowMode: "array" | "object" | undefined,
650
+ use?: readonly string[],
651
+ ): GuardedQueryWireArgs => {
652
+ // `rowMode` is only included when set (exactOptionalPropertyTypes: no `{ rowMode: undefined }`).
653
+ const options = rowMode ? { rowMode } : {};
654
+ return use ? [sql, params, options, use] : [sql, params, options];
655
+ };
656
+ // A `ClientPGlite`-shaped bridge executor Drizzle runs reads against (ADR-0032 decision 4). Drizzle's pglite
657
+ // driver calls only `client.query` for reads and `client.transaction` for `.transaction()`. `query` routes
658
+ // to the worker's `guardedQuery` RPC (stripping drizzle's non-serializable `parsers` to just `rowMode`; the
659
+ // worker re-applies drizzle's identity parsers) and returns the full `Results` so Drizzle's mapping runs on
660
+ // the tab. `use` (a raw-fragment's undetectable lazy relations, ADR-0021) is baked into the closure per read —
661
+ // see `bridgeReadDrizzle` — NOT stashed on a shared field: a shared stash races, because Drizzle executes
662
+ // the builder in a microtask AFTER `queryRaw` returns, so a plain `query` issued synchronously in between
663
+ // would drain its executor first and consume the wrong call's `use`. A per-read scoped executor cannot
664
+ // cross-contaminate.
665
+ const makeBridgeExecutor = (use?: readonly string[]): ClientPGlite =>
666
+ ({
667
+ query: (sql: string, params?: unknown[], options?: { rowMode?: "array" | "object" }): Promise<Results> =>
668
+ rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
669
+ transaction: noBridgeTransaction,
670
+ }) as unknown as ClientPGlite;
671
+ // The base (no-`use`) bridge database `client.drizzle` exposes, plus the cached factory that mints a fresh
672
+ // database over a per-read `use`-carrying executor (the schema/relations are computed ONCE, ADR-0032
673
+ // decision 4). `views` are unchanged.
674
+ const { drizzle, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
675
+ // Build a `use`-scoped Drizzle for one `queryRaw`/`queryRawRow` call and run its builder against a shallow
676
+ // clone of the client whose `drizzle` is that scoped db. The clone is safe: every client method is an arrow
677
+ // closing over this scope (no `this`), so spreading preserves behaviour and only `drizzle` is swapped.
678
+ const bridgeReadDrizzle = (use?: readonly string[]) => drizzleFor(makeBridgeExecutor(use));
679
+
624
680
  const groupKeyForTable = (table: SyncTableName<TRegistry>): string | undefined => {
625
681
  const entry = options.registry[table];
626
682
  return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
@@ -629,13 +685,9 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
629
685
  const client: AttachedSyncClient<TRegistry> = {
630
686
  drizzle,
631
687
  views,
632
- // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse.
633
- pglite: new Proxy(
634
- {},
635
- {
636
- get: notSupported("client.pglite"),
637
- },
638
- ) as never,
688
+ // The tab has no local PGlite; reads go through the live-rows bridge. Touching `.pglite` is a misuse
689
+ // — the real trap is installed as a NON-ENUMERABLE throwing getter after this literal (see below).
690
+ pglite: undefined as never,
639
691
  tables: Object.fromEntries(
640
692
  Object.keys(options.registry).map((tableKey) => [
641
693
  tableKey,
@@ -671,6 +723,11 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
671
723
  // itself stays blocked (below); these route the raw statement over the RPC round-trip instead.
672
724
  rawQuery: (sql, params, options) => rpc<Results>("rawQuery", [sql, params, options]),
673
725
  rawExec: (sql, options) => rpc<Results[]>("rawExec", [sql, options]),
726
+ // The GUARDED raw-SQL read (ADR-0032 decision 4) — the seam the worker host dispatches `guardedQuery` to.
727
+ // Unlike `rawQuery` (raw inspection, no guard), this routes to the worker's `guardedRawQuery`, so the read
728
+ // gate + lazy-group guard run worker-side. Only `rowMode` crosses in the options (see the bridge executor).
729
+ guardedRawQuery: (sql, params, options, use) =>
730
+ rpc<Results>("guardedQuery", guardedQueryArgs(sql, params, options?.rowMode, use)),
674
731
  mutate: {
675
732
  create: (table, input) => rpc<void>("create", [table, input]),
676
733
  update: (table, entityKey, patch) => rpc<void>("update", [table, entityKey, patch]),
@@ -688,12 +745,42 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
688
745
  subscribeLiveRows,
689
746
  query: (sql, params) => rpc<Results>("rawQuery", [sql, params]),
690
747
  }),
691
- query: notSupported("client.query"),
692
- queryRow: notSupported("client.queryRow"),
693
- queryRaw: notSupported("client.queryRaw"),
694
- queryRawRow: notSupported("client.queryRawRow"),
695
- ensureSynced: notSupported("client.ensureSynced"),
696
- isSynced: notSupported("client.isSynced"),
748
+ // One-shot Drizzle reads (ADR-0032 decision 4) — proxied, mirroring the in-process shapes exactly. `build`
749
+ // runs against a client whose `drizzle` is a bridge database, so awaiting the builder executes the read via
750
+ // the `guardedQuery` RPC: the read gate + lazy-group guard run worker-side (no tab-side `prepareQuery`) and
751
+ // Drizzle's own mapping runs on the tab. The pure `query`/`queryRow` need no `use` (the worker's SQL scan
752
+ // finds every relation) and run against the base `client`. `queryRaw`/`queryRawRow` may embed a raw
753
+ // fragment naming a lazy relation the scan cannot see, so each runs against a `{ ...client, drizzle }`
754
+ // clone whose drizzle carries THAT call's `use` in its own executor — no shared state, no cross-read race.
755
+ query: (build) => Promise.resolve(build(client)),
756
+ queryRow: async (build) => {
757
+ const rows = await build(client);
758
+ return rows[0] ?? null;
759
+ },
760
+ queryRaw: ({ build, use }) => Promise.resolve(build({ ...client, drizzle: bridgeReadDrizzle(use) })),
761
+ queryRawRow: async ({ build, use }) => {
762
+ const rows = await build({ ...client, drizzle: bridgeReadDrizzle(use) });
763
+ return rows[0] ?? null;
764
+ },
765
+ // Lazy activation (ADR-0021) over the shared engine — a plain RPC. Activation is engine-WIDE, but unlike
766
+ // `desync` it is additive and idempotent: starting a group another tab already activated is a no-op, and
767
+ // it never reverts or truncates, so there is no cross-tab footgun. Resolves once the group's stream is
768
+ // started (catch-up may still be in flight — await `groupReady` for that), exactly as in-process.
769
+ ensureSynced: (keys) => rpc<void>("ensureSynced", [keys]),
770
+ // `isSynced` is the SYNCHRONOUS peek in-process (`isTableStarted` — is the group's stream STARTED). It
771
+ // cannot be an RPC (its signature returns a boolean, not a promise), and the tab's cached state cannot
772
+ // answer it: the bridge delivers per-group CATCH-UP readiness (`status.groups` / `groupReady`), which is
773
+ // strictly weaker than activation-started — an activated-but-not-yet-caught-up lazy group reads as
774
+ // not-ready, the very case `isSynced` exists to distinguish. So no faithful synchronous answer is derivable.
775
+ isSynced: () => {
776
+ throw new Error(
777
+ "[pgxsinkit] client.isSynced is not available on a worker-attached client: it is a SYNCHRONOUS " +
778
+ "activation-STARTED peek (in-process: isTableStarted), but the tab caches only per-group CATCH-UP " +
779
+ "readiness (status.groups / groupReady) — an activated-but-not-caught-up group reads as not-ready — " +
780
+ "so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " +
781
+ "client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.",
782
+ );
783
+ },
697
784
  // In SharedWorker mode the engine is SHARED, so a desync from one tab reverts the consistency group for
698
785
  // EVERY attached tab — inherent to desync's group-wide semantics (that footgun is why the narrower
699
786
  // `discardEphemeral` exists). The RPC runs the worker's real `desync` (same refusals as in-process).
@@ -804,6 +891,18 @@ export async function attachSyncClient<const TRegistry extends SyncTableRegistry
804
891
  },
805
892
  };
806
893
 
894
+ // The `pglite` misuse trap MUST be a NON-ENUMERABLE throwing getter, never an enumerable property
895
+ // holding a throw-on-get Proxy: host tooling reflects over the client wherever the app hands it around
896
+ // (React 19.2's dev-build render logging serializes prop diffs property-by-property — observed crashing
897
+ // a <SyncClientProvider client={...}> re-render — and console inspection / object spreads do the same),
898
+ // and an enumerable trap turns that passive reflection into a crash. Non-enumerable keeps the trap out
899
+ // of every enumeration path while a direct `client.pglite` touch still throws the misuse error.
900
+ Object.defineProperty(client, "pglite", {
901
+ get: notSupported("client.pglite"),
902
+ enumerable: false,
903
+ configurable: true,
904
+ });
905
+
807
906
  return client;
808
907
  }
809
908