@pgxsinkit/client 0.2.7 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +81 -0
  4. package/README.md +11 -3
  5. package/dist/boot-report.d.ts +11 -8
  6. package/dist/boot-report.d.ts.map +1 -1
  7. package/dist/circuits/envelope-to-change.d.ts +39 -0
  8. package/dist/circuits/envelope-to-change.d.ts.map +1 -0
  9. package/dist/circuits/group-sync.d.ts +123 -0
  10. package/dist/circuits/group-sync.d.ts.map +1 -0
  11. package/dist/circuits/shape-group.d.ts +77 -0
  12. package/dist/circuits/shape-group.d.ts.map +1 -0
  13. package/dist/circuits/stream-inbox.d.ts +126 -0
  14. package/dist/circuits/stream-inbox.d.ts.map +1 -0
  15. package/dist/circuits/stream-source.d.ts +96 -0
  16. package/dist/circuits/stream-source.d.ts.map +1 -0
  17. package/dist/circuits/subscription-client.d.ts +143 -0
  18. package/dist/circuits/subscription-client.d.ts.map +1 -0
  19. package/dist/circuits/sync-engine.d.ts +131 -0
  20. package/dist/circuits/sync-engine.d.ts.map +1 -0
  21. package/dist/debug.d.ts +0 -10
  22. package/dist/debug.d.ts.map +1 -1
  23. package/dist/event-lane.d.ts +32 -1
  24. package/dist/event-lane.d.ts.map +1 -1
  25. package/dist/export-data.d.ts +3 -3
  26. package/dist/export-dump.d.ts +9 -9
  27. package/dist/export-dump.d.ts.map +1 -1
  28. package/dist/export-store.d.ts +13 -13
  29. package/dist/index.d.ts +237 -113
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +7037 -6665
  32. package/dist/index.js.map +46 -43
  33. package/dist/local-store.d.ts +1 -1
  34. package/dist/local-store.d.ts.map +1 -1
  35. package/dist/local-tables.d.ts +59 -1
  36. package/dist/local-tables.d.ts.map +1 -1
  37. package/dist/mutation.d.ts +2 -2
  38. package/dist/mutation.d.ts.map +1 -1
  39. package/dist/mutations-api.d.ts.map +1 -1
  40. package/dist/opfs-effects.d.ts +30 -2
  41. package/dist/opfs-effects.d.ts.map +1 -1
  42. package/dist/schema.d.ts +12 -1
  43. package/dist/schema.d.ts.map +1 -1
  44. package/dist/store-boot.d.ts +30 -2
  45. package/dist/store-boot.d.ts.map +1 -1
  46. package/dist/store-build.d.ts +19 -0
  47. package/dist/store-build.d.ts.map +1 -0
  48. package/dist/store-engine.d.ts +22 -0
  49. package/dist/store-engine.d.ts.map +1 -0
  50. package/dist/store-meta.d.ts +29 -3
  51. package/dist/store-meta.d.ts.map +1 -1
  52. package/dist/store-ownership-lock.d.ts +33 -0
  53. package/dist/store-ownership-lock.d.ts.map +1 -0
  54. package/dist/store-path.d.ts +40 -28
  55. package/dist/store-path.d.ts.map +1 -1
  56. package/dist/sync/apply.d.ts +17 -25
  57. package/dist/sync/apply.d.ts.map +1 -1
  58. package/dist/sync/copy.d.ts +84 -8
  59. package/dist/sync/copy.d.ts.map +1 -1
  60. package/dist/sync/drizzle-executor.d.ts +4 -4
  61. package/dist/sync/drizzle-executor.d.ts.map +1 -1
  62. package/dist/sync/fold.d.ts +40 -0
  63. package/dist/sync/fold.d.ts.map +1 -0
  64. package/dist/sync/metadata-tables.d.ts +25 -1
  65. package/dist/sync/metadata-tables.d.ts.map +1 -1
  66. package/dist/sync/subscription-state.d.ts +26 -7
  67. package/dist/sync/subscription-state.d.ts.map +1 -1
  68. package/dist/sync/types.d.ts +9 -129
  69. package/dist/sync/types.d.ts.map +1 -1
  70. package/dist/testing.d.ts +1 -1
  71. package/dist/testing.js +4 -3
  72. package/dist/testing.js.map +4 -4
  73. package/dist/worker/attach-sync-client.d.ts +27 -14
  74. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  75. package/dist/worker/define-sync-worker.d.ts +52 -19
  76. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  77. package/dist/worker/engine-control.d.ts +53 -0
  78. package/dist/worker/engine-control.d.ts.map +1 -1
  79. package/dist/worker/live-query-manager.d.ts +3 -3
  80. package/dist/worker/live-query-manager.d.ts.map +1 -1
  81. package/dist/worker/live-query-params-guard.d.ts +5 -5
  82. package/dist/worker/protocol.d.ts +26 -7
  83. package/dist/worker/protocol.d.ts.map +1 -1
  84. package/package.json +11 -9
  85. package/skills/core/SKILL.md +145 -63
  86. package/skills/operating/SKILL.md +221 -221
  87. package/skills/operating/references/postgres-builds.md +48 -0
  88. package/src/boot-report.ts +13 -12
  89. package/src/circuits/envelope-to-change.ts +211 -0
  90. package/src/circuits/group-sync.ts +1047 -0
  91. package/src/circuits/shape-group.ts +158 -0
  92. package/src/circuits/stream-inbox.ts +225 -0
  93. package/src/circuits/stream-source.ts +191 -0
  94. package/src/circuits/subscription-client.ts +353 -0
  95. package/src/circuits/sync-engine.ts +643 -0
  96. package/src/debug.ts +1 -85
  97. package/src/event-lane.ts +132 -14
  98. package/src/export-data.ts +4 -4
  99. package/src/export-dump.ts +24 -28
  100. package/src/export-store.ts +17 -17
  101. package/src/index.ts +797 -544
  102. package/src/lazy-guard.ts +1 -1
  103. package/src/live-rows-sql.ts +1 -1
  104. package/src/local-store.ts +2 -2
  105. package/src/local-tables.ts +76 -5
  106. package/src/mutation.ts +9 -8
  107. package/src/mutations-api.ts +2 -2
  108. package/src/opfs-effects.ts +74 -10
  109. package/src/schema.ts +126 -29
  110. package/src/store-boot.ts +71 -7
  111. package/src/store-build.ts +37 -0
  112. package/src/store-engine.ts +94 -0
  113. package/src/store-lifecycle.ts +1 -1
  114. package/src/store-meta.ts +155 -4
  115. package/src/store-ownership-lock.ts +109 -0
  116. package/src/store-path.ts +56 -40
  117. package/src/sync/apply.ts +104 -156
  118. package/src/sync/copy.ts +116 -21
  119. package/src/sync/drizzle-executor.ts +13 -14
  120. package/src/sync/fold.ts +94 -0
  121. package/src/sync/metadata-tables.ts +43 -2
  122. package/src/sync/subscription-state.ts +28 -10
  123. package/src/sync/types.ts +13 -141
  124. package/src/testing.ts +4 -4
  125. package/src/worker/attach-sync-client.ts +150 -57
  126. package/src/worker/define-sync-worker.ts +325 -87
  127. package/src/worker/engine-control.ts +89 -0
  128. package/src/worker/engine-router.ts +1 -1
  129. package/src/worker/live-query-fingerprint.ts +4 -4
  130. package/src/worker/live-query-manager.ts +12 -12
  131. package/src/worker/live-query-params-guard.ts +10 -10
  132. package/src/worker/protocol.ts +38 -7
  133. package/dist/read-stream-stall.d.ts +0 -54
  134. package/dist/read-stream-stall.d.ts.map +0 -1
  135. package/dist/shape-sync.d.ts +0 -207
  136. package/dist/shape-sync.d.ts.map +0 -1
  137. package/dist/sync/index.d.ts +0 -32
  138. package/dist/sync/index.d.ts.map +0 -1
  139. package/dist/sync/nudge.d.ts +0 -49
  140. package/dist/sync/nudge.d.ts.map +0 -1
  141. package/dist/sync/shape-inbox.d.ts +0 -215
  142. package/dist/sync/shape-inbox.d.ts.map +0 -1
  143. package/dist/sync/tags.d.ts +0 -142
  144. package/dist/sync/tags.d.ts.map +0 -1
  145. package/dist/sync-auth.d.ts +0 -53
  146. package/dist/sync-auth.d.ts.map +0 -1
  147. package/src/read-stream-stall.ts +0 -102
  148. package/src/shape-sync.ts +0 -533
  149. package/src/sync/index.ts +0 -1124
  150. package/src/sync/nudge.ts +0 -110
  151. package/src/sync/shape-inbox.ts +0 -566
  152. package/src/sync/tags.ts +0 -390
  153. package/src/sync-auth.ts +0 -117
