@pgxsinkit/client 0.1.51 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +22 -0
  2. package/dist/adoption.d.ts +118 -0
  3. package/dist/adoption.d.ts.map +1 -0
  4. package/dist/boot-report.d.ts +54 -15
  5. package/dist/boot-report.d.ts.map +1 -1
  6. package/dist/convergence.d.ts +2 -1
  7. package/dist/convergence.d.ts.map +1 -1
  8. package/dist/error-chain.d.ts +9 -0
  9. package/dist/error-chain.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts.map +1 -1
  11. package/dist/export-store.d.ts +1 -1
  12. package/dist/export-store.d.ts.map +1 -1
  13. package/dist/index.d.ts +309 -38
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +4628 -1489
  16. package/dist/index.js.map +36 -24
  17. package/dist/live-rows-sql.d.ts +1 -1
  18. package/dist/local-store.d.ts +16 -31
  19. package/dist/local-store.d.ts.map +1 -1
  20. package/dist/local-tables.d.ts +10 -4
  21. package/dist/local-tables.d.ts.map +1 -1
  22. package/dist/mutation.d.ts +12 -15
  23. package/dist/mutation.d.ts.map +1 -1
  24. package/dist/opfs-effects.d.ts +51 -0
  25. package/dist/opfs-effects.d.ts.map +1 -0
  26. package/dist/placement-probe.d.ts +75 -0
  27. package/dist/placement-probe.d.ts.map +1 -0
  28. package/dist/schema.d.ts +11 -16
  29. package/dist/schema.d.ts.map +1 -1
  30. package/dist/store-boot.d.ts +77 -0
  31. package/dist/store-boot.d.ts.map +1 -0
  32. package/dist/store-lifecycle.d.ts +153 -0
  33. package/dist/store-lifecycle.d.ts.map +1 -0
  34. package/dist/store-meta.d.ts +190 -0
  35. package/dist/store-meta.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +77 -7
  37. package/dist/store-path.d.ts.map +1 -1
  38. package/dist/sync/apply.d.ts +12 -1
  39. package/dist/sync/apply.d.ts.map +1 -1
  40. package/dist/sync/index.d.ts.map +1 -1
  41. package/dist/sync/shape-inbox.d.ts +1 -1
  42. package/dist/sync/types.d.ts +3 -3
  43. package/dist/testing.js.map +3 -3
  44. package/dist/worker/attach-sync-client.d.ts +239 -13
  45. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  46. package/dist/worker/define-sync-worker.d.ts +162 -5
  47. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  48. package/dist/worker/election-coordinator.d.ts +95 -0
  49. package/dist/worker/election-coordinator.d.ts.map +1 -0
  50. package/dist/worker/engine-control.d.ts +265 -0
  51. package/dist/worker/engine-control.d.ts.map +1 -0
  52. package/dist/worker/engine-router.d.ts +75 -0
  53. package/dist/worker/engine-router.d.ts.map +1 -0
  54. package/dist/worker/live-query-manager.d.ts.map +1 -1
  55. package/dist/worker/live-query-params-guard.d.ts +14 -0
  56. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  57. package/dist/worker/protocol.d.ts +32 -11
  58. package/dist/worker/protocol.d.ts.map +1 -1
  59. package/dist/worker/sw-placement.d.ts +37 -0
  60. package/dist/worker/sw-placement.d.ts.map +1 -0
  61. package/package.json +4 -3
  62. package/skills/core/SKILL.md +15 -8
  63. package/skills/operating/SKILL.md +114 -34
  64. package/src/adoption.ts +275 -0
  65. package/src/boot-report.ts +70 -17
  66. package/src/convergence.ts +2 -1
  67. package/src/error-chain.ts +26 -0
  68. package/src/export-dump.ts +5 -1
  69. package/src/export-store.ts +1 -1
  70. package/src/index.ts +1246 -118
  71. package/src/live-rows-sql.ts +1 -1
  72. package/src/local-store.ts +18 -40
  73. package/src/local-tables.ts +9 -2
  74. package/src/mutation.ts +67 -49
  75. package/src/mutations-api.ts +3 -3
  76. package/src/opfs-effects.ts +160 -0
  77. package/src/placement-probe.ts +168 -0
  78. package/src/schema.ts +17 -22
  79. package/src/store-boot.ts +343 -0
  80. package/src/store-lifecycle.ts +227 -0
  81. package/src/store-meta.ts +459 -0
  82. package/src/store-path.ts +197 -22
  83. package/src/sync/apply.ts +227 -89
  84. package/src/sync/index.ts +33 -9
  85. package/src/sync/shape-inbox.ts +1 -1
  86. package/src/sync/types.ts +3 -3
  87. package/src/testing.ts +2 -2
  88. package/src/worker/attach-sync-client.ts +1675 -117
  89. package/src/worker/define-sync-worker.ts +810 -50
  90. package/src/worker/election-coordinator.ts +462 -0
  91. package/src/worker/engine-control.ts +379 -0
  92. package/src/worker/engine-router.ts +355 -0
  93. package/src/worker/live-query-manager.ts +10 -1
  94. package/src/worker/live-query-params-guard.ts +57 -0
  95. package/src/worker/protocol.ts +41 -10
  96. package/src/worker/sw-placement.ts +64 -0
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[] };
@@ -140,6 +203,68 @@ async function executeInsertBatch(
140
203
  await pg.query(rendered.sqlText, flat as unknown[]);
141
204
  }
