@pgxsinkit/client 0.3.0 → 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.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +10 -3
- package/dist/boot-report.d.ts +6 -6
- package/dist/circuits/envelope-to-change.d.ts +9 -5
- package/dist/circuits/envelope-to-change.d.ts.map +1 -1
- package/dist/circuits/group-sync.d.ts +2 -2
- package/dist/circuits/group-sync.d.ts.map +1 -1
- package/dist/circuits/stream-source.d.ts +6 -0
- package/dist/circuits/stream-source.d.ts.map +1 -1
- package/dist/circuits/sync-engine.d.ts +2 -2
- package/dist/circuits/sync-engine.d.ts.map +1 -1
- package/dist/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +9 -9
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +191 -95
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +989 -432
- package/dist/index.js.map +39 -36
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +58 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +40 -28
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +5 -5
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +82 -6
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +5 -5
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +24 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +35 -18
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -8
- package/skills/core/SKILL.md +80 -15
- package/skills/operating/SKILL.md +129 -129
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +9 -9
- package/src/circuits/envelope-to-change.ts +121 -12
- package/src/circuits/group-sync.ts +2 -2
- package/src/circuits/stream-source.ts +35 -9
- package/src/circuits/sync-engine.ts +6 -4
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +21 -26
- package/src/export-store.ts +17 -17
- package/src/index.ts +520 -284
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +70 -6
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +2 -2
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +124 -18
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +56 -40
- package/src/sync/apply.ts +32 -46
- package/src/sync/copy.ts +108 -13
- package/src/sync/drizzle-executor.ts +13 -14
- package/src/sync/metadata-tables.ts +1 -1
- package/src/sync/subscription-state.ts +7 -7
- package/src/testing.ts +3 -3
- package/src/worker/attach-sync-client.ts +142 -56
- package/src/worker/define-sync-worker.ts +204 -75
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +10 -10
- package/src/worker/protocol.ts +38 -7
package/src/live-rows-sql.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { quoteIdentifier } from "@pgxsinkit/contracts";
|
|
|
2
2
|
|
|
3
3
|
// ─── Live-read materialization safety (ADR-0032 S2 §4) ───────────────────────────────────────────────
|
|
4
4
|
//
|
|
5
|
-
// The live-rows seam feeds the compiled SQL of a Drizzle-built select into
|
|
5
|
+
// The live-rows seam feeds the compiled SQL of a Drizzle-built select into pgwasm's `live` extension,
|
|
6
6
|
// which MATERIALISES the query (a temp view + state table it diffs against). Drizzle emits no output
|
|
7
7
|
// aliases — it maps result columns positionally — so a JOIN whose tables share a column name (two
|
|
8
8
|
// `title`) compiles to a SELECT with duplicate OUTPUT column names. That is legal as a plain one-shot
|
package/src/local-store.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { and, eq, like, notExists, sql } from "drizzle-orm";
|
|
2
|
-
import { drizzle } from "drizzle-orm/pglite";
|
|
3
2
|
|
|
4
3
|
import { type MutationDiagnostics, type SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
4
|
+
import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
5
5
|
|
|
6
6
|
import { syncDebug } from "./debug";
|
|
7
7
|
import { getJournalTable, getLocalMetaTable } from "./local-tables";
|
|
@@ -219,7 +219,7 @@ function writableTableKeys(registry: SyncTableRegistry): string[] {
|
|
|
219
219
|
* statement — but only where NOT EXISTS any `sending` row in ANY writable journal (the EXISTS-union is built
|
|
220
220
|
* from the registry's journal Drizzle objects via {@link getJournalTable}). Correct regardless of JS
|
|
221
221
|
* bookkeeping: a concurrent enqueue that committed a `sending` row makes the guard fail, so the marker stays
|
|
222
|
-
* `"true"`. Returns `{ cleared }` from the statement's affected-row count (
|
|
222
|
+
* `"true"`. Returns `{ cleared }` from the statement's affected-row count (pgwasm reports `affectedRows`) —
|
|
223
223
|
* `true` when the guard passed (an existing marker row flipped/held at `"false"`), `false` when a `sending`
|
|
224
224
|
* row blocked it OR no marker row exists yet. Off the boot path AND at the end of a boot recovery pass.
|
|
225
225
|
*
|
package/src/local-tables.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
deriveSyncColumnTypes,
|
|
24
24
|
getLocalSyncedTablePrimaryKeyColumns,
|
|
25
25
|
getSyncRegistrySchema,
|
|
26
|
+
jsonUdtName,
|
|
26
27
|
type SyncColumnType,
|
|
27
28
|
type SyncTableEntry,
|
|
28
29
|
type SyncTableRegistry,
|
|
@@ -109,7 +110,7 @@ function buildOverlayFixedColumns() {
|
|
|
109
110
|
/**
|
|
110
111
|
* The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.
|
|
111
112
|
* Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so
|
|
112
|
-
* `local_updated_at_us` is a `mode: "bigint"` int8 (
|
|
113
|
+
* `local_updated_at_us` is a `mode: "bigint"` int8 (pgwasm returns it as a string at runtime) rather than
|
|
113
114
|
* the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same
|
|
114
115
|
* way the generator names them (`view["overlay_kind"]`).
|
|
115
116
|
*/
|
|
@@ -151,7 +152,7 @@ const localMetaShape = pgTable(LOCAL_META_TABLE, {
|
|
|
151
152
|
* The **Outbox**'s columns (ADR-0053 decision 2), mirroring the DDL in `schema.ts` — see {@link OUTBOX_TABLE}
|
|
152
153
|
* there for the column-by-column public contract. The `_us` bigints and `seq` are the same `bigintText`
|
|
153
154
|
* passthrough the journal object uses (rows come back through the raw seam UNMAPPED, so the runtime reads
|
|
154
|
-
* them as strings); `payload` is real `jsonb` (
|
|
155
|
+
* them as strings); `payload` is real `jsonb` (pgwasm parses it, so the flush loop gets the object back).
|
|
155
156
|
* `seq` is DEFAULTed by the sequence, so an insert omits it — hence no `.notNull()` footgun on `$inferInsert`.
|
|
156
157
|
*/
|
|
157
158
|
function buildOutboxColumns() {
|
|
@@ -165,6 +166,7 @@ function buildOutboxColumns() {
|
|
|
165
166
|
attemptCount: integer("attempt_count").notNull().default(0),
|
|
166
167
|
nextRetryAtUs: bigintText("next_retry_at_us"),
|
|
167
168
|
lastReason: text("last_reason"),
|
|
169
|
+
ackedAtUs: bigintText("acked_at_us"),
|
|
168
170
|
};
|
|
169
171
|
}
|
|
170
172
|
|
|
@@ -519,6 +521,20 @@ export interface ApplyTarget {
|
|
|
519
521
|
propertyKeyByName: Record<string, string>;
|
|
520
522
|
/** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */
|
|
521
523
|
primaryKey: string[];
|
|
524
|
+
/**
|
|
525
|
+
* The SERVER primary-key column names, in declaration order — the order the engine joins stream-key
|
|
526
|
+
* components in (`schema.rs` `key_string`). Identical to {@link primaryKey} except under a
|
|
527
|
+
* `clientProjection.localPrimaryKey` narrowing, where the stream key still carries every server
|
|
528
|
+
* component and the local key is a subset.
|
|
529
|
+
*/
|
|
530
|
+
serverPrimaryKey: string[];
|
|
531
|
+
/**
|
|
532
|
+
* Server-key components `clientProjection.localPrimaryKey` drops (subscribe-time compile refuses the
|
|
533
|
+
* narrowing unless the shape's predicate pins each to a single value). The engine force-includes
|
|
534
|
+
* every server pk component in emitted rows and keys, so the applier projects exactly these away —
|
|
535
|
+
* any OTHER unknown column stays a loud config error.
|
|
536
|
+
*/
|
|
537
|
+
droppedKeyColumns: string[];
|
|
522
538
|
/**
|
|
523
539
|
* CDC insert-apply policy (ADR-0045), from the entry. `"insert"` (default) applies a CDC insert as a
|
|
524
540
|
* plain INSERT so a genuine PK collision surfaces; `"upsert"` applies it idempotently (ON CONFLICT DO
|
|
@@ -527,6 +543,16 @@ export interface ApplyTarget {
|
|
|
527
543
|
applyMode: "insert" | "upsert";
|
|
528
544
|
/** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */
|
|
529
545
|
columnTypes: SyncColumnType[];
|
|
546
|
+
/**
|
|
547
|
+
* DB column names of the SCALAR `json`/`jsonb` columns — the columns whose wire cell is decoded from
|
|
548
|
+
* JSON text to a JS value on the way in (see `envelopeToChange`). Derived from {@link columnTypes} via
|
|
549
|
+
* the contracts' `jsonUdtName`, once per shape at resolve time rather than per row: the decode runs on
|
|
550
|
+
* every cell of every backfill row, so re-deriving it there would be a per-row string normalisation.
|
|
551
|
+
*
|
|
552
|
+
* Array json columns (`json[]`/`jsonb[]`) are NOT listed — like every array column they stay in
|
|
553
|
+
* Postgres's `array_out` text, which every apply tier feeds back to `array_in`.
|
|
554
|
+
*/
|
|
555
|
+
jsonColumns: string[];
|
|
530
556
|
/**
|
|
531
557
|
* Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,
|
|
532
558
|
* params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied
|
|
@@ -535,6 +561,22 @@ export interface ApplyTarget {
|
|
|
535
561
|
insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;
|
|
536
562
|
}
|
|
537
563
|
|
|
564
|
+
/**
|
|
565
|
+
* The DB column names of the SCALAR `json`/`jsonb` columns in a resolved column-type list — the
|
|
566
|
+
* {@link ApplyTarget.jsonColumns} derivation, exported so the test-support target builder and any other
|
|
567
|
+
* ApplyTarget producer derive it the one way (through the contracts' `jsonUdtName`).
|
|
568
|
+
*/
|
|
569
|
+
export function scalarJsonColumnNames(columnTypes: readonly SyncColumnType[]): string[] {
|
|
570
|
+
const names: string[] = [];
|
|
571
|
+
for (const column of columnTypes) {
|
|
572
|
+
const udt = jsonUdtName(column);
|
|
573
|
+
if (udt === "json" || udt === "jsonb") {
|
|
574
|
+
names.push(column.name);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return names;
|
|
578
|
+
}
|
|
579
|
+
|
|
538
580
|
/**
|
|
539
581
|
* Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape
|
|
540
582
|
* at subscribe time — never per message. The single source is the registry item: identity via
|
|
@@ -553,6 +595,18 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
|
|
|
553
595
|
columnByName[column.name] = column;
|
|
554
596
|
propertyKeyByName[column.name] = propertyKey;
|
|
555
597
|
}
|
|
598
|
+
// Both pk specs are stored verbatim (property key OR column name) — normalize each against the
|
|
599
|
+
// table that actually carries its columns: the local key against the projected synced table, the
|
|
600
|
+
// server key against the full server table (a dropped component has no local column to resolve by).
|
|
601
|
+
const localPrimaryKey = getLocalSyncedTablePrimaryKeyColumns(entry).map((declared) =>
|
|
602
|
+
columns[declared] ? columns[declared].name : declared,
|
|
603
|
+
);
|
|
604
|
+
const localPrimaryKeySet = new Set(localPrimaryKey);
|
|
605
|
+
const serverColumns = getColumns(entry.table as AnyPgTable) as Record<string, PgColumn>;
|
|
606
|
+
const serverPrimaryKey = entry.primaryKey.columns.map((declared) =>
|
|
607
|
+
serverColumns[declared] ? serverColumns[declared].name : declared,
|
|
608
|
+
);
|
|
609
|
+
const columnTypes = deriveSyncColumnTypes(entry);
|
|
556
610
|
return {
|
|
557
611
|
table: table as AnyPgTable,
|
|
558
612
|
columnByName,
|
|
@@ -562,11 +616,12 @@ export function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey ext
|
|
|
562
616
|
// differ, the un-normalized form reaches `columnByName`/`propertyKeyByName`, which are keyed by
|
|
563
617
|
// column name, and every update and delete throws "column not found". Resolving here, where the
|
|
564
618
|
// table's own columns are in hand, makes the field match what it has always claimed to be.
|
|
565
|
-
primaryKey:
|
|
566
|
-
|
|
567
|
-
),
|
|
619
|
+
primaryKey: localPrimaryKey,
|
|
620
|
+
serverPrimaryKey,
|
|
621
|
+
droppedKeyColumns: serverPrimaryKey.filter((name) => !localPrimaryKeySet.has(name)),
|
|
568
622
|
applyMode: entry.applyMode,
|
|
569
|
-
columnTypes
|
|
623
|
+
columnTypes,
|
|
624
|
+
jsonColumns: scalarJsonColumnNames(columnTypes),
|
|
570
625
|
insertRenderCache: new Map(),
|
|
571
626
|
};
|
|
572
627
|
}
|
|
@@ -627,6 +682,15 @@ export function getAllMutationsView(_registry: SyncTableRegistry): AllMutationsV
|
|
|
627
682
|
* Public on purpose: the table's shape is contract, so an app composing a best-guess view (pending events
|
|
628
683
|
* over down-synced aggregates) authors it as tier-① Drizzle instead of hand-written SQL —
|
|
629
684
|
* `client.query((c) => c.drizzle.select().from(getOutboxTable(registry)).where(eq(outbox.stream, "…")))`.
|
|
685
|
+
*
|
|
686
|
+
* **A best-guess view's pending predicate is `acked_at_us IS NULL`** (ADR-0060), not "the row is present":
|
|
687
|
+
* with `events.ackedRetentionMs > 0` an accepted event is STAMPED and RETAINED rather than deleted, because
|
|
688
|
+
* the server has only accepted it — its consumer has not folded it yet, and the folded aggregate has not
|
|
689
|
+
* synced back down. That retention window is the composition's **grace ledger**: keep counting an acked row
|
|
690
|
+
* until your own synced row's stamp passes its `acked_at_us` (or until the retention elapses and the lane's
|
|
691
|
+
* sweep deletes it), and the composed value stops dipping between the ack and the fold. At the default
|
|
692
|
+
* retention of `0` an acked row is deleted on the spot, so `acked_at_us` is never non-NULL and the predicate
|
|
693
|
+
* costs nothing.
|
|
630
694
|
*/
|
|
631
695
|
export function getOutboxTable(registry: SyncTableRegistry): OutboxTable {
|
|
632
696
|
const localSchema = getSyncRegistrySchema(registry);
|
package/src/mutation.ts
CHANGED
|
@@ -24,7 +24,8 @@ import {
|
|
|
24
24
|
type PgColumn,
|
|
25
25
|
type PgInsertValue,
|
|
26
26
|
} from "drizzle-orm/pg-core";
|
|
27
|
-
|
|
27
|
+
|
|
28
|
+
import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
28
29
|
|
|
29
30
|
import {
|
|
30
31
|
clearMutationRecoveryMarkerIfSettled,
|
|
@@ -190,7 +191,7 @@ export interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistr
|
|
|
190
191
|
registryVersion?: string;
|
|
191
192
|
/**
|
|
192
193
|
* Whether pgxsinkit owns the local schema (and therefore the `pgxsinkit_local_meta` table the durable
|
|
193
|
-
* recovery-required marker lives in). Defaults to `true`. A caller-owned `
|
|
194
|
+
* recovery-required marker lives in). Defaults to `true`. A caller-owned `pgwasmInstance` boot sets this
|
|
194
195
|
* `false`: the meta table may not exist, so the marker is never read/written and boot recovery runs
|
|
195
196
|
* unconditionally.
|
|
196
197
|
*/
|
|
@@ -395,7 +396,7 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
|
|
|
395
396
|
* runs from a consumer call ({@link recoverSending} keeps today's exact per-table semantics and never
|
|
396
397
|
* touches the marker); {@link BootRecoveryOutcome} feeds the `warmBoot` BootReport fields verbatim.
|
|
397
398
|
*
|
|
398
|
-
* - `ownsMetaTable: false` (caller-owned
|
|
399
|
+
* - `ownsMetaTable: false` (caller-owned pgwasm) → unconditional recovery, marker untouched.
|
|
399
400
|
* - `restore: true` → unconditional recovery + {@link quarantineRecovered} + self-verifying clear (marker ignored).
|
|
400
401
|
* - marker `false` → skip the loop entirely.
|
|
401
402
|
* - marker absent (not initialized) → one conservative recovery pass, then initialize the marker.
|
|
@@ -534,7 +535,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
534
535
|
};
|
|
535
536
|
|
|
536
537
|
// Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
|
|
537
|
-
// recovery-required marker lives in). A caller-owned
|
|
538
|
+
// recovery-required marker lives in). A caller-owned pgwasm boot sets this false, so the marker is never
|
|
538
539
|
// touched and the SET/clear seams below are no-ops.
|
|
539
540
|
const ownsMetaTable = options.ownsMetaTable ?? true;
|
|
540
541
|
// Cached "this epoch has already committed the marker `true`" flag. Marker-first ordering:
|
|
@@ -608,7 +609,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
608
609
|
// so relative to this synchronous check-and-reset block it is either
|
|
609
610
|
// (i) BEFORE it → `markSendingInFlight > 0` here → no clear is issued at all (the FIX 1 gate); or
|
|
610
611
|
// (ii) AFTER it → the sender reads `recoveryMarkerDirty === false` → it awaits
|
|
611
|
-
// `writeMutationRecoveryRequired(true)`, and
|
|
612
|
+
// `writeMutationRecoveryRequired(true)`, and pgwasm's single-connection queue serializes that upsert
|
|
612
613
|
// AFTER the already-issued clear → the marker is durably `true` again BEFORE the sender's `sending`
|
|
613
614
|
// UPDATE (only issued once the marker await resolves) can commit. A crash between the rewrite and the
|
|
614
615
|
// UPDATE leaves marker-`true`/no-row (conservative).
|
|
@@ -1440,7 +1441,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
1440
1441
|
const contexts = filterContexts(tableContexts, undefined);
|
|
1441
1442
|
const tablesVisited = contexts.length;
|
|
1442
1443
|
|
|
1443
|
-
// Caller-owned
|
|
1444
|
+
// Caller-owned pgwasm: the meta table may not exist, so never touch the marker and always recover.
|
|
1444
1445
|
if (!bootOwnsMetaTable) {
|
|
1445
1446
|
await runtime.recoverSending();
|
|
1446
1447
|
return { skipped: false, required: true, tablesVisited, rowsRecovered: null };
|
|
@@ -3149,7 +3150,7 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
|
|
|
3149
3150
|
// (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When
|
|
3150
3151
|
// none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip
|
|
3151
3152
|
// the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable
|
|
3152
|
-
// table on its interval (default 1.5s), and each CTE pays full
|
|
3153
|
+
// table on its interval (default 1.5s), and each CTE pays full pgwasm plan+execute cost even against an
|
|
3153
3154
|
// empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the
|
|
3154
3155
|
// <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing
|
|
3155
3156
|
// to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)
|
|
@@ -3302,7 +3303,7 @@ async function reconcileTable(db: MutationDb, context: TableContext) {
|
|
|
3302
3303
|
await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);
|
|
3303
3304
|
|
|
3304
3305
|
// Clear acknowledged delete mutations where synced row is absent
|
|
3305
|
-
// Single compound CTE —
|
|
3306
|
+
// Single compound CTE — pgwasm does not support multi-statement query().
|
|
3306
3307
|
const clearableEntities = queryBuilder.$with("clearable_entities").as(
|
|
3307
3308
|
queryBuilder
|
|
3308
3309
|
.selectDistinct(
|
package/src/mutations-api.ts
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
// names.
|
|
11
11
|
|
|
12
12
|
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
|
13
|
-
import { drizzle } from "drizzle-orm/pglite";
|
|
14
13
|
|
|
15
14
|
import type { MutationSummary, SyncTableName, SyncTableRegistry } from "@pgxsinkit/contracts";
|
|
15
|
+
import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
16
16
|
|
|
17
17
|
import { getAllMutationsView } from "./local-tables";
|
|
18
18
|
import type { MutationDetail, MutationKind } from "./mutation";
|
|
@@ -25,7 +25,7 @@ export type MutationSummaryDetail = MutationDetail;
|
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
27
|
* Build-only Drizzle (compiles to SQL via `.toSQL()`; never executes) — same mock seam mutation.ts uses.
|
|
28
|
-
* Lazily constructed: some unit suites mock
|
|
28
|
+
* Lazily constructed: some unit suites mock `@pgxsinkit/pgwasm/drizzle`, so `drizzle.mock` is unavailable at module
|
|
29
29
|
* load; a lazy builder is only reached when a real query is actually authored (never in those mocked boots).
|
|
30
30
|
*/
|
|
31
31
|
let queryBuilderInstance: ReturnType<typeof drizzle.mock> | undefined;
|
package/src/opfs-effects.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
// swallowed (deleteSentinel, deleteStoreDirectory). `observeCommitmentNamespace` never creates and never
|
|
14
14
|
// throws — a root/API failure reads as `"unobservable"` (present absence is not historical proof).
|
|
15
15
|
|
|
16
|
+
import { withStoreOwnership, type OwnershipLocks } from "./store-ownership-lock";
|
|
16
17
|
import { opfsCommitmentSentinelPath, opfsStoreDirectoryPath } from "./store-path";
|
|
17
18
|
|
|
18
19
|
/**
|
|
@@ -34,15 +35,30 @@ export interface OpfsEffectsDeps {
|
|
|
34
35
|
* `"unobservable"`, and the create effects throw (they are only reached in the opfs engine home).
|
|
35
36
|
*/
|
|
36
37
|
getRoot?: () => Promise<DirLike>;
|
|
38
|
+
/**
|
|
39
|
+
* The Web Locks surface `deleteStoreDirectory` orders on (`store-ownership-lock.ts`). Omit in production: the
|
|
40
|
+
* default reads `navigator.locks` off `globalThis`; `null` (or an absent API) skips the ordering.
|
|
41
|
+
*/
|
|
42
|
+
locks?: OwnershipLocks | null;
|
|
43
|
+
/** Bound on waiting for the store's owner to release before `deleteStoreDirectory` fails. Default 10 s. */
|
|
44
|
+
ownershipWaitMs?: number;
|
|
37
45
|
}
|
|
38
46
|
|
|
39
47
|
/** The effects surface the store-boot wiring drives (create-if-absent / delete-if-present / never-creating observe). */
|
|
40
48
|
export interface OpfsEffects {
|
|
41
49
|
/** Create-if-absent the commitment sentinel file at `pgxsinkit/commitments/<identity>`. */
|
|
42
50
|
publishSentinel(): Promise<void>;
|
|
43
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
* Delete-if-present the commitment sentinel (`NotFoundError` swallowed). A root that cannot be opened at all
|
|
53
|
+
* raises {@link OpfsRootUnavailableError}.
|
|
54
|
+
*/
|
|
44
55
|
deleteSentinel(): Promise<void>;
|
|
45
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* Recursively delete-if-present the store directory `pgxsinkit/stores/<identity>` (`NotFoundError` swallowed),
|
|
58
|
+
* under the store's ownership lock: the delete waits (bounded) until the context holding the directory's
|
|
59
|
+
* sync-access handles has released them, and fails with `StoreOwnershipWaitError` under a live owner. A root
|
|
60
|
+
* that cannot be opened at all raises {@link OpfsRootUnavailableError}.
|
|
61
|
+
*/
|
|
46
62
|
deleteStoreDirectory(): Promise<void>;
|
|
47
63
|
/**
|
|
48
64
|
* Never-creating walk of the commitment namespace. A root/API failure (or the API being absent) reads as
|
|
@@ -53,6 +69,29 @@ export interface OpfsEffects {
|
|
|
53
69
|
getStoreDirectoryHandle(): Promise<unknown>;
|
|
54
70
|
}
|
|
55
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The OPFS root could not be opened AT ALL in this context — `navigator.storage.getDirectory()` rejected
|
|
74
|
+
* (WebKit's throwaway contexts reject with `UnknownError`; probably Safari private windows too). Raised only by
|
|
75
|
+
* the two DELETE effects, so the destruction wiring can tell "this context cannot reach OPFS" from a failure
|
|
76
|
+
* inside a reachable OPFS and record the OPFS side as pending instead (ADR-0036 amendment, 2026-09-28). The
|
|
77
|
+
* original rejection is the `cause`.
|
|
78
|
+
*/
|
|
79
|
+
export class OpfsRootUnavailableError extends Error {
|
|
80
|
+
constructor(storePath: string, cause: unknown) {
|
|
81
|
+
super(
|
|
82
|
+
`[pgxsinkit] the OPFS root cannot be opened in this context, so the OPFS side of ${JSON.stringify(storePath)} ` +
|
|
83
|
+
"cannot be deleted here.",
|
|
84
|
+
{ cause },
|
|
85
|
+
);
|
|
86
|
+
this.name = "OpfsRootUnavailableError";
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Is this an {@link OpfsRootUnavailableError}? Name-based, so it survives duplicated module instances. */
|
|
91
|
+
export function isOpfsRootUnavailableError(error: unknown): boolean {
|
|
92
|
+
return (error as { name?: string } | null)?.name === "OpfsRootUnavailableError";
|
|
93
|
+
}
|
|
94
|
+
|
|
56
95
|
/** Is this a `NotFoundError` (a missing OPFS entry) — the delete/observe "absent" signal? */
|
|
57
96
|
function isNotFoundError(error: unknown): boolean {
|
|
58
97
|
return (error as { name?: string } | null)?.name === "NotFoundError";
|
|
@@ -84,6 +123,19 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
|
|
|
84
123
|
return handle;
|
|
85
124
|
}
|
|
86
125
|
|
|
126
|
+
// The delete effects' walk: identical, except that a REJECTING root (OPFS cannot be opened in this context at
|
|
127
|
+
// all) is raised as the typed {@link OpfsRootUnavailableError}, distinct from any failure inside a reachable OPFS.
|
|
128
|
+
async function walkDirectoriesForDelete(segments: readonly string[]): Promise<DirLike> {
|
|
129
|
+
let handle: DirLike;
|
|
130
|
+
try {
|
|
131
|
+
handle = await getRoot!();
|
|
132
|
+
} catch (error) {
|
|
133
|
+
throw new OpfsRootUnavailableError(storePath, error);
|
|
134
|
+
}
|
|
135
|
+
for (const segment of segments) handle = await handle.getDirectoryHandle(segment, { create: false });
|
|
136
|
+
return handle;
|
|
137
|
+
}
|
|
138
|
+
|
|
87
139
|
// Never-creating existence check for one namespace entry; `NotFoundError` anywhere in the chain → absent.
|
|
88
140
|
async function entryExists(path: readonly string[], kind: "file" | "dir"): Promise<boolean> {
|
|
89
141
|
try {
|
|
@@ -117,7 +169,7 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
|
|
|
117
169
|
if (getRoot == null) return;
|
|
118
170
|
const path = opfsCommitmentSentinelPath(storePath);
|
|
119
171
|
try {
|
|
120
|
-
const parent = await
|
|
172
|
+
const parent = await walkDirectoriesForDelete(path.slice(0, -1));
|
|
121
173
|
await parent.removeEntry(path[path.length - 1]!);
|
|
122
174
|
} catch (error) {
|
|
123
175
|
// Delete-if-present: a missing parent dir or a missing sentinel both count as already deleted.
|
|
@@ -128,13 +180,25 @@ export function createOpfsEffects(storePath: string, deps?: OpfsEffectsDeps): Op
|
|
|
128
180
|
async deleteStoreDirectory(): Promise<void> {
|
|
129
181
|
if (getRoot == null) return;
|
|
130
182
|
const path = opfsStoreDirectoryPath(storePath);
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
183
|
+
// Ordering, not retrying: the previous owner (a reloaded page's or a relocated engine's worker) may still
|
|
184
|
+
// hold the directory's EXCLUSIVE sync-access handles, and a `removeEntry` under them is refused. Its
|
|
185
|
+
// ownership lock is held until those handles are closed (or its context is gone), so take it first.
|
|
186
|
+
await withStoreOwnership(
|
|
187
|
+
storePath,
|
|
188
|
+
async () => {
|
|
189
|
+
try {
|
|
190
|
+
const parent = await walkDirectoriesForDelete(path.slice(0, -1));
|
|
191
|
+
// Recursive: the store directory holds the four VFS-owned files; the whole leaf goes.
|
|
192
|
+
await parent.removeEntry(path[path.length - 1]!, { recursive: true });
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (!isNotFoundError(error)) throw error;
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
...(deps?.locks !== undefined ? { locks: deps.locks } : {}),
|
|
199
|
+
...(deps?.ownershipWaitMs !== undefined ? { waitMs: deps.ownershipWaitMs } : {}),
|
|
200
|
+
},
|
|
201
|
+
);
|
|
138
202
|
},
|
|
139
203
|
|
|
140
204
|
async observeCommitmentNamespace(): Promise<
|
package/src/schema.ts
CHANGED
|
@@ -71,6 +71,17 @@ export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
|
|
|
71
71
|
* `next_retry_at_us` is in the future is skipped by batch assembly. NULL = eligible now.
|
|
72
72
|
* - `last_reason` — the most recent server `deferred` reason, kept on the row it belongs to (never a
|
|
73
73
|
* second, retention-bearing verdict table — ADR-0053 rejects that).
|
|
74
|
+
* - `acked_at_us` — the **acked ledger** stamp (ADR-0060): when the server accepted the event, or NULL
|
|
75
|
+
* while it is still PENDING a verdict. NULL is the pending predicate — everything the library means by
|
|
76
|
+
* "pending" reads `acked_at_us IS NULL` (the drain signal, batch assembly, `diagnostics().outbox`, the
|
|
77
|
+
* non-forced `destroy()` refusal), so a stamped row is never re-posted and never keeps the lane
|
|
78
|
+
* "non-empty". It is stamped instead of deleted only when the client configures
|
|
79
|
+
* `events.ackedRetentionMs > 0`; at the default `0` an `acked` verdict deletes the row immediately and
|
|
80
|
+
* this column is never non-NULL. **For a best-guess view it is the grace ledger**: an `acked` row has
|
|
81
|
+
* been accepted but NOT yet folded by the server's consumer, and the folded aggregate has not yet synced
|
|
82
|
+
* back down — so a composition may keep counting an acked row until its own synced row's stamp passes
|
|
83
|
+
* `acked_at_us`, or until the retention elapses and the sweep deletes it. That dip is the whole reason
|
|
84
|
+
* the column exists.
|
|
74
85
|
*/
|
|
75
86
|
export const OUTBOX_TABLE = "pgxsinkit_outbox";
|
|
76
87
|
|
|
@@ -159,15 +170,27 @@ function localMetaBootstrapStatements(localSchema: string): string[] {
|
|
|
159
170
|
}
|
|
160
171
|
|
|
161
172
|
/**
|
|
162
|
-
* The **Outbox** DDL (ADR-0053 decision 2) — its sequence, table, and the
|
|
163
|
-
* unconditionally in the durable stream (never gated on `registry.streams`): the shape is
|
|
164
|
-
* and the table must exist before the first `appendEvent`, which may be the first thing
|
|
165
|
-
* registry gains its first Event stream. See {@link OUTBOX_TABLE} for the column
|
|
173
|
+
* The **Outbox** DDL (ADR-0053 decision 2) — its sequence, table, and the three indexes that serve it.
|
|
174
|
+
* Emitted unconditionally in the durable stream (never gated on `registry.streams`): the shape is
|
|
175
|
+
* stream-independent and the table must exist before the first `appendEvent`, which may be the first thing
|
|
176
|
+
* an app does after a registry gains its first Event stream. See {@link OUTBOX_TABLE} for the column
|
|
177
|
+
* contract.
|
|
166
178
|
*
|
|
167
|
-
*
|
|
179
|
+
* **CREATE-only, deliberately** (ADR-0060): these are `IF NOT EXISTS` statements, so a store provisioned
|
|
180
|
+
* before a column existed does NOT gain it — there is no ALTER path and no adoption. A store predating
|
|
181
|
+
* `acked_at_us` is reset at the consumer's cutover, per this library's greenfield rule.
|
|
182
|
+
*
|
|
183
|
+
* Three indexes, one per access pattern:
|
|
168
184
|
* - `(stream, seq)` serves the APP's `WHERE stream = ?` best-guess-view queries in append order;
|
|
169
185
|
* - `(next_retry_at_us, seq)` serves BATCH ASSEMBLY — ordered by `seq` across all streams, skipping rows
|
|
170
|
-
* whose deferred backoff has not elapsed
|
|
186
|
+
* whose deferred backoff has not elapsed;
|
|
187
|
+
* - `(acked_at_us, seq)` serves BOTH halves of the acked ledger (ADR-0060) with one index: the pending
|
|
188
|
+
* predicate `acked_at_us IS NULL ORDER BY seq` that every "pending" read now carries (assembly, the
|
|
189
|
+
* drain signal), and the retention sweep's `acked_at_us <= now - retention`. A partial index on `seq`
|
|
190
|
+
* `WHERE acked_at_us IS NULL` would serve the pending side slightly more tightly and leave the SWEEP
|
|
191
|
+
* with no index at all — it targets exactly the rows such an index excludes, which in a ledger-enabled
|
|
192
|
+
* store are most of the table. Leading on `acked_at_us` keeps both as range scans, and `seq` second
|
|
193
|
+
* keeps assembly's ordering free of a sort.
|
|
171
194
|
*/
|
|
172
195
|
function outboxStatements(localSchema: string): string[] {
|
|
173
196
|
const outboxTable = qualifyIdentifier(localSchema, OUTBOX_TABLE);
|
|
@@ -185,9 +208,11 @@ function outboxStatements(localSchema: string): string[] {
|
|
|
185
208
|
"attempt_count INTEGER NOT NULL DEFAULT 0",
|
|
186
209
|
"next_retry_at_us BIGINT",
|
|
187
210
|
"last_reason TEXT",
|
|
211
|
+
"acked_at_us BIGINT",
|
|
188
212
|
].join(",\n ")}\n);`,
|
|
189
213
|
renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_stream_seq_idx`, ["stream", "seq"]),
|
|
190
214
|
renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_retry_seq_idx`, ["next_retry_at_us", "seq"]),
|
|
215
|
+
renderCreateIndexStatement(outboxTable, `${OUTBOX_TABLE}_acked_seq_idx`, ["acked_at_us", "seq"]),
|
|
191
216
|
];
|
|
192
217
|
}
|
|
193
218
|
|
|
@@ -219,11 +244,13 @@ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, lo
|
|
|
219
244
|
const temp = ephemeral ? "TEMP " : "";
|
|
220
245
|
|
|
221
246
|
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
222
|
-
const
|
|
247
|
+
const projectedColumns = getProjectedColumns(entry);
|
|
248
|
+
const columns = projectedColumns.map(({ column }) => column);
|
|
223
249
|
const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
|
|
224
250
|
const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
|
|
225
251
|
|
|
226
252
|
statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
|
|
253
|
+
statements.push(...buildLocalIndexStatements(entry, projection.syncedTable, projectedColumns));
|
|
227
254
|
|
|
228
255
|
if (entry.mode === "readonly") {
|
|
229
256
|
return statements;
|
|
@@ -569,7 +596,6 @@ function buildReadModelViewSql(
|
|
|
569
596
|
throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);
|
|
570
597
|
}
|
|
571
598
|
|
|
572
|
-
const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);
|
|
573
599
|
const syncedLocalUpdatedExpression = columnNames.includes("updated_at_us") ? "t.updated_at_us" : "CAST(0 AS BIGINT)";
|
|
574
600
|
|
|
575
601
|
return [
|
|
@@ -585,14 +611,98 @@ function buildReadModelViewSql(
|
|
|
585
611
|
` 'synced' AS overlay_kind,`,
|
|
586
612
|
` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,
|
|
587
613
|
`FROM ${projection.syncedTable} AS t`,
|
|
588
|
-
|
|
589
|
-
" SELECT 1",
|
|
590
|
-
` FROM ${projection.overlayTable} AS o`,
|
|
591
|
-
` WHERE ${pkMatch}`,
|
|
592
|
-
")",
|
|
614
|
+
...buildOverlayNonMembershipTest(entry.primaryKey.columns, projection.overlayTable),
|
|
593
615
|
].join("\n");
|
|
594
616
|
}
|
|
595
617
|
|
|
618
|
+
/**
|
|
619
|
+
* Render the entry's OPT-IN `clientProjection.localIndexes` on its synced table (never on the overlay,
|
|
620
|
+
* never on the journal) through the same {@link renderCreateIndexStatement} core the journal indexes use,
|
|
621
|
+
* so every index this generator emits has one statement shape.
|
|
622
|
+
*
|
|
623
|
+
* Only what a consumer declared: a synced table's SERVER indexes are deliberately not mirrored (they serve
|
|
624
|
+
* server loads and routinely cover columns the client projection omits), so the local store carries the
|
|
625
|
+
* primary key plus exactly these. A column may be named by DB column name or by Drizzle property key — the
|
|
626
|
+
* either/or the primary-key specs accept — and is resolved to the DB column name here; the registry has
|
|
627
|
+
* already refused an unknown column, an omitted one, and a duplicate index name, so a name that fails to
|
|
628
|
+
* resolve at this point is a generator bug, not a consumer error.
|
|
629
|
+
*/
|
|
630
|
+
function buildLocalIndexStatements(
|
|
631
|
+
entry: SyncTableEntry,
|
|
632
|
+
syncedTable: string,
|
|
633
|
+
projectedColumns: ReturnType<typeof getProjectedColumns>,
|
|
634
|
+
): string[] {
|
|
635
|
+
const localIndexes = entry.clientProjection?.localIndexes ?? [];
|
|
636
|
+
if (localIndexes.length === 0) {
|
|
637
|
+
return [];
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const columnNameByKey = new Map<string, string>();
|
|
641
|
+
for (const { propertyKey, columnName } of projectedColumns) {
|
|
642
|
+
columnNameByKey.set(propertyKey, columnName);
|
|
643
|
+
columnNameByKey.set(columnName, columnName);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return localIndexes.map((index) => {
|
|
647
|
+
const columnExpressions = index.columns.map((column) => {
|
|
648
|
+
const columnName = columnNameByKey.get(column);
|
|
649
|
+
if (!columnName) {
|
|
650
|
+
throw new Error(
|
|
651
|
+
`local index ${index.name} on ${syncedTable} names column ${column}, which is not a projected column`,
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
return maybeQuoteIdentifier(columnName);
|
|
655
|
+
});
|
|
656
|
+
return renderCreateIndexStatement(syncedTable, maybeQuoteIdentifier(index.name), columnExpressions, {
|
|
657
|
+
...(index.unique === true ? { unique: true } : {}),
|
|
658
|
+
});
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* The synced branch's "this row is not shadowed by the overlay" test, as a NOT IN over the overlay's
|
|
664
|
+
* primary key — **a plan choice, not a style one**, and the one place the read model's cost is decided.
|
|
665
|
+
*
|
|
666
|
+
* The obvious form (`NOT EXISTS (SELECT 1 FROM overlay o WHERE o.pk = t.pk)`, and its `LEFT JOIN … IS
|
|
667
|
+
* NULL` twin) leaves the shape to the planner, and the planner gets it wrong in the overlay's NORMAL
|
|
668
|
+
* state. An overlay that is physically empty AND has been analysed reports `relpages = 0, reltuples = 0`,
|
|
669
|
+
* so `estimate_rel_size` skips its never-vacuumed 10-page floor and costs a scan of it at **0.00** — a
|
|
670
|
+
* free inner relation, which makes a `Nested Loop Anti Join` look cheapest. The executor then RESCANS the
|
|
671
|
+
* empty overlay once per synced row (`loops = <rowcount>`), and the rescan is not free: on 100k synced rows
|
|
672
|
+
* read through the view, that form measures ~180-260 ms against ~95-145 ms for a hash anti join
|
|
673
|
+
* (`tests/unit/read-model-overlay-plan` logs both per run), and a consumer measured 224 ms of a 270 ms
|
|
674
|
+
* selection sitting in that node. No index fixes it — the
|
|
675
|
+
* overlay's PRIMARY KEY already IS an index, and an index scan cannot beat a 0.00-cost seq scan; an
|
|
676
|
+
* `ANALYZE` does not fix it either, it is what CAUSES it (a never-analysed overlay gets the 10-page floor
|
|
677
|
+
* and plans as a hash anti join).
|
|
678
|
+
*
|
|
679
|
+
* `NOT IN` takes the choice away: the subquery is uncorrelated, so Postgres evaluates it ONCE into a
|
|
680
|
+
* hashed SubPlan and each synced row is a hash probe — measured ~95-215 ms in that same pathological state
|
|
681
|
+
* (roughly half the nested loop, machine-load dependent), 106 ms with no statistics at all, and 60 ms (vs
|
|
682
|
+
* 196 ms) for a composite key. The one cost is the tail:
|
|
683
|
+
* above roughly `hash_mem / (pk width + 24)` rows — order 150k pending overlay rows at the default 4 MB —
|
|
684
|
+
* the planner stops hashing and the SubPlan becomes a per-row rescan, which IS quadratic. That trade is
|
|
685
|
+
* taken deliberately: the overlay holds only rows with an unflushed local mutation, so tens of thousands
|
|
686
|
+
* is already an app in trouble, while "empty and analysed" is the steady state of every read-mostly table.
|
|
687
|
+
* (`EXPLAIN` tells the two apart: `hashed SubPlan` vs a bare `SubPlan`.)
|
|
688
|
+
*
|
|
689
|
+
* The NULL trap that normally disqualifies `NOT IN` cannot fire here: both sides are PRIMARY KEY columns
|
|
690
|
+
* of tables this generator emits (the overlay carries the same key as the synced table), so neither side
|
|
691
|
+
* can be NULL and `NOT IN` is exactly equivalent to the `NOT EXISTS` it replaces.
|
|
692
|
+
*/
|
|
693
|
+
function buildOverlayNonMembershipTest(primaryKeyColumns: string[], overlayTable: string): string[] {
|
|
694
|
+
const key =
|
|
695
|
+
primaryKeyColumns.length === 1
|
|
696
|
+
? `t.${primaryKeyColumns[0]}`
|
|
697
|
+
: `(${primaryKeyColumns.map((column) => `t.${column}`).join(", ")})`;
|
|
698
|
+
return [
|
|
699
|
+
`WHERE ${key} NOT IN (`,
|
|
700
|
+
` SELECT ${primaryKeyColumns.map((column) => `o.${column}`).join(", ")}`,
|
|
701
|
+
` FROM ${overlayTable} AS o`,
|
|
702
|
+
")",
|
|
703
|
+
];
|
|
704
|
+
}
|
|
705
|
+
|
|
596
706
|
function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {
|
|
597
707
|
return [
|
|
598
708
|
...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),
|
|
@@ -619,7 +729,7 @@ function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[]
|
|
|
619
729
|
* takes the UNqualified relation name (the TEMP keyword places it in `pg_temp`; a `CREATE TEMP TABLE
|
|
620
730
|
* pg_temp.x` target is not portable). Same relation/index NAMES as the durable form: an index name lives
|
|
621
731
|
* per schema, so the durable (metadata-schema) and session (`pg_temp`) indexes coexist without collision
|
|
622
|
-
* (probed on real
|
|
732
|
+
* (probed on real pgwasm).
|
|
623
733
|
*
|
|
624
734
|
* CAVEAT — the `temp` flag only bares the RELATION name; `buildTableColumnSql` below still receives
|
|
625
735
|
* `schemaName` and would qualify any ENUM column type into THAT schema. That is correct only because the
|
|
@@ -982,10 +1092,6 @@ function readArrayDimensions(column: TableColumn) {
|
|
|
982
1092
|
return arrayColumn.dimensions ?? 0;
|
|
983
1093
|
}
|
|
984
1094
|
|
|
985
|
-
function buildPrimaryKeyMatch(primaryKeyColumns: string[]) {
|
|
986
|
-
return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(" AND ");
|
|
987
|
-
}
|
|
988
|
-
|
|
989
1095
|
function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {
|
|
990
1096
|
const projection = baseProjection(entry, tableKey);
|
|
991
1097
|
const syncedTableName = projection.syncedTable ?? tableKey;
|