package/src/sync/apply.ts CHANGED
@@ -1,23 +1,22 @@
1
- // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
2
- // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
3
- import type { ChangeMessage, Row } from "@electric-sql/client";
4
- import type { PGliteInterface, Transaction } from "@electric-sql/pglite";
5
1
  import { and, eq, fillPlaceholders, type SQL, sql } from "drizzle-orm";
6
2
  import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
7
3
 
8
- import { quoteIdentifier, type SyncColumnType } from "@pgxsinkit/contracts";
4
+ import { jsonUdtName, quoteIdentifier, type SyncChange, type SyncColumnType, type SyncRow } from "@pgxsinkit/contracts";
5
+ // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).
6
+ // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
7
+ import type { Pgwasm, Transaction } from "@pgxsinkit/pgwasm";
9
8
 
10
9
  import type { ApplyTarget } from "../local-tables";
11
- import { generateCopyData } from "./copy";
10
+ import { buildCopyFromBlobStatement } from "./copy";
12
11
  import { drizzleOverPg } from "./drizzle-executor";
13
- import type { InsertChangeMessage } from "./types";
12
+ import type { UpsertChangeMessage } from "./types";
14
13
 
15
14
  /**
16
- * Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the
15
+ * Re-key a streamed change row (keyed by DB **column name**) to the Drizzle **property keys** the
17
16
  * query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a
18
17
  * config error and surfaces, rather than silently binding to nothing.
19
18
  */