142
205
 
206
+ function getValueSize(value: unknown): number {
207
+ if (value === null) return 0;
208
+ if (value instanceof ArrayBuffer) return value.byteLength;
209
+ if (value instanceof Blob) return value.size;
210
+ if (value instanceof Uint8Array) return value.byteLength;
211
+ if (value instanceof DataView) return value.byteLength;
212
+ if (ArrayBuffer.isView(value)) return value.byteLength;
213
+
214
+ switch (typeof value) {
215
+ case "string":
216
+ return value.length;
217
+ case "number":
218
+ return 8;
219
+ case "boolean":
220
+ return 1;
221
+ case "bigint":
222
+ case "symbol":
223
+ return value.toString().length;
224
+ case "function":
225
+ case "undefined":
226
+ return 0;
227
+ default: {
228
+ // Remaining typeof: object (null was handled above).
229
+ if (value instanceof Date) return 8;
230
+ try {
231
+ return JSON.stringify(value)?.length ?? 0;
232
+ } catch {
233
+ // Non-serialisable nested value (e.g. bigint inside jsonb).
234
+ return 16;
235
+ }
236
+ }
237
+ }
238
+ }
239
+
240
+ function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
241
+ return columns.reduce((size, column) => {
242
+ const value = row[column];
243
+ if (value === null) return size;
244
+
245
+ if (Array.isArray(value)) {
246
+ if (value.length === 0) return size;
247
+ const firstElement = value[0];
248
+
249
+ switch (typeof firstElement) {
250
+ case "number":
251
+ return size + value.length * 8;
252
+ case "string":
253
+ return size + value.reduce((arrSize, str) => arrSize + str.length, 0);
254
+ case "boolean":
255
+ return size + value.length;
256
+ default:
257
+ if (firstElement instanceof Date) {
258
+ return size + value.length * 8;
259
+ }
260
+ return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);
261
+ }
262
+ }
263
+
264
+ return size + getValueSize(value);
265
+ }, 0);
266
+ }
267
+
143
268
  export async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
144
269
  const data: Row<unknown>[] = messages.map((message) => message.value);
145
270
  const firstRow = data[0];
@@ -151,74 +276,12 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
151
276
  const columns = Object.keys(firstRow);
152
277
  const db = drizzleOverPg(pg);
153
278
 
