@pgxsinkit/client 0.1.32 → 0.1.40
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/README.md +11 -0
- package/dist/boot-report.d.ts +134 -0
- package/dist/boot-report.d.ts.map +1 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/export-data.d.ts +100 -0
- package/dist/export-data.d.ts.map +1 -0
- package/dist/export-dump.d.ts +92 -0
- package/dist/export-dump.d.ts.map +1 -0
- package/dist/export-store.d.ts +214 -0
- package/dist/export-store.d.ts.map +1 -0
- package/dist/index.d.ts +615 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8083 -2286
- package/dist/index.js.map +81 -44
- package/dist/lazy-guard.d.ts +59 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/lifecycle-slot.d.ts +31 -0
- package/dist/lifecycle-slot.d.ts.map +1 -0
- package/dist/live-rows-sql.d.ts +21 -0
- package/dist/live-rows-sql.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +69 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +129 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +82 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +190 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/store-path.d.ts +132 -0
- package/dist/store-path.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +126 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +17 -0
- package/dist/testing.js.map +11 -0
- package/dist/worker/attach-sync-client.d.ts +96 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +76 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +341 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +20 -7
- package/skills/core/SKILL.md +210 -0
- package/skills/operating/SKILL.md +303 -0
- package/src/boot-report.ts +287 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/export-data.ts +300 -0
- package/src/export-dump.ts +239 -0
- package/src/export-store.ts +309 -0
- package/src/index.ts +1652 -51
- package/src/lazy-guard.ts +135 -0
- package/src/lifecycle-slot.ts +66 -0
- package/src/live-rows-sql.ts +45 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +99 -0
- package/src/mutation.ts +1910 -562
- package/src/schema.ts +472 -28
- package/src/shape-sync.ts +498 -0
- package/src/store-path.ts +249 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1087 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +141 -0
- package/src/sync-auth.ts +117 -0
- package/src/testing.ts +53 -0
- package/src/worker/attach-sync-client.ts +653 -0
- package/src/worker/define-sync-worker.ts +762 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +425 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,530 @@
|
|
|
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
|
+
import { and, eq, fillPlaceholders, sql } from "drizzle-orm";
|
|
6
|
+
import { getTableConfig, type PgColumn } from "drizzle-orm/pg-core";
|
|
7
|
+
|
|
8
|
+
import { quoteIdentifier } from "@pgxsinkit/contracts";
|
|
9
|
+
|
|
10
|
+
import type { ApplyTarget } from "../local-tables";
|
|
11
|
+
import { generateCopyData } from "./copy";
|
|
12
|
+
import { drizzleOverPg } from "./drizzle-executor";
|
|
13
|
+
import type { InsertChangeMessage } from "./types";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the
|
|
17
|
+
* query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a
|
|
18
|
+
* config error and surfaces, rather than silently binding to nothing.
|
|
19
|
+
*/
|
|
20
|
+
function toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {
|
|
21
|
+
const out: Record<string, unknown> = {};
|
|
22
|
+
for (const name of Object.keys(data)) {
|
|
23
|
+
const propertyKey = target.propertyKeyByName[name];
|
|
24
|
+
if (propertyKey === undefined) {
|
|
25
|
+
throw new Error(`sync apply: column ${JSON.stringify(name)} is not present on the local synced table`);
|
|
26
|
+
}
|
|
27
|
+
out[propertyKey] = data[name];
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The `PgColumn` for a DB column name on the target table (for `eq`/conflict-target/COPY clauses). */
|
|
33
|
+
function targetColumn(target: ApplyTarget, name: string): PgColumn {
|
|
34
|
+
const column = target.columnByName[name];
|
|
35
|
+
if (!column) {
|
|
36
|
+
throw new Error(`sync apply: column ${JSON.stringify(name)} not found on the local synced table`);
|
|
37
|
+
}
|
|
38
|
+
return column;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ApplyMessageToTableOptions {
|
|
42
|
+
pg: PGliteInterface | Transaction;
|
|
43
|
+
target: ApplyTarget;
|
|
44
|
+
message: ChangeMessage<Row<unknown>>;
|
|
45
|
+
debug: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions) {
|
|
49
|
+
const data = message.value;
|
|
50
|
+
const db = drizzleOverPg(pg);
|
|
51
|
+
|
|
52
|
+
switch (message.headers.operation) {
|
|
53
|
+
case "insert": {
|
|
54
|
+
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);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
case "update": {
|
|
61
|
+
if (debug) console.log("updating", data);
|
|
62
|
+
const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));
|
|
63
|
+
if (setColumns.length === 0) return;
|
|
64
|
+
const setValues: Record<string, unknown> = {};
|
|
65
|
+
for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];
|
|
66
|
+
return await db
|
|
67
|
+
.update(target.table)
|
|
68
|
+
.set(setValues as never)
|
|
69
|
+
.where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
case "delete": {
|
|
73
|
+
if (debug) console.log("deleting", data);
|
|
74
|
+
return await db
|
|
75
|
+
.delete(target.table)
|
|
76
|
+
.where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface BulkApplyMessagesToTableOptions {
|
|
82
|
+
pg: PGliteInterface | Transaction;
|
|
83
|
+
target: ApplyTarget;
|
|
84
|
+
messages: InsertChangeMessage[];
|
|
85
|
+
debug: boolean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const MAX_INSERT_PARAMS = 32_000;
|
|
89
|
+
const MAX_INSERT_BYTES = 50 * 1024 * 1024;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The rendered `{sqlText, params}` for a batched INSERT of `rowCount` rows over `colNames` (ADR-0029
|
|
93
|
+
* D5's render-once remedy). Rendered ONCE per distinct (column-set, row-count) via a placeholder INSERT
|
|
94
|
+
* over the real table, then reused for every batch of that shape — driving the per-row × per-column
|
|
95
|
+
* builder-AST cost to zero. `sql.placeholder` cells make Drizzle emit `$n` markers without applying a
|
|
96
|
+
* codec at render time; the codec is applied per value at execution (see {@link executeInsertBatch}).
|
|
97
|
+
*/
|
|
98
|
+
function renderInsert(
|
|
99
|
+
db: ReturnType<typeof drizzleOverPg>,
|
|
100
|
+
target: ApplyTarget,
|
|
101
|
+
colNames: string[],
|
|
102
|
+
rowCount: number,
|
|
103
|
+
): { sqlText: string; params: unknown[] } {
|
|
104
|
+
const key = JSON.stringify([rowCount, colNames]);
|
|
105
|
+
const cached = target.insertRenderCache.get(key);
|
|
106
|
+
if (cached) return cached;
|
|
107
|
+
const placeholderRows = Array.from({ length: rowCount }, (_, r) =>
|
|
108
|
+
Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),
|
|
109
|
+
);
|
|
110
|
+
const rendered = db
|
|
111
|
+
.insert(target.table)
|
|
112
|
+
.values(placeholderRows as never)
|
|
113
|
+
.toSQL();
|
|
114
|
+
const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };
|
|
115
|
+
target.insertRenderCache.set(key, value);
|
|
116
|
+
return value;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Execute one rendered batch: fill the render-once placeholders with this batch's values, applying the
|
|
121
|
+
* real per-column codec (`fillPlaceholders` runs each column's `mapToDriverValue`, with a null guard —
|
|
122
|
+
* byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.
|
|
123
|
+
*/
|
|
124
|
+
async function executeInsertBatch(
|
|
125
|
+
pg: PGliteInterface | Transaction,
|
|
126
|
+
db: ReturnType<typeof drizzleOverPg>,
|
|
127
|
+
target: ApplyTarget,
|
|
128
|
+
colNames: string[],
|
|
129
|
+
batch: Row<unknown>[],
|
|
130
|
+
): Promise<void> {
|
|
131
|
+
const rendered = renderInsert(db, target, colNames, batch.length);
|
|
132
|
+
const values: Record<string, unknown> = {};
|
|
133
|
+
for (let r = 0; r < batch.length; r++) {
|
|
134
|
+
const row = batch[r]!;
|
|
135
|
+
for (let ci = 0; ci < colNames.length; ci++) {
|
|
136
|
+
values[`${r}_${ci}`] = row[colNames[ci]!];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const flat = fillPlaceholders(rendered.params, values);
|
|
140
|
+
await pg.query(rendered.sqlText, flat as unknown[]);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
|
|
144
|
+
const data: Row<unknown>[] = messages.map((message) => message.value);
|
|
145
|
+
const firstRow = data[0];
|
|
146
|
+
if (!firstRow) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (debug) console.log("inserting", data);
|
|
151
|
+
const columns = Object.keys(firstRow);
|
|
152
|
+
const db = drizzleOverPg(pg);
|
|
153
|
+
|
|
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
|
+
let currentBatch: Row<unknown>[] = [];
|
|
217
|
+
let currentBatchSize = 0;
|
|
218
|
+
let currentBatchParams = 0;
|
|
219
|
+
|
|
220
|
+
for (const row of data) {
|
|
221
|
+
const rowSize = getRowSize(row);
|
|
222
|
+
const rowParams = columns.length;
|
|
223
|
+
|
|
224
|
+
if (
|
|
225
|
+
currentBatch.length > 0 &&
|
|
226
|
+
(currentBatchSize + rowSize > MAX_INSERT_BYTES || currentBatchParams + rowParams > MAX_INSERT_PARAMS)
|
|
227
|
+
) {
|
|
228
|
+
if (debug && currentBatchSize + rowSize > MAX_INSERT_BYTES) {
|
|
229
|
+
console.log("batch size limit exceeded, executing batch");
|
|
230
|
+
}
|
|
231
|
+
if (debug && currentBatchParams + rowParams > MAX_INSERT_PARAMS) {
|
|
232
|
+
console.log("batch params limit exceeded, executing batch");
|
|
233
|
+
}
|
|
234
|
+
await executeInsertBatch(pg, db, target, columns, currentBatch);
|
|
235
|
+
currentBatch = [];
|
|
236
|
+
currentBatchSize = 0;
|
|
237
|
+
currentBatchParams = 0;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
currentBatch.push(row);
|
|
241
|
+
currentBatchSize += rowSize;
|
|
242
|
+
currentBatchParams += rowParams;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (currentBatch.length > 0) {
|
|
246
|
+
await executeInsertBatch(pg, db, target, columns, currentBatch);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the
|
|
254
|
+
* shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent
|
|
255
|
+
* grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:
|
|
256
|
+
* `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`
|
|
257
|
+
* for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must
|
|
258
|
+
* surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present
|
|
259
|
+
* row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).
|
|
260
|
+
*/
|
|
261
|
+
export async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
|
|
262
|
+
const primaryKey = target.primaryKey;
|
|
263
|
+
if (primaryKey.length === 0) throw new Error("applyUpsertsToTable requires a primary key");
|
|
264
|
+
|
|
265
|
+
const data: Row<unknown>[] = messages.map((message) => message.value);
|
|
266
|
+
const firstRow = data[0];
|
|
267
|
+
if (!firstRow) return;
|
|
268
|
+
|
|
269
|
+
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
|
+
}
|
|
281
|
+
|
|
282
|
+
const perRow = columns.length;
|
|
283
|
+
const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));
|
|
284
|
+
const db = drizzleOverPg(pg);
|
|
285
|
+
|
|
286
|
+
for (let i = 0; i < data.length; i += rowsPerBatch) {
|
|
287
|
+
const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));
|
|
288
|
+
const insert = db.insert(target.table).values(batch as never);
|
|
289
|
+
if (nonPkColumns.length > 0) {
|
|
290
|
+
await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });
|
|
291
|
+
} else {
|
|
292
|
+
// Target the PK explicitly so a pk-only conflict is a no-op ONLY on the primary key — a bare
|
|
293
|
+
// `ON CONFLICT DO NOTHING` would swallow conflicts on any unique constraint.
|
|
294
|
+
await insert.onConflictDoNothing({ target: conflictTarget });
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (debug) console.log(`Upserted ${messages.length} move-in rows`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** A column's name plus the SQL type to cast it to inside a `json_to_recordset` record definition. */
|
|
302
|
+
interface JsonRecordsetColumn {
|
|
303
|
+
name: string;
|
|
304
|
+
castType: string;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The `json_to_recordset` casts for the rows being applied, narrowed to the columns actually present in
|
|
309
|
+
* the synced row, from the model-derived {@link ApplyTarget.columnTypes} (ADR-0029 D2 — never from a
|
|
310
|
+
* catalog probe: the types are always present, derived from the same Drizzle definitions the local
|
|
311
|
+
* store was rendered from).
|
|
312
|
+
*/
|
|
313
|
+
function jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {
|
|
314
|
+
const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);
|
|
315
|
+
return target.columnTypes
|
|
316
|
+
.filter((column) => present(column.name))
|
|
317
|
+
.map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` }));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
|
|
321
|
+
if (debug) console.log("applying messages with json_to_recordset");
|
|
322
|
+
|
|
323
|
+
const data: Row<unknown>[] = messages.map((message) => message.value);
|
|
324
|
+
const firstRow = data[0];
|
|
325
|
+
if (!firstRow) {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const columns = jsonRecordsetColumns(target, firstRow);
|
|
329
|
+
const targetTable = target.table;
|
|
330
|
+
// Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound
|
|
331
|
+
// param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,
|
|
332
|
+
// NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`
|
|
333
|
+
// record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and
|
|
334
|
+
// type names there, which no tier-①/② builder expresses.
|
|
335
|
+
const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
|
|
336
|
+
const db = drizzleOverPg(pg);
|
|
337
|
+
|
|
338
|
+
const max = 10_000;
|
|
339
|
+
for (let i = 0; i < data.length; i += max) {
|
|
340
|
+
const batch = data.slice(i, i + max);
|
|
341
|
+
await db.execute(
|
|
342
|
+
sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (debug) {
|
|
347
|
+
console.log(`Inserted ${messages.length} rows using json_to_recordset`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to
|
|
353
|
+
* disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by
|
|
354
|
+
* runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected
|
|
355
|
+
* (ADR-0029 D2).
|
|
356
|
+
*/
|
|
357
|
+
function copyColumnUdts(target: ApplyTarget): Record<string, string> {
|
|
358
|
+
const map: Record<string, string> = {};
|
|
359
|
+
for (const column of target.columnTypes) {
|
|
360
|
+
const base = column.sqlType
|
|
361
|
+
.replace(/\(.*\)/g, "")
|
|
362
|
+
.trim()
|
|
363
|
+
.toLowerCase();
|
|
364
|
+
if (base === "json" || base === "jsonb") {
|
|
365
|
+
map[column.name] = column.isArray ? `_${base}` : base;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return map;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {
|
|
372
|
+
if (debug) console.log("applying messages with COPY");
|
|
373
|
+
|
|
374
|
+
const data: Row<unknown>[] = messages.map((message) => message.value);
|
|
375
|
+
const firstRow = data[0];
|
|
376
|
+
if (!firstRow) {
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const columns = Object.keys(firstRow);
|
|
380
|
+
|
|
381
|
+
// Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's
|
|
382
|
+
// CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),
|
|
383
|
+
// json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,
|
|
384
|
+
// unlike the previous hand-rolled CSV encoder.
|
|
385
|
+
const columnUdts = copyColumnUdts(target);
|
|
386
|
+
const copyData = generateCopyData(data, columns, columnUdts);
|
|
387
|
+
const copyBlob = new Blob([copyData], { type: "text/plain" });
|
|
388
|
+
|
|
389
|
+
// TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\N`, both of
|
|
390
|
+
// which generateCopyData emits.
|
|
391
|
+
//
|
|
392
|
+
// Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no
|
|
393
|
+
// Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real
|
|
394
|
+
// synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.
|
|
395
|
+
const { name: tableName, schema } = getTableConfig(target.table);
|
|
396
|
+
const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);
|
|
397
|
+
await pg.query(
|
|
398
|
+
`
|
|
399
|
+
COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(", ")})
|
|
400
|
+
FROM '/dev/blob'
|
|
401
|
+
WITH (FORMAT text)
|
|
402
|
+
`,
|
|
403
|
+
[],
|
|
404
|
+
{
|
|
405
|
+
blob: copyBlob,
|
|
406
|
+
},
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
if (debug) console.log(`Inserted ${messages.length} rows using COPY`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const JSON_RECORDSET_BATCH = 10_000;
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* The `json_to_recordset` casts for an **explicit, ordered** column list — the bulk UPDATE/DELETE source
|
|
416
|
+
* relations need the PK columns (plus, for updates, the group's SET columns) in a known order. Derived
|
|
417
|
+
* from the model ({@link ApplyTarget.columnTypes}), never introspected (ADR-0029 D2).
|
|
418
|
+
*/
|
|
419
|
+
function recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {
|
|
420
|
+
const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
|
|
421
|
+
return columnNames.map((name) => {
|
|
422
|
+
const column = byName.get(name);
|
|
423
|
+
if (!column) {
|
|
424
|
+
throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);
|
|
425
|
+
}
|
|
426
|
+
return { name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` };
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export interface BulkKeyedApplyOptions {
|
|
431
|
+
pg: PGliteInterface | Transaction;
|
|
432
|
+
target: ApplyTarget;
|
|
433
|
+
/** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */
|
|
434
|
+
messages: ChangeMessage<Row<unknown>>[];
|
|
435
|
+
debug: boolean;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Bulk DELETE by primary key via `DELETE … USING json_to_recordset(…)` (ADR-0014 Phase 3). Safe
|
|
440
|
+
* because the read-path fold already left **one row per PK** — no same-PK duplicate in the source.
|
|
441
|
+
*/
|
|
442
|
+
export async function applyBulkDeletesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
|
|
443
|
+
const primaryKey = target.primaryKey;
|
|
444
|
+
if (primaryKey.length === 0) throw new Error("applyBulkDeletesToTable requires a primary key");
|
|
445
|
+
if (messages.length === 0) return;
|
|
446
|
+
|
|
447
|
+
const rows = messages.map((message) => {
|
|
448
|
+
const data = message.value;
|
|
449
|
+
return Object.fromEntries(primaryKey.map((column) => [column, data[column]]));
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
const casts = recordsetColumnCasts(target, primaryKey);
|
|
453
|
+
const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
|
|
454
|
+
const whereJoin = primaryKey
|
|
455
|
+
.map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
|
|
456
|
+
.join(" AND ");
|
|
457
|
+
const targetTable = target.table;
|
|
458
|
+
const db = drizzleOverPg(pg);
|
|
459
|
+
|
|
460
|
+
for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {
|
|
461
|
+
const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);
|
|
462
|
+
// Tier ② (ADR-0028): the target table is an interpolated table object; the pk-projection batch is a
|
|
463
|
+
// single bound param (`sql.param` binds the raw JS array unchanged — as the old `[batch]` did, and
|
|
464
|
+
// NOT `JSON.stringify`, which would throw on bigint pks). No cast is needed — `json_to_recordset`
|
|
465
|
+
// has a single json-typed signature. The `x(col type, …)` record definition and the alias-qualified
|
|
466
|
+
// `t.*`/`x.*` join are raw text: the `USING`/recordset-join grammar requires those bare identifiers.
|
|
467
|
+
await db.execute(
|
|
468
|
+
sql`DELETE FROM ${targetTable} AS t USING json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of
|
|
477
|
+
* non-PK columns** each row carries. Electric's default replica sends only the changed columns, so
|
|
478
|
+
* two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps
|
|
479
|
+
* each statement uniform. Safe from the same-PK join hazard because the fold already left one row per
|
|
480
|
+
* PK, so no PK appears twice within a group.
|
|
481
|
+
*/
|
|
482
|
+
export async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {
|
|
483
|
+
const primaryKey = target.primaryKey;
|
|
484
|
+
if (primaryKey.length === 0) throw new Error("applyBulkUpdatesToTable requires a primary key");
|
|
485
|
+
if (messages.length === 0) return;
|
|
486
|
+
|
|
487
|
+
const pkSet = new Set(primaryKey);
|
|
488
|
+
const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();
|
|
489
|
+
for (const message of messages) {
|
|
490
|
+
const data = message.value;
|
|
491
|
+
const setColumns = Object.keys(data)
|
|
492
|
+
.filter((column) => !pkSet.has(column))
|
|
493
|
+
.sort();
|
|
494
|
+
// A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.
|
|
495
|
+
if (setColumns.length === 0) continue;
|
|
496
|
+
const groupKey = setColumns.join(" ");
|
|
497
|
+
let group = groups.get(groupKey);
|
|
498
|
+
if (!group) {
|
|
499
|
+
group = { setColumns, rows: [] };
|
|
500
|
+
groups.set(groupKey, group);
|
|
501
|
+
}
|
|
502
|
+
group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const targetTable = target.table;
|
|
506
|
+
const db = drizzleOverPg(pg);
|
|
507
|
+
|
|
508
|
+
for (const { setColumns, rows } of groups.values()) {
|
|
509
|
+
const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);
|
|
510
|
+
const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(", ");
|
|
511
|
+
const setClause = setColumns
|
|
512
|
+
.map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
|
|
513
|
+
.join(", ");
|
|
514
|
+
const whereJoin = primaryKey
|
|
515
|
+
.map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)
|
|
516
|
+
.join(" AND ");
|
|
517
|
+
|
|
518
|
+
for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {
|
|
519
|
+
const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);
|
|
520
|
+
// Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound
|
|
521
|
+
// `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /
|
|
522
|
+
// `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).
|
|
523
|
+
await db.execute(
|
|
524
|
+
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)}`,
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);
|
|
530
|
+
}
|