20
- function toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {
19
+ function toDriverRow(target: ApplyTarget, data: SyncRow): Record<string, unknown> {
21
20
  const out: Record<string, unknown> = {};
22
21
  for (const name of Object.keys(data)) {
23
22
  const propertyKey = target.propertyKeyByName[name];
@@ -61,7 +60,7 @@ function hasGeneratedIdentityColumn(target: ApplyTarget, colNames: readonly stri
61
60
  * locally-generated one — so OVERRIDING SYSTEM VALUE is the semantically correct clause (and it makes
62
61
  * drizzle re-include the column it would otherwise drop). Tables without a generated column get a plain
63
62
  * 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
63
+ * PK as a PLAIN column — the generator emits `getSQLType()` with no identity clause — and pgwasm accepts
65
64
  * OVERRIDING SYSTEM VALUE against a plain column as a no-op, so this is safe there too.)
66
65
  */
67
66
  function insertInto(db: ReturnType<typeof drizzleOverPg>, target: ApplyTarget, colNames: readonly string[]) {
@@ -87,9 +86,9 @@ function castTypeFor(column: SyncColumnType, tableSchema: string | undefined): s
87
86
  }
88
87
 
89
88
  export interface ApplyMessageToTableOptions {
90
- pg: PGliteInterface | Transaction;
89
+ pg: Pgwasm | Transaction;
91
90
  target: ApplyTarget;
92
- message: ChangeMessage<Row<unknown>>;
91
+ message: SyncChange;
93
92
  debug: boolean;
94
93
  }
95
94
 
@@ -98,39 +97,18 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
98
97
  const db = drizzleOverPg(pg);
99
98
 
100
99
  switch (message.headers.operation) {
101
- case "insert": {
102
- if (debug) console.log("inserting", data);
100
+ case "upsert": {
101
+ if (debug) console.log("upserting", data);
103
102
  const columns = Object.keys(data);
103
+ // `insertInto` adds OVERRIDING SYSTEM VALUE when the row carries a GENERATED ALWAYS identity
104
+ // column, so the server's authoritative id is preserved rather than silently dropped.
104
105
  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 });
106
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
107
+ if (nonPkColumns.length > 0) {
108
+ return await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
115
109
  }
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;
122
- }
123
-
124
- case "update": {
125
- if (debug) console.log("updating", data);
126
- const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));
127
- if (setColumns.length === 0) return;
128
- const setValues: Record<string, unknown> = {};
129
- for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];
130
- return await db
131
- .update(target.table)
132
- .set(setValues as never)
133
- .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));
110
+ // Target the pk explicitly so a pk-only conflict is a no-op ONLY on the primary key.
111
+ return await insert.onConflictDoNothing({ target: conflictTarget });
134
112
  }
135
113
 
