@pgxsinkit/client 0.1.51 → 0.1.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/error-chain.d.ts +9 -0
- package/dist/error-chain.d.ts.map +1 -0
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +66 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +213 -55
- package/dist/index.js.map +15 -13
- package/dist/local-tables.d.ts +6 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +12 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts +4 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +41 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +14 -0
- package/dist/worker/live-query-params-guard.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +17 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/core/SKILL.md +6 -2
- package/skills/operating/SKILL.md +28 -5
- package/src/error-chain.ts +26 -0
- package/src/export-dump.ts +5 -1
- package/src/index.ts +175 -41
- package/src/local-tables.ts +7 -0
- package/src/sync/apply.ts +164 -26
- package/src/sync/index.ts +31 -7
- package/src/worker/attach-sync-client.ts +119 -20
- package/src/worker/define-sync-worker.ts +112 -2
- package/src/worker/live-query-manager.ts +6 -0
- package/src/worker/live-query-params-guard.ts +57 -0
- package/src/worker/protocol.ts +28 -0
|
@@ -7,10 +7,13 @@
|
|
|
7
7
|
// port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
|
|
8
8
|
// port, so no real Worker is needed to exercise the whole protocol.
|
|
9
9
|
|
|
10
|
+
import { type ParserOptions, type QueryOptions, types } from "@electric-sql/pglite";
|
|
11
|
+
|
|
10
12
|
import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
|
|
11
13
|
|
|
12
14
|
import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
|
|
13
15
|
import { setSyncDebugSink, syncDebug } from "../debug";
|
|
16
|
+
import { describeErrorChain } from "../error-chain";
|
|
14
17
|
import {
|
|
15
18
|
type ClientPGlite,
|
|
16
19
|
createClientPGlite,
|
|
@@ -40,6 +43,7 @@ import {
|
|
|
40
43
|
type BridgeEvent,
|
|
41
44
|
type BridgePort,
|
|
42
45
|
type ExportArtefactWire,
|
|
46
|
+
type GuardedQueryWireArgs,
|
|
43
47
|
identityCodec,
|
|
44
48
|
isBridgeEnvelope,
|
|
45
49
|
postBridgeMessage,
|
|
@@ -52,6 +56,29 @@ import {
|
|
|
52
56
|
} from "./protocol";
|
|
53
57
|
import { createWorkerTokenCache } from "./token-cache";
|
|
54
58
|
|
|
59
|
+
// The identity-parser map a guarded bridge read re-applies before executing (ADR-0032 decision 4). It
|
|
60
|
+
// MIRRORS the fixed `parsers` constant in `drizzle-orm/pglite`'s session VERBATIM (pinned to
|
|
61
|
+
// drizzle-orm@1.0.0-rc.4, `drizzle-orm/pglite/session.js`): identity parsers so the listed OIDs come back as
|
|
62
|
+
// raw STRINGS — exactly what the in-process drizzle session receives, because it passes this same map into
|
|
63
|
+
// `pglite.query`. The members are: the scalar OIDs `types.TIMESTAMP` / `TIMESTAMPTZ` / `INTERVAL` / `DATE`,
|
|
64
|
+
// and the array OIDs 1115 = `timestamp[]`, 1185 = `timestamptz[]`, 1187 = `interval[]`, 1182 = `date[]`, and
|
|
65
|
+
// 1231 = `numeric[]` (NOT temporal — drizzle's list is mirrored verbatim, whatever its members). Over the
|
|
66
|
+
// bridge the map is FUNCTIONS (non-serializable), so the attach side strips the options down to `rowMode`
|
|
67
|
+
// and this worker re-applies the identical map. We do NOT import drizzle's private constant — this is a
|
|
68
|
+
// deliberate, version-pinned mirror.
|
|
69
|
+
const identityParser = (value: string): string => value;
|
|
70
|
+
const DRIZZLE_PGLITE_IDENTITY_PARSERS: ParserOptions = {
|
|
71
|
+
[types.TIMESTAMP]: identityParser,
|
|
72
|
+
[types.TIMESTAMPTZ]: identityParser,
|
|
73
|
+
[types.INTERVAL]: identityParser,
|
|
74
|
+
[types.DATE]: identityParser,
|
|
75
|
+
1231: identityParser,
|
|
76
|
+
1115: identityParser,
|
|
77
|
+
1185: identityParser,
|
|
78
|
+
1187: identityParser,
|
|
79
|
+
1182: identityParser,
|
|
80
|
+
};
|
|
81
|
+
|
|
55
82
|
export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
56
83
|
/**
|
|
57
84
|
* The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
|
|
@@ -74,6 +101,21 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
74
101
|
* Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
|
|
75
102
|
*/
|
|
76
103
|
createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
|
|
104
|
+
/**
|
|
105
|
+
* Relax PGlite's per-query durability for every store this worker mints (default `true`; ADR-0047). A
|
|
106
|
+
* worker-ENTRY option (baked into the worker file as code, like {@link convergenceIntervalMs}), NOT an
|
|
107
|
+
* attach option — a tab cannot set it. Forwarded to the worker's default {@link createPglite} factory (the
|
|
108
|
+
* provision/spare mint) AND to the {@link createSyncClient} boot, so it governs whichever path mints the
|
|
109
|
+
* store. Ignored when a custom {@link createPglite} is injected (that factory owns its own create).
|
|
110
|
+
*
|
|
111
|
+
* On PGlite's idb backend the per-query synchronous flush to IndexedDB dominates local write latency, so
|
|
112
|
+
* the toolkit defaults to relaxed: the query returns before the flush and the flush is scheduled
|
|
113
|
+
* asynchronously. Loss window: only the writes not yet covered by a completed flush (typically the last one or two under human-rate input) can be at risk, and only on a
|
|
114
|
+
* crash before BOTH their journal rows reach the write API (within ~hundreds of ms of enqueue) AND the
|
|
115
|
+
* scheduled idb flush lands — synced tables are recoverable from the server by construction, so this
|
|
116
|
+
* relaxes flush TIMING, not persistence (ADR-0036). Opt out with `relaxedDurability: false`.
|
|
117
|
+
*/
|
|
118
|
+
relaxedDurability?: boolean;
|
|
77
119
|
electricUrl: string;
|
|
78
120
|
writeUrl: string;
|
|
79
121
|
/** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
|
|
@@ -109,6 +151,32 @@ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
|
|
|
109
151
|
precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
|
|
110
152
|
/** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
|
|
111
153
|
pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
|
|
154
|
+
/**
|
|
155
|
+
* App-level schema prep run IN THE WORKER, against the engine's own local store, BEFORE the registry
|
|
156
|
+
* schema exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDbBeforeSchema}, same
|
|
157
|
+
* timing as the in-process client. This is a worker-ENTRY option (baked into the worker file as code),
|
|
158
|
+
* NOT an attach option: the hook is a function and functions cannot cross the bridge, so a tab can never
|
|
159
|
+
* supply it — the worker owns it. Use it for DDL that must precede the registry's local tables (extensions,
|
|
160
|
+
* a bespoke schema search_path). On a fresh store the registry-derived local tables do NOT yet exist when
|
|
161
|
+
* this runs (that ordering is what distinguishes it from {@link prepareLocalDb}).
|
|
162
|
+
*
|
|
163
|
+
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
164
|
+
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there). On a restore boot it still
|
|
165
|
+
* runs, but the store already carries the registry tables from the backup's datadir, so the "tables absent"
|
|
166
|
+
* invariant does not hold there.
|
|
167
|
+
*/
|
|
168
|
+
prepareLocalDbBeforeSchema?: CreateSyncClientOptions<TRegistry>["prepareLocalDbBeforeSchema"];
|
|
169
|
+
/**
|
|
170
|
+
* App-level schema prep run IN THE WORKER, against the engine's own local store, AFTER the registry schema
|
|
171
|
+
* exec — forwarded verbatim to {@link CreateSyncClientOptions.prepareLocalDb}, same timing as the in-process
|
|
172
|
+
* client. Like {@link prepareLocalDbBeforeSchema} this is a worker-ENTRY option, never an attach option (the
|
|
173
|
+
* tab never sees it — functions cannot cross the bridge). Use it for app-level indexes, views, or migrations
|
|
174
|
+
* that depend on the registry's local tables, which DO exist by the time this runs.
|
|
175
|
+
*
|
|
176
|
+
* Runs on the storePath, {@link precreatedPglite}, and restore boots; SKIPPED entirely on the
|
|
177
|
+
* {@link pgliteInstance} path (the caller owns schema/prepare/reconcile there).
|
|
178
|
+
*/
|
|
179
|
+
prepareLocalDb?: CreateSyncClientOptions<TRegistry>["prepareLocalDb"];
|
|
112
180
|
/**
|
|
113
181
|
* Bounded zero-subscriber keep-alive for the live-query manager (ADR-0040 decision 4). When an entry's last
|
|
114
182
|
* subscriber leaves, a nonzero effective keep-alive retains its PGlite registration + diff state for a grace
|
|
@@ -160,7 +228,13 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
160
228
|
const createPglite =
|
|
161
229
|
options.createPglite ??
|
|
162
230
|
((storePath: string, backendOverride?: "memory") =>
|
|
163
|
-
|
|
231
|
+
// Relaxed durability (ADR-0047): the default factory forwards the worker-entry choice into
|
|
232
|
+
// `createClientPGlite`, which resolves the `?? true` default. A store minted for a spare/provision
|
|
233
|
+
// (`provision` handler) is thus created under the same durability mode the boot create uses.
|
|
234
|
+
createClientPGlite(storePath, {
|
|
235
|
+
...(backendOverride ? { backendOverride } : {}),
|
|
236
|
+
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
237
|
+
}));
|
|
164
238
|
// A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
|
|
165
239
|
// non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
|
|
166
240
|
// which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
|
|
@@ -409,6 +483,14 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
409
483
|
...(provisionStamp ? { provisionStamp } : {}),
|
|
410
484
|
...(precreatedPglite ? { precreatedPglite } : {}),
|
|
411
485
|
...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
|
|
486
|
+
// App-level schema prep runs IN THE WORKER around the registry schema exec (before/after), exactly as
|
|
487
|
+
// the in-process client. Worker-entry options, not attach options: functions cannot cross the bridge.
|
|
488
|
+
...(options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {}),
|
|
489
|
+
...(options.prepareLocalDb ? { prepareLocalDb: options.prepareLocalDb } : {}),
|
|
490
|
+
// Relaxed durability (ADR-0047): forward the worker-entry choice to the client-owned boot create too
|
|
491
|
+
// (the storePath / precreated-fallback path inside createSyncClient), so a worker that never adopts a
|
|
492
|
+
// provisioned spare still mints its store under the chosen durability mode.
|
|
493
|
+
...(options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}),
|
|
412
494
|
// Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
|
|
413
495
|
// spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
|
|
414
496
|
// journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
|
|
@@ -428,7 +510,9 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
428
510
|
onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
|
|
429
511
|
onReject: (details) => broadcastEvent({ kind: "reject", details }),
|
|
430
512
|
onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
|
|
431
|
-
|
|
513
|
+
// The cause chain, not just the wrapper message: the bridge carries a string, and dropping
|
|
514
|
+
// `.cause` here hid the actual database error from every tab (SQLSTATE, detail).
|
|
515
|
+
onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: describeErrorChain(error) }),
|
|
432
516
|
// Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
|
|
433
517
|
// push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
|
|
434
518
|
onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
|
|
@@ -445,6 +529,22 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
445
529
|
|
|
446
530
|
// ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
|
|
447
531
|
const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
|
|
532
|
+
// Guarded-read parser re-application (ADR-0032 decision 4). A guarded read compiled by the tab's
|
|
533
|
+
// Drizzle-over-bridge arrives as the {@link GuardedQueryWireArgs} tuple `[sql, params?, { rowMode? }, use?]`:
|
|
534
|
+
// the `parsers` map drizzle's pglite session normally passes could not cross the bridge (it is FUNCTIONS,
|
|
535
|
+
// not clonable), so the tab stripped it and we re-apply the identical map here before executing. Without it
|
|
536
|
+
// PGlite's default parsers would turn the identity-parsed OIDs (temporal OIDs + `numeric[]`) into `Date`s
|
|
537
|
+
// and numbers, whereas the in-process drizzle session sees them as raw STRINGS — so a guarded read would
|
|
538
|
+
// diverge from its in-process twin exactly on those columns. Typed against `GuardedQueryWireArgs` so the
|
|
539
|
+
// decode here shares the wire contract with the tab-side encoders (attach-sync-client).
|
|
540
|
+
const runGuardedQueryRpc = (): Promise<unknown> => {
|
|
541
|
+
const [sql, params, options, use] = args as unknown as GuardedQueryWireArgs;
|
|
542
|
+
const queryOptions: QueryOptions = {
|
|
543
|
+
...(options?.rowMode ? { rowMode: options.rowMode } : {}),
|
|
544
|
+
parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS,
|
|
545
|
+
};
|
|
546
|
+
return active.guardedRawQuery(sql, params, queryOptions, use as readonly SyncTableName<TRegistry>[] | undefined);
|
|
547
|
+
};
|
|
448
548
|
type TableKey = SyncTableName<TRegistry>;
|
|
449
549
|
switch (op) {
|
|
450
550
|
case "create":
|
|
@@ -491,6 +591,10 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
491
591
|
return active.desync(args[0] as TableKey);
|
|
492
592
|
case "discardEphemeral":
|
|
493
593
|
return active.discardEphemeral(args[0] as TableKey);
|
|
594
|
+
case "ensureSynced":
|
|
595
|
+
// Lazy activation (ADR-0021) on the worker's real client. Engine-wide but additive/idempotent — a tab
|
|
596
|
+
// activating a group another tab already started is a no-op, so no cross-tab revert hazard (cf. desync).
|
|
597
|
+
return active.ensureSynced(args[0] as readonly TableKey[]);
|
|
494
598
|
case "readMutationDetails":
|
|
495
599
|
return active.readMutationDetails(args[0] as TableKey | undefined);
|
|
496
600
|
case "diagnostics":
|
|
@@ -503,6 +607,12 @@ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
|
|
|
503
607
|
return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
|
|
504
608
|
case "rawExec":
|
|
505
609
|
return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
|
|
610
|
+
case "guardedQuery":
|
|
611
|
+
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the ADR-0041 read gate + the ADR-0021
|
|
612
|
+
// lazy-group guard run worker-side inside the engine's `guardedRawQuery`, so a read referencing a
|
|
613
|
+
// lazy relation activates its group exactly as in-process. The full `Results` structured-clones back
|
|
614
|
+
// and drizzle's own mapping (relational/nested included) runs on the tab.
|
|
615
|
+
return runGuardedQueryRpc();
|
|
506
616
|
case "bootReport":
|
|
507
617
|
// Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
|
|
508
618
|
// reads a boot predating it; the report structured-clones across the bridge as a plain object.
|
|
@@ -19,6 +19,7 @@ import type { LiveNamespace, LiveQuery, LiveQueryResults } from "@electric-sql/p
|
|
|
19
19
|
import { syncDebug } from "../debug";
|
|
20
20
|
import { computeLiveDiff, type LiveDiffState, seedLiveDiffState } from "./live-diff";
|
|
21
21
|
import { fingerprintLiveQuery } from "./live-query-fingerprint";
|
|
22
|
+
import { assertLiveQueryParamsSafe } from "./live-query-params-guard";
|
|
22
23
|
import type { LiveDiffPayload } from "./protocol";
|
|
23
24
|
|
|
24
25
|
type Row = Record<string, unknown>;
|
|
@@ -452,6 +453,11 @@ export function createLiveQueryManager(deps: LiveQueryManagerDeps): LiveQueryMan
|
|
|
452
453
|
`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`,
|
|
453
454
|
);
|
|
454
455
|
}
|
|
456
|
+
// Reject a param shape that would trip PGlite bug #1055's broken live-query param inlining BEFORE any
|
|
457
|
+
// fingerprinting or registration (see live-query-params-guard.ts). Synchronous, so every subscriber —
|
|
458
|
+
// in-process and worker alike — fails loudly rather than binding wrong rows or hitting a cryptic
|
|
459
|
+
// `format()` error deep inside PGlite.
|
|
460
|
+
assertLiveQueryParamsSafe(spec.materialSql, spec.params);
|
|
455
461
|
const keepAliveMs = hint ?? 0;
|
|
456
462
|
const scope = opts?.scope;
|
|
457
463
|
// Track this whole call so `dispose()` can drain the post-await join before it settles the teardown set —
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// A defensive guard against PGlite upstream bug https://github.com/electric-sql/pglite/issues/1055 on the
|
|
2
|
+
// live-query path. WHY this exists:
|
|
3
|
+
//
|
|
4
|
+
// PGlite 0.5.4's `live.query` / `live.incrementalQuery` inline bound params into a `CREATE TEMP VIEW`
|
|
5
|
+
// (via `formatQuery`) WHENEVER `params.length > 0`. That inlining rewrites every `$N` placeholder with
|
|
6
|
+
// `sql.replace(/\$([0-9]+)/g, (_, n) => "%" + n + "L")` — emitting `%NL`, which is Postgres `format()`'s
|
|
7
|
+
// "pad to width N, consume the NEXT argument sequentially" directive, NOT the positional `%N$L` it means to
|
|
8
|
+
// emit. Empirically confirmed consequences:
|
|
9
|
+
// - out-of-order placeholders (`… $2 … $1 …`) silently bind params in TEXTUAL order → wrong rows;
|
|
10
|
+
// - a repeated placeholder (`$1 … $1`) throws `too few arguments for format()`;
|
|
11
|
+
// - a skipped placeholder silently mis-binds.
|
|
12
|
+
// The ONLY input shape under which PGlite's broken inlining is still correct: the placeholders, read in
|
|
13
|
+
// textual order, are exactly `$1, $2, …, $n` (n = params.length) — each appearing exactly once, strictly
|
|
14
|
+
// ascending. Drizzle-compiled SQL always satisfies this (its serializer numbers params in the same
|
|
15
|
+
// left-to-right pass that emits them); hand-written raw SQL may not.
|
|
16
|
+
//
|
|
17
|
+
// So this guard fails LOUDLY at the client boundary for any other shape, turning a silent wrong-rows /
|
|
18
|
+
// cryptic-`format()` failure into an actionable error naming the upstream bug. It can be DELETED once
|
|
19
|
+
// transcrobes/pgxsinkit pin a PGlite release whose `formatQuery` emits the positional `%N$L`.
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Throw if `sql` + `params` would hit PGlite bug #1055's broken param inlining (see the module header).
|
|
23
|
+
*
|
|
24
|
+
* `params.length === 0` returns immediately: PGlite skips `formatQuery` entirely in that case, so any `$N`
|
|
25
|
+
* tokens are Postgres's own concern, not this guard's. Otherwise the SQL is scanned with the SAME regex
|
|
26
|
+
* PGlite's rewrite uses (`/\$(\d+)/g`) — deliberately, so the guard sees EXACTLY the tokens PGlite would
|
|
27
|
+
* touch. That includes a `$1` sitting inside a string literal: PGlite would corrupt that too, so a loud
|
|
28
|
+
* false positive here is a feature, not a bug — it flags SQL PGlite cannot inline safely regardless.
|
|
29
|
+
*
|
|
30
|
+
* Safe iff the collected numbers (in textual order) are exactly `[1, 2, …, params.length]`. Anything else —
|
|
31
|
+
* out-of-order, repeated, skipped, or a count mismatch in either direction — throws.
|
|
32
|
+
*/
|
|
33
|
+
export function assertLiveQueryParamsSafe(sql: string, params: readonly unknown[]): void {
|
|
34
|
+
// No params → PGlite never calls formatQuery, so its broken inlining never runs. Placeholders without
|
|
35
|
+
// params are Postgres's problem to report, not this guard's.
|
|
36
|
+
if (params.length === 0) return;
|
|
37
|
+
|
|
38
|
+
// The SAME regex PGlite's `formatQuery` applies — so we see exactly the tokens its rewrite would touch,
|
|
39
|
+
// including any `$N` inside a string literal (which PGlite would corrupt too; flagging it is intentional).
|
|
40
|
+
const numbers: number[] = [];
|
|
41
|
+
for (const match of sql.matchAll(/\$(\d+)/g)) numbers.push(Number(match[1]));
|
|
42
|
+
|
|
43
|
+
const expected = params.length;
|
|
44
|
+
const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
|
|
45
|
+
if (safe) return;
|
|
46
|
+
|
|
47
|
+
const found = numbers.length === 0 ? "(none)" : numbers.map((n) => `$${n}`).join(", ");
|
|
48
|
+
throw new Error(
|
|
49
|
+
`[pgxsinkit] live query hits PGlite bug #1055 ` +
|
|
50
|
+
`(https://github.com/electric-sql/pglite/issues/1055): its live-query param inlining binds $N ` +
|
|
51
|
+
`placeholders SEQUENTIALLY (in textual order), not positionally, so anything but a strictly ` +
|
|
52
|
+
`ascending $1..$n each used once silently mis-binds or throws. Found placeholders [${found}] for ` +
|
|
53
|
+
`${expected} param${expected === 1 ? "" : "s"}, expected exactly [$1..$${expected}]. Renumber the ` +
|
|
54
|
+
`placeholders to a strictly sequential $1..$${expected}, each used once — or pass the query as a ` +
|
|
55
|
+
`Drizzle builder, which always compiles to that shape.`,
|
|
56
|
+
);
|
|
57
|
+
}
|
package/src/worker/protocol.ts
CHANGED
|
@@ -253,10 +253,23 @@ export type RpcOp =
|
|
|
253
253
|
| "discardQuarantined"
|
|
254
254
|
| "desync"
|
|
255
255
|
| "discardEphemeral"
|
|
256
|
+
// Lazy activation (ADR-0021): start the consistency groups of the given relation keys on the shared engine.
|
|
257
|
+
// Engine-WIDE but additive/idempotent (unlike `desync`), so it is a plain fire-and-await RPC — carries
|
|
258
|
+
// `[keys]`, resolves once the streams are started (catch-up may still be in flight).
|
|
259
|
+
| "ensureSynced"
|
|
256
260
|
| "readMutationDetails"
|
|
257
261
|
| "diagnostics"
|
|
258
262
|
| "rawQuery"
|
|
259
263
|
| "rawExec"
|
|
264
|
+
// Guarded one-shot Drizzle read (ADR-0032 decision 4): the attach client's Drizzle-over-bridge compiles a
|
|
265
|
+
// read to SQL on the tab and routes it here as the {@link GuardedQueryWireArgs} tuple
|
|
266
|
+
// `[sql, params?, { rowMode? }, use?]`. Unlike `rawQuery` (raw inspection, no guard), the worker runs the
|
|
267
|
+
// engine's `guardedRawQuery` — the ADR-0041 read gate + the ADR-0021 lazy-group guard (activating any lazy
|
|
268
|
+
// relation the SQL/`use` reference) — then returns the full PGlite `Results` over `rpc-result`, so Drizzle's
|
|
269
|
+
// own result mapping runs on the tab. Only `rowMode` crosses in the options: drizzle's `parsers` map is
|
|
270
|
+
// FUNCTIONS (non-serializable) and is stripped tab-side, then re-applied worker-side so the identity-parsed
|
|
271
|
+
// OIDs (drizzle's identity parsers — temporal OIDs + numeric[]) round-trip as raw strings exactly as in-process.
|
|
272
|
+
| "guardedQuery"
|
|
260
273
|
// Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the
|
|
261
274
|
// stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.
|
|
262
275
|
| "bootReport"
|
|
@@ -273,6 +286,21 @@ export type RpcOp =
|
|
|
273
286
|
// clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.
|
|
274
287
|
| "exportData";
|
|
275
288
|
|
|
289
|
+
/**
|
|
290
|
+
* The positional wire tuple the `guardedQuery` {@link RpcOp} carries: a guarded one-shot Drizzle read compiled
|
|
291
|
+
* to SQL on the tab. Encoded identically by both tab-side senders (`attachSyncClient`'s bridge executor and
|
|
292
|
+
* `guardedRawQuery`) and decoded against this same type worker-side (`defineSyncWorker`'s dispatch), so encoder
|
|
293
|
+
* and decoder share ONE contract. `options` carries only `rowMode` — drizzle's `parsers` map is stripped
|
|
294
|
+
* tab-side (see the `guardedQuery` op above) and re-applied worker-side. The optional trailing `use` lists the
|
|
295
|
+
* raw-fragment lazy relations (ADR-0021) the SQL scan cannot see.
|
|
296
|
+
*/
|
|
297
|
+
export type GuardedQueryWireArgs = [
|
|
298
|
+
sql: string,
|
|
299
|
+
params: unknown[] | undefined,
|
|
300
|
+
options: { rowMode?: "array" | "object" },
|
|
301
|
+
use?: readonly string[],
|
|
302
|
+
];
|
|
303
|
+
|
|
276
304
|
/** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
|
|
277
305
|
export interface RpcPayload {
|
|
278
306
|
op: RpcOp;
|