154
- const getValueSize = (value: unknown): number => {
155
- if (value === null) return 0;
156
- if (value instanceof ArrayBuffer) return value.byteLength;
157
- if (value instanceof Blob) return value.size;
158
- if (value instanceof Uint8Array) return value.byteLength;
159
- if (value instanceof DataView) return value.byteLength;
160
- if (ArrayBuffer.isView(value)) return value.byteLength;
161
-
162
- switch (typeof value) {
163
- case "string":
164
- return value.length;
165
- case "number":
166
- return 8;
167
- case "boolean":
168
- return 1;
169
- case "bigint":
170
- case "symbol":
171
- return value.toString().length;
172
- case "function":
173
- case "undefined":
174
- return 0;
175
- default: {
176
- // Remaining typeof: object (null was handled above).
177
- if (value instanceof Date) return 8;
178
- try {
179
- return JSON.stringify(value)?.length ?? 0;
180
- } catch {
181
- // Non-serialisable nested value (e.g. bigint inside jsonb).
182
- return 16;
183
- }
184
- }
185
- }
186
- };
187
-
188
- const getRowSize = (row: Row<unknown>): number => {
189
- return columns.reduce((size, column) => {
190
- const value = row[column];
191
- if (value === null) return size;
192
-
193
- if (Array.isArray(value)) {
194
- if (value.length === 0) return size;
195
- const firstElement = value[0];
196
-
197
- switch (typeof firstElement) {
198
- case "number":
199
- return size + value.length * 8;
200
- case "string":
201
- return size + value.reduce((arrSize, str) => arrSize + str.length, 0);
202
- case "boolean":
203
- return size + value.length;
204
- default:
205
- if (firstElement instanceof Date) {
206
- return size + value.length * 8;
207
- }
208
- return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);
209
- }
210
- }
211
-
212
- return size + getValueSize(value);
213
- }, 0);
214
- };
215
-
216
279
  let currentBatch: Row<unknown>[] = [];
217
280
  let currentBatchSize = 0;
218
281
  let currentBatchParams = 0;
219
282
 
220
283
  for (const row of data) {
221
- const rowSize = getRowSize(row);
284
+ const rowSize = getRowSize(row, columns);
222
285
  const rowParams = columns.length;
223
286
 
224
287
  if (
@@ -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) }));
318
397
  }
319
398
 
320
- export async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
321
- if (debug) console.log("applying messages with json_to_recordset");
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}`;
422
+ }
423
+
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,
@@ -900,8 +924,8 @@ export async function createSyncEngine(pg: PGliteInterface, options?: ElectricSy
900
924
  if (debug) {
901
925
  console.log("received must-refetch", message);
902
926
  }
903
- // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`
904
- // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot
927
+ // Surface the expired-handle / rewind event on the syncDebug rail too (the `debug` option only
928
+ // console.logs it): must-refetch is the trigger for the truncate + re-snapshot
905
929
  // recovery, so it must be visible when diagnosing a convergence loss in a live app.
906
930
  syncDebug("must-refetch received", { shape: message.shape });
907
931
  inbox.resetShape(message.shape);
@@ -504,7 +504,7 @@ function mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {
504
504
  *
505
505
  * - **trailing `delete`** ⇒ a single DELETE;
506
506
  * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values
507
- * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);
507
+ * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert);
508
508
  * - **only `update`s** ⇒ a single UPDATE with merged values;
509
509
  * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the
510
510
  * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT
package/src/sync/types.ts CHANGED
@@ -56,9 +56,9 @@ export interface SyncShapesToTablesOptions {
56
56
  * SESSION-scoped — stored in the engine's `pg_temp` metadata relations that die with the engine, not the
57
57
  * durable ones. Set for an `ephemeral`-retention group, whose whole cluster is already TEMP: the cursor
58
58
  * and tags then die with the rows they index, so a returning engine re-streams the shape from scratch
59
- * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — every
60
- * persistent group's storage is byte-identical to before. One storage-scope bit; the engine never learns
61
- * the retention model.
59
+ * instead of resuming a stale durable cursor over a recreated-empty TEMP cluster. Default `false` — a
60
+ * persistent group's storage is identical whether the bit is `false` or unset; it only scopes an
61
+ * ephemeral group's bookkeeping. One storage-scope bit; the engine never learns the retention model.
62
62
  */
63
63
  sessionScoped?: boolean | undefined;
64
64
  initialInsertMethod?: InitialInsertMethod | undefined;
package/src/testing.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  // The helpers mint plain options objects that ALSO carry the module-internal {@link TEST_STORE_BACKEND}
12
12
  // marker at runtime — invisible in the public return type. Consumers SPREAD them into the client options:
13
13
  //
14
- // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, writeUrl })
15
- // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, writeUrl })
14
+ // createSyncClient({ ...memoryStoreForTests("my-test"), registry, electricUrl, batchWriteUrl })
15
+ // createSyncClient({ ...testStoreAcknowledgment(), pgliteInstance, registry, electricUrl, batchWriteUrl })
16
16
 
17
17
  import { TEST_STORE_BACKEND } from "./store-path";
18
18