136
114
  case "delete": {
@@ -143,9 +121,9 @@ export async function applyMessageToTable({ pg, target, message, debug }: ApplyM
143
121
  }
144
122
 
145
123
  export interface BulkApplyMessagesToTableOptions {
146
- pg: PGliteInterface | Transaction;
124
+ pg: Pgwasm | Transaction;
147
125
  target: ApplyTarget;
148
- messages: InsertChangeMessage[];
126
+ messages: UpsertChangeMessage[];
149
127
  debug: boolean;
150
128
  }
151
129
 
@@ -185,11 +163,11 @@ function renderInsert(
185
163
  * byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.
186
164
  */
187
165
  async function executeInsertBatch(
188
- pg: PGliteInterface | Transaction,
166
+ pg: Pgwasm | Transaction,
189
167
  db: ReturnType<typeof drizzleOverPg>,
190
168
  target: ApplyTarget,
191
169
  colNames: string[],
192
- batch: Row<unknown>[],
170
+ batch: SyncRow[],
193
171
  ): Promise<void> {
194
172
  const rendered = renderInsert(db, target, colNames, batch.length);
195
173
  const values: Record<string, unknown> = {};
@@ -237,7 +215,7 @@ function getValueSize(value: unknown): number {
237
215
  }
238
216
  }
239
217
 
240
- function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
218
+ function getRowSize(row: SyncRow, columns: readonly string[]): number {
241
219
  return columns.reduce((size, column) => {
242
220
  const value = row[column];
243
221
  if (value === null) return size;
@@ -266,7 +244,7 @@ function getRowSize(row: Row<unknown>, columns: readonly string[]): number {
266
244
  }
267
245
 
268
246
  export async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
269
- const data: Row<unknown>[] = messages.map((message) => message.value);
247
+ const data: SyncRow[] = messages.map((message) => message.value);
270
248
  const firstRow = data[0];
271
249
  if (!firstRow) {
272
250
  return;
@@ -274,9 +252,10 @@ export async function applyInsertsToTable({ pg, target, messages, debug }: BulkA
274
252
 
275
253
  if (debug) console.log("inserting", data);
276
254
  const columns = Object.keys(firstRow);
255
+ assertUniformColumnSet(target, columns, data, "applyInsertsToTable");
277
256
  const db = drizzleOverPg(pg);
278
257
 
279
- let currentBatch: Row<unknown>[] = [];
258
+ let currentBatch: SyncRow[] = [];
280
259
  let currentBatchSize = 0;
281
260
  let currentBatchParams = 0;
282
261
 
@@ -336,23 +315,56 @@ function upsertConflictSpec(
336
315
  }
337
316
 
338
317
  /**
339
- * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the
340
- * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent
341
- * grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:
342
- * `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`
343
- * for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must
344
- * surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present
345
- * row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).
318
+ * Refuse a batch whose rows do not all carry the same columns.
319
+ *
320
+ * **Every** bulk applier here takes its column list from the FIRST row and binds the rest against it,
321
+ * so a batch with mixed column sets does not fail — it writes the wrong thing, differently per tier: a
322
+ * missing column binds `DEFAULT` on the param-bound paths (overwriting a real value with the column
323
+ * default on conflict) and NULL through `json_to_recordset`, while an extra column is silently dropped
324
+ * everywhere. So all four call sites assert, including the three backfill tiers — a corrupt initial
325
+ * load is the worse outcome of the two, not the lesser one.
326
+ *
327
+ * The wire makes a mixed batch impossible: `row_to_json_cols(row, out_cols)` emits every column of the
328
+ * shape's `out_cols` on every upsert, and `out_cols` is the local table's column set. This is a cheap
329
+ * check that the guarantee still holds, kept because ADR-0058 retired the primary-key collision that
330
+ * used to be the backstop for "the apply path silently wrote something wrong". O(rows × columns),
331
+ * against per-row serialization of the same order — nothing measurable next to the work it guards.
332
+ */
333
+ function assertUniformColumnSet(target: ApplyTarget, columns: string[], rows: SyncRow[], applier: string): void {
334
+ const expected = new Set(columns);
335
+ for (const row of rows) {
336
+ const keys = Object.keys(row);
337
+ if (keys.length === expected.size && keys.every((key) => expected.has(key))) continue;
338
+ const missing = columns.filter((column) => !(column in row));
339
+ const extra = keys.filter((key) => !expected.has(key));
340
+ throw new Error(
341
+ `[pgxsinkit] ${applier}: batch for ${getTableConfig(target.table).name} ` +
342
+ `mixes column sets — every row must carry the same columns as the first ` +
343
+ `(${columns.join(", ")})${missing.length > 0 ? `; missing ${missing.join(", ")}` : ""}` +
344
+ `${extra.length > 0 ? `; unexpected ${extra.join(", ")}` : ""}`,
345
+ );
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Bulk **upsert** — the applier for the wire's `upsert` verb (ADR-0058 decision 1). The engine states a
351
+ * row's new value rather than claiming anything about what preceded it, so an upsert routinely names a
352
+ * row already present locally: a subquery flip, a scope grant, a backfill replay, or a re-delivery on a
353
+ * resume from before its offset. So it is applied idempotently: `INSERT … ON CONFLICT (pk) DO UPDATE`
354
+ * refreshes to the authoritative value (or `DO NOTHING` for a pk-only table). The plain `INSERT` of the
355
+ * backfill path ({@link applyInsertsToTable}) is intentionally NOT used here, because a present row is
356
+ * expected, not a bug. Batched by parameter count (steady-state volume is incremental, not a backfill).
346
357
  */
347
358
  export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
348
359
  const primaryKey = target.primaryKey;
349
360
  if (primaryKey.length === 0) throw new Error("applyUpsertsToTable requires a primary key");
350
361
 
351
- const data: Row<unknown>[] = messages.map((message) => message.value);
362
+ const data: SyncRow[] = messages.map((message) => message.value);
352
363
  const firstRow = data[0];
353
364
  if (!firstRow) return;
354
365
 
355
366
  const columns = Object.keys(firstRow);
367
+ assertUniformColumnSet(target, columns, data, "applyUpsertsToTable");
356
368
  const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
357
369
 
358
370
  const perRow = columns.length;
@@ -388,7 +400,7 @@ interface JsonRecordsetColumn {
388
400
  * catalog probe: the types are always present, derived from the same Drizzle definitions the local
389
401
  * store was rendered from).
390
402
  */
391
- function jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {
403
+ function jsonRecordsetColumns(target: ApplyTarget, firstRow: SyncRow): JsonRecordsetColumn[] {
392
404
  const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);
393
405
  const { schema } = getTableConfig(target.table);
394
406
  return target.columnTypes
@@ -434,12 +446,18 @@ async function applyMessagesToTableWithJsonImpl(
434
446
  ) {
435
447
  if (debug) console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
436
448
 
437
- const data: Row<unknown>[] = messages.map((message) => message.value);
449
+ const data: SyncRow[] = messages.map((message) => message.value);
438
450
  const firstRow = data[0];
439
451
  if (!firstRow) {
440
452
  return;
441
453
  }
442
454
  const columns = jsonRecordsetColumns(target, firstRow);
455
+ assertUniformColumnSet(
456
+ target,
457
+ columns.map((column) => column.name),
458
+ data,
459
+ "applyMessagesToTableWithJson",
460
+ );
443
461
  const targetTable = target.table;
444
462
  // Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound
445
463
  // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,
@@ -487,19 +505,17 @@ export async function applyUpsertsToTableWithJson(options: BulkApplyMessagesToTa
487
505
 
488
506
  /**
489
507
  * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to
490
- * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by
491
- * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected
492
- * (ADR-0029 D2).
508
+ * disambiguate `json`/`jsonb` (whose decoded values are indistinguishable from SQL arrays/objects by
509
+ * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}) through the contracts'
510
+ * `jsonUdtName` — the same classifier the read path's json decode uses, so the serializer and the decode
511
+ * cannot disagree about which columns carry JSON — never introspected (ADR-0029 D2).
493
512
  */
494
513
  function copyColumnUdts(target: ApplyTarget): Record<string, string> {
495
514
  const map: Record<string, string> = {};
496
515
  for (const column of target.columnTypes) {
497
- const base = column.sqlType
498
- .replace(/\(.*\)/g, "")
499
- .trim()
500
- .toLowerCase();
501
- if (base === "json" || base === "jsonb") {
502
- map[column.name] = column.isArray ? `_${base}` : base;
516
+ const udt = jsonUdtName(column);
517
+ if (udt !== undefined) {
518
+ map[column.name] = udt;
503
519
  }
504
520
  }
505
521
  return map;
@@ -508,40 +524,29 @@ function copyColumnUdts(target: ApplyTarget): Record<string, string> {
508
524
  export async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
509
525
  if (debug) console.log("applying messages with COPY");
510
526
 
511
- const data: Row<unknown>[] = messages.map((message) => message.value);
527
+ const data: SyncRow[] = messages.map((message) => message.value);
512
528
  const firstRow = data[0];
513
529
  if (!firstRow) {
514
530
  return;
515
531
  }
516
532
  const columns = Object.keys(firstRow);
517
-
518
- // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's
519
- // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),
520
- // json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,
521
- // unlike the previous hand-rolled CSV encoder.
522
- const columnUdts = copyColumnUdts(target);
523
- const copyData = generateCopyData(data, columns, columnUdts);
524
- const copyBlob = new Blob([copyData], { type: "text/plain" });
525
-
526
- // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\N`, both of
527
- // which generateCopyData emits.
528
- //
529
- // Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no
530
- // Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real
531
- // synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.
532
- const { name: tableName, schema } = getTableConfig(target.table);
533
- const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);
534
- await pg.query(
535
- `
536
- COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(", ")})
537
- FROM '/dev/blob'
538
- WITH (FORMAT text)
539
- `,
540
- [],
541
- {
542
- blob: copyBlob,
543
- },
544
- );
533
+ assertUniformColumnSet(target, columns, data, "applyMessagesToTableWithCopy");
534
+
535
+ // ONE implementation of the COPY-from-blob load, shared with the public raw seam
536
+ // ({@link buildCopyFromBlobStatement}): it renders the tier-③ statement from the REAL table object
537
+ // (`getTableConfig` — a bare name for an ephemeral relation, schema-qualified otherwise) and serializes
538
+ // the rows with Postgres' own COPY TEXT format — a faithful port of the backend's CopyAttributeOutText /
539
+ // array_out routines (see ./copy) — so arrays (incl. multi-dimensional), json/jsonb, bytea, timestamps
540
+ // and strings with embedded delimiters/newlines all round-trip.
541
+ const statement = buildCopyFromBlobStatement({
542
+ table: target.table,
543
+ columns,
544
+ rows: data,
545
+ udtNames: copyColumnUdts(target),
546
+ });
547
+ // The statement carries its body as BYTES (that is what crosses the worker bridge as a transferable on
548
+ // the raw seam); pgwasm reads `/dev/blob` from a `Blob`, so wrap them here.
549
+ await pg.query(statement.sql, [], { blob: new Blob([statement.blob], { type: "text/plain" }) });
545
550
 
546
551
  if (debug) console.log(`Inserted ${messages.length} rows using COPY`);
547
552
  }
@@ -566,10 +571,10 @@ function recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonR
566
571
  }
567
572
 
568
573
  export interface BulkKeyedApplyOptions {
569
- pg: PGliteInterface | Transaction;
574
+ pg: Pgwasm | Transaction;
570
575
  target: ApplyTarget;
571
576
  /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */
572
- messages: ChangeMessage<Row<unknown>>[];
577
+ messages: SyncChange[];
573
578
  debug: boolean;
574
579
  }
575
580
 
@@ -609,60 +614,3 @@ export async function applyBulkDeletesToTable({ pg, target, messages, debug }: B
609
614
 
610
615
  if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);
611
616
  }
612
-
613
- /**
614
- * Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of
615
- * non-PK columns** each row carries. Electric's default replica sends only the changed columns, so
616
- * two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps
617
- * each statement uniform. Safe from the same-PK join hazard because the fold already left one row per
618
- * PK, so no PK appears twice within a group.
619
- */
620
- export async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
621
- const primaryKey = target.primaryKey;
622
- if (primaryKey.length === 0) throw new Error("applyBulkUpdatesToTable requires a primary key");
623
- if (messages.length === 0) return;
624
-
625
- const pkSet = new Set(primaryKey);
626
- const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();
627
- for (const message of messages) {
628
- const data = message.value;
629
- const setColumns = Object.keys(data)
630
- .filter((column) => !pkSet.has(column))
631
- .sort();
632
- // A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.
633
- if (setColumns.length === 0) continue;
634
- const groupKey = setColumns.join(" ");
635
- let group = groups.get(groupKey);
636
- if (!group) {
637
- group = { setColumns, rows: [] };
638
- groups.set(groupKey, group);
639
- }
640
- group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));
641
- }
642
-
643
- const targetTable = target.table;
644
- const db = drizzleOverPg(pg);
645
-
646
- for (const { setColumns, rows } of groups.values()) {
647
- const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);
648
- const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
649
- const setClause = setColumns
650
- .map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
651
- .join(", ");
652
- const whereJoin = primaryKey
653
- .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
654
- .join(" AND ");
655
-
656
- for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {
657
- const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);
658
- // Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound
659
- // `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /
660
- // `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).
661
- await db.execute(
662
- sql`UPDATE ${targetTable} AS t SET ${sql.raw(setClause)} FROM json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,
663
- );
664
- }
665
- }
666
-
667
- if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);
668
- }
package/src/sync/copy.ts CHANGED
@@ -1,18 +1,25 @@
1
- // Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —
2
- // specifically a port of the serializer from electric-sql/pglite PR #1035.
3
- // Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.
1
+ // Ports PostgreSQL's CopyAttributeOutText (src/backend/commands/copyto.c) and array_out
2
+ // (src/backend/utils/adt/arrayfuncs.c) — PostgreSQL License, © The PostgreSQL Global Development Group (see NOTICE).
4
3
  /**
5
4
  * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT
6
5
  * text)` stream.
7
6
  *
8
- * The Electric client parses the wire values it receives into native JS values
9
- * before they reach this module: `int2`/`int4`/`float4`/`float8` become
10
- * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`
11
- * become parsed objects/arrays, array columns become (possibly nested) JS
12
- * arrays, and every other type is left as its raw Postgres text representation
13
- * (a `string`). To feed those values back into `COPY` we have to reverse that:
14
- * turn each value into the exact text Postgres' input functions expect, then
15
- * apply the COPY framing.
7
+ * Values reach this module already decoded, so the runtime types it accepts are
8
+ * the decoded ones: `int2`/`int4`/`float4`/`float8` as `number`, `bool` as
9
+ * `boolean`, `json`/`jsonb` as parsed objects/arrays/scalars, `int8` as
10
+ * `bigint`, and every other type — **array columns included** — as its raw
11
+ * Postgres text representation (a `string`). To feed those values back into
12
+ * `COPY` we have to reverse that: turn each value into the exact text Postgres'
13
+ * input functions expect, then apply the COPY framing.
14
+ *
15
+ * Only the json ones are decoded on the way in, and by exactly one step:
16
+ * `envelopeToChange`'s `decodeJsonColumns` (`../circuits/envelope-to-change`).
17
+ * The wire itself carries EVERY non-int/float/bool cell as Postgres output text
18
+ * — a `jsonb` column included — so without that step the `JSON.stringify` below
19
+ * would encode already-encoded JSON a second time and the column would land as a
20
+ * JSON string scalar. An array column's `array_out` text is deliberately left
21
+ * alone: it passes through {@link valueToText} unchanged and `COPY`'s `array_in`
22
+ * parses it, which is why a `json[]` value here is a `string`, not a JS array.
16
23
  *
17
24
  * Rather than invent an escaping scheme (the previous CSV-based approach broke
18
25
  * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the
@@ -26,6 +33,12 @@
26
33
  * every built-in type.
27
34
  */
28
35
 
36
+ import { type AnyPgTable, getTableConfig } from "drizzle-orm/pg-core";
37
+
38
+ import { quoteIdentifier } from "@pgxsinkit/contracts";
39
+
40
+ import type { RawStatement } from "../index";
41
+
29
42
  // Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.
30
43
  const DELIMITER = "\t";
31
44
  const NULL_MARKER = "\\N";
@@ -53,8 +66,8 @@ function escapeCopyText(value: string): string {
53
66
 
54
67
  /**
55
68
  * Convert a Uint8Array to Postgres `bytea` hex-format text (`\xDEADBEEF`).
56
- * Electric normally delivers `bytea` already as such a string, so this only
57
- * matters for callers using a custom parser that yields binary.
69
+ * The read path normally delivers `bytea` already as such a string, so this only
70
+ * matters for a caller whose decoder yields binary.
58
71
  */
59
72
  function byteaToText(bytes: Uint8Array): string {
60
73
  let hex = "";
@@ -107,8 +120,8 @@ function arrayToText(arr: ReadonlyArray<unknown>): string {
107
120
 
108
121
  /**
109
122
  * Convert a non-null JS value to its bare Postgres text representation (before
110
- * COPY field escaping is applied). Dispatch is on the runtime type produced by
111
- * the Electric parser. `json`/`jsonb` columns are handled ahead of this by
123
+ * COPY field escaping is applied). Dispatch is on the value's decoded runtime
124
+ * type. `json`/`jsonb` columns are handled ahead of this by
112
125
  * `serializeCopyValue` when a column type is known; reaching the object branch
113
126
  * here is the type-less fallback.
114
127
  */
@@ -135,7 +148,7 @@ function valueToText(value: unknown): string {
135
148
  return JSON.stringify(value);
136
149
  }
137
150
  default:
138
- // Should be unreachable for Electric-parsed values; be defensive.
151
+ // Should be unreachable for decoded wire values; be defensive.
139
152
  return String(value);
140
153
  }
141
154
  }
@@ -152,11 +165,11 @@ function jsonArrayToText(arr: ReadonlyArray<unknown>): string {
152
165
  }
153
166
 
154
167
  /**
155
- * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric
156
- * delivers these columns already run through `JSON.parse`, so the value is the
157
- * decoded JS value (object, array, string, number, boolean or null) and always
158
- * needs `JSON.stringify` to become valid JSON input again — including scalars
159
- * (the string `hi` must be written as `"hi"`).
168
+ * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. These columns
169
+ * arrive already run through `JSON.parse` (the read path's `decodeJsonColumns`),
170
+ * so the value is the decoded JS value (object, array, string, number, boolean or
171
+ * null) and always needs `JSON.stringify` to become valid JSON input again —
172
+ * including scalars (the string `hi` must be written as `"hi"`).
160
173
  */
161
174
  function jsonToText(value: unknown): string {
162
175
  return JSON.stringify(value);
@@ -177,6 +190,14 @@ const JSON_ARRAY_UDT_NAMES = new Set(["_json", "_jsonb"]);
177
190
  * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates
178
191
  * `json`/`jsonb` columns; when omitted the value's runtime type is used (which
179
192
  * cannot tell a `jsonb` array from a SQL array).
193
+ *
194
+ * PUBLIC (re-exported from the package root) so an app that bulk-loads a table
195
+ * pgxsinkit does not manage writes the SAME COPY TEXT the applier does. The
196
+ * value contract is the one this module's header states: numbers/booleans/
197
+ * bigints as JS primitives, `json`/`jsonb` as **parsed** values (an object, an
198
+ * array, or a scalar — never pre-stringified JSON, which would land as a JSON
199
+ * string), a `Date` or its text for the temporal types, a JS array (or the
200
+ * Postgres array text) for an array column, and every other type as a `string`.
180
201
  */
181
202
  export function serializeCopyValue(value: unknown, udtName?: string): string {
182
203
  if (value === null || value === undefined) return NULL_MARKER;
@@ -194,6 +215,21 @@ export function serializeCopyValue(value: unknown, udtName?: string): string {
194
215
  *
195
216
  * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass
196
217
  * it so `json`/`jsonb` columns serialize correctly.
218
+ *
219
+ * PUBLIC (re-exported from the package root) for an app-owned, pgxsinkit-unmanaged
220
+ * table. Two contracts bind the caller:
221
+ *
222
+ * - **`columns` IS the column list of the COPY statement.** The fields are
223
+ * emitted in exactly this order, so the same array must be named — in the
224
+ * same order — in the `COPY <table> (...)` that ingests the bytes.
225
+ * {@link buildCopyFromBlobStatement} renders both from one array so they
226
+ * cannot drift.
227
+ * - **`columnTypes` keys are DB column names, values are Postgres `udt_name`s**
228
+ * (`text`, `int4`, `jsonb`, `timestamptz`, `_text` for `text[]`, …). Only the
229
+ * json ones (`json`/`jsonb`/`_json`/`_jsonb`) change behaviour — everything
230
+ * else dispatches on the value's runtime type — but passing the full map is
231
+ * harmless. A `json`/`jsonb` value MUST be the parsed value, per
232
+ * {@link serializeCopyValue}.
197
233
  */
198
234
  export function generateCopyData(
199
235
  rows: ReadonlyArray<Record<string, unknown>>,
@@ -204,3 +240,62 @@ export function generateCopyData(
204
240
  .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))
205
241
  .join(ROW_SEPARATOR);
206
242
  }
243
+
244
+ /** One shared UTF-8 encoder for the COPY TEXT body — `TextEncoder` is stateless, so module-level. */
245
+ const COPY_TEXT_ENCODER = new TextEncoder();
246
+
247
+ /** The inputs {@link buildCopyFromBlobStatement} renders a COPY-from-blob statement from. */
248
+ export interface CopyFromBlobStatementOptions {
249
+ /**
250
+ * The REAL Drizzle table object to load into — the identifier is read off it with `getTableConfig`,
251
+ * never taken as a hand-written string, so a rename can never leave a stale name in the SQL. A bare
252
+ * (schemaless) table renders unqualified and resolves through `search_path` (that is how the applier
253
+ * reaches an ephemeral relation in `pg_temp`).
254
+ */
255
+ table: AnyPgTable;
256
+ /**
257
+ * The DB column names to load, in order. ONE array drives both halves of the statement: the COPY
258
+ * column list and the field order of the serialized body, so they cannot drift.
259
+ */
260
+ columns: readonly string[];
261
+ /** The rows to load, keyed by DB column name (a key missing from a row is loaded as NULL). */
262
+ rows: ReadonlyArray<Record<string, unknown>>;
263
+ /**
264
+ * DB column name → Postgres `udt_name`, per {@link generateCopyData}. Needed for `json`/`jsonb`
265
+ * (and `_json`/`_jsonb`) columns; ignored for every other type.
266
+ */
267
+ udtNames?: Readonly<Record<string, string | undefined>>;
268
+ }
269
+
270
+ /**
271
+ * Render the `COPY <table> (<columns>) FROM '/dev/blob' WITH (FORMAT text)` statement for `rows`,
272
+ * together with the COPY TEXT bytes pgwasm must read for it — a {@link RawStatement} whose `blob`
273
+ * carries the body (narrowed to a non-optional `blob`: this builder ALWAYS produces one).
274
+ *
275
+ * This is the ONE implementation of the COPY-from-blob load: the sync applier's bulk path
276
+ * (`applyMessagesToTableWithCopy`) and the public raw seam both call it, so an app-owned table
277
+ * bulk-loads on exactly the contract the applier is tested against.
278
+ *
279
+ * Hand it to `rawTransaction` (to bulk-load inside one local transaction, e.g. delete-then-COPY) or
280
+ * to `rawQuery`'s `blob` option for a single statement. On a worker-attached client the bytes are
281
+ * TRANSFERRED, not copied — see {@link RawStatement.blob}: the buffer is detached after the call.
282
+ *
283
+ * Tier ③ (ADR-0028 allow-list), exactly as the applier's copy of this statement was: `COPY … FROM
284
+ * '/dev/blob'` is pgwasm's blob-ingest grammar and has NO Drizzle builder form, so the statement text
285
+ * stays a raw string. Every identifier in it is still derived — the table from `getTableConfig`, each
286
+ * column through `quoteIdentifier` — so nothing in the string is a hand-written identifier.
287
+ */
288
+ export function buildCopyFromBlobStatement({
289
+ table,
290
+ columns,
291
+ rows,
292
+ udtNames,
293
+ }: CopyFromBlobStatementOptions): RawStatement & { blob: Uint8Array<ArrayBuffer> } {
294
+ const { name: tableName, schema } = getTableConfig(table);
295
+ const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);
296
+ const columnList = columns.map((column) => quoteIdentifier(column)).join(", ");
297
+ // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\N`, both of
298
+ // which generateCopyData emits.
299
+ const sql = `COPY ${copyTarget} (${columnList}) FROM '/dev/blob' WITH (FORMAT text)`;
300
+ return { sql, params: [], blob: COPY_TEXT_ENCODER.encode(generateCopyData(rows, columns, udtNames)) };
301
+ }