@pgxsinkit/client 0.1.49 → 0.1.50

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/src/schema.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  getLocalSyncPrimaryKeyColumns,
7
7
  getSyncRegistrySchema,
8
8
  getProjectedColumns,
9
+ hashString,
9
10
  maybeQuoteIdentifier,
10
11
  quoteIdentifier,
11
12
  quoteSqlLiteral as quoteSqlStringLiteral,
@@ -43,12 +44,72 @@ interface ResolvedProjection {
43
44
  */
44
45
  export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
45
46
  export const REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
47
+ /**
48
+ * The `pgxsinkit_local_meta` key holding the DURABLE-schema fingerprint the local store was last
49
+ * provisioned under (warm-persisted-store-startup slice 3 / proposal §3). Its value is
50
+ * `lsf1:<hash(durable SQL)>` (see {@link computeLocalSchemaFingerprint}); a boot compares it against the
51
+ * freshly-generated durable SQL's hash to SKIP the durable replay when they match.
52
+ */
53
+ export const LOCAL_SCHEMA_FINGERPRINT_KEY = "local_schema_fingerprint";
54
+ /** The versioned value prefix for {@link LOCAL_SCHEMA_FINGERPRINT_KEY} (bump only if the encoding changes). */
55
+ export const LOCAL_SCHEMA_FINGERPRINT_PREFIX = "lsf1:";
56
+
57
+ /**
58
+ * The registry-wide cross-journal mutation view (warm-persisted-store-startup slice 4 / proposal §5,
59
+ * option 1). A `TEMP` view UNION-ALL-ing every writable table's journal down to the shared fixed columns
60
+ * (plus a `table_key` literal per branch), so a consumer can render one global mutation summary/detail
61
+ * subscription instead of one live query per writable journal. It MUST be `TEMP`: an ephemeral entry's
62
+ * journal is a `pg_temp` relation (ADR-0021 §3), which a durable view cannot reference — and it is
63
+ * recreated on every engine boot (a TEMP view dies with the old engine), so it lives in the always-applied
64
+ * ephemeral schema portion, NOT the durable (fingerprint-gated) portion. See {@link getAllMutationsView}
65
+ * for the query-authoring Drizzle object over it.
66
+ */
67
+ export const ALL_MUTATIONS_VIEW = "pgxsinkit_all_mutations";
68
+
69
+ /**
70
+ * The shared fixed journal columns the {@link ALL_MUTATIONS_VIEW} branches project (in journal-DDL order),
71
+ * mirroring `buildJournalFixedColumns` (local-tables.ts) MINUS `payload_json` (detail rows stay
72
+ * payload-free by default — entity identity comes from `entity_key_json`) and the per-table PRIMARY KEY
73
+ * columns (they differ per branch, so they cannot appear in a UNION ALL). `mutation_seq` is retained: it is
74
+ * a shared fixed column and {@link import("./mutation").MutationDetail} carries it — but it is per-journal,
75
+ * NOT globally ordered, so the detail API orders by `enqueued_at_us`, never this.
76
+ */
77
+ export const ALL_MUTATIONS_JOURNAL_COLUMNS = [
78
+ "mutation_id",
79
+ "entity_key_json",
80
+ "mutation_seq",
81
+ "mutation_kind",
82
+ "status",
83
+ "registry_version",
84
+ "base_server_version",
85
+ "write_unit",
86
+ "write_mode",
87
+ "attempt_count",
88
+ "last_error",
89
+ "last_http_status",
90
+ "conflict_reason",
91
+ "server_updated_at_us",
92
+ "enqueued_at_us",
93
+ "next_retry_at_us",
94
+ "sent_at_us",
95
+ "acked_at_us",
96
+ "updated_at_us",
97
+ ] as const;
46
98
 
47
99
  type TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number]["column"];
48
100
 
49
- export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
101
+ /** Join a statement list into a single executable script, matching the historical generator's separator. */
102
+ function joinSchemaStatements(statements: string[]): string {
103
+ return `${statements.join("\n\n")}\n`;
104
+ }
105
+
106
+ /**
107
+ * The schema-create (non-public only) + `pgxsinkit_local_meta` CREATE-IF-NOT-EXISTS — the minimal durable
108
+ * bootstrap every boot needs BEFORE it can read/write the local-schema fingerprint. Emitted standalone by
109
+ * {@link buildLocalMetaBootstrapSql}, and first in the durable statement stream.
110
+ */
111
+ function localMetaBootstrapStatements(localSchema: string): string[] {
50
112
  const statements: string[] = [];
51
- const localSchema = getSyncRegistrySchema(registry);
52
113
 
53
114
  if (localSchema !== "public") {
54
115
  statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
@@ -61,222 +122,374 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
61
122
  ].join(",\n ")}\n);`,
62
123
  );
63
124
 
64
- const enumDefinitions = collectEnumDefinitions(registry, localSchema);
125
+ return statements;
126
+ }
65
127
 
66
- for (const enumDefinition of enumDefinitions) {
67
- statements.push(buildCreateEnumTypeSql(enumDefinition));
128
+ /**
129
+ * The minimal durable bootstrap (schema + meta table) as an executable script (slice 3). Run as the first,
130
+ * tiny crossing on every client-owned boot so the `local_schema_fingerprint` read/write has its table before
131
+ * the fingerprint fast path decides whether to replay the rest of the durable schema. Depends on the
132
+ * registry only for its local schema name, so it is a function rather than a bare constant.
133
+ */
134
+ export function buildLocalMetaBootstrapSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
135
+ return joinSchemaStatements(localMetaBootstrapStatements(getSyncRegistrySchema(registry)));
136
+ }
137
+
138
+ /**
139
+ * Build the full DDL cluster for ONE registry entry — synced table, and (for a writable entry) overlay,
140
+ * sequence, journal + its indexes, reconcile function + trigger, and the read-model/sync-state views. This
141
+ * is the per-entry body {@link generateDurableLocalSchemaSql} and {@link generateEphemeralLocalSchemaSql}
142
+ * share (partitioned by `retention === "ephemeral"`), so the two paths cannot drift.
143
+ *
144
+ * ADR-0021 §3: an `ephemeral` entry's whole cluster is emitted as `TEMP` — bare (unqualified) object names
145
+ * that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together (no durable
146
+ * trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema. For a persistent
147
+ * entry `temp` is "" and `objectSchema` is the registry schema.
148
+ */
149
+ function buildEntryClusterStatements(entry: SyncTableEntry, tableKey: string, localSchema: string): string[] {
150
+ const statements: string[] = [];
151
+ const ephemeral = entry.retention === "ephemeral";
152
+ const objectSchema = ephemeral ? "public" : localSchema;
153
+ const temp = ephemeral ? "TEMP " : "";
154
+
155
+ const projection = getClientProjection(entry, tableKey, objectSchema);
156
+ const columns = getProjectedColumns(entry).map(({ column }) => column);
157
+ const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
158
+ const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
159
+
160
+ statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
161
+
162
+ if (entry.mode === "readonly") {
163
+ return statements;
68
164
  }
69
165
 
70
- for (const [tableKey, entry] of Object.entries(registry)) {
71
- // ADR-0021 §3: an `ephemeral` table's whole cluster is emitted as `TEMP` — bare (unqualified) object
72
- // names that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together
73
- // (no durable trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema.
74
- // For a persistent table `temp` is "" and `objectSchema` is the registry schema → byte-identical output.
75
- const ephemeral = entry.retention === "ephemeral";
76
- const objectSchema = ephemeral ? "public" : localSchema;
77
- const temp = ephemeral ? "TEMP " : "";
166
+ if (!projection.overlayTable || !projection.journalTable) {
167
+ throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);
168
+ }
78
169
 
79
- const projection = getClientProjection(entry, tableKey, objectSchema);
80
- const columns = getProjectedColumns(entry).map(({ column }) => column);
81
- const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
82
- const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
170
+ const journalTableName = entry.clientProjection?.journalTable;
83
171
 
84
- statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
172
+ if (!journalTableName) {
173
+ throw new Error(`journal table is required for writable table ${tableKey}`);
174
+ }
85
175
 
86
- if (entry.mode === "readonly") {
87
- continue;
88
- }
176
+ const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
177
+ const column = columns.find((candidate) => candidate.name === columnName);
89
178
 
90
- if (!projection.overlayTable || !projection.journalTable) {
91
- throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);
179
+ if (!column) {
180
+ throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
92
181
  }
93
182
 
94
- const journalTableName = entry.clientProjection?.journalTable;
183
+ return column;
184
+ });
185
+ const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
186
+ const journalSequenceName = buildJournalSequenceName(journalTableName);
187
+ const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
188
+
189
+ statements.push(
190
+ `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\n ${[
191
+ ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),
192
+ "overlay_kind VARCHAR(24) NOT NULL",
193
+ "local_updated_at_us BIGINT NOT NULL",
194
+ ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),
195
+ ].join(",\n ")}\n);`,
196
+ );
197
+
198
+ statements.push(
199
+ `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,
200
+ );
201
+
202
+ statements.push(
203
+ `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\n ${[
204
+ "mutation_id UUID PRIMARY KEY",
205
+ ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),
206
+ "entity_key_json TEXT NOT NULL",
207
+ `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
208
+ "mutation_kind VARCHAR(24) NOT NULL",
209
+ "status VARCHAR(24) NOT NULL",
210
+ // The registry fingerprint (ADR-0004) this mutation was authored under, so a
211
+ // version-boundary crossing is known before sending (ADR-0006 decision 4).
212
+ "registry_version TEXT",
213
+ // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation
214
+ // was authored. The slot lives on the journal (per-mutation, like registry_version above);
215
+ // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.
216
+ "base_server_version BIGINT",
217
+ // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared
218
+ // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path
219
+ // (an untagged mutation), where the flusher derives mode + unit from the table's static group.
220
+ "write_unit TEXT",
221
+ "write_mode VARCHAR(24)",
222
+ "payload_json TEXT NOT NULL",
223
+ "attempt_count INTEGER NOT NULL DEFAULT 0",
224
+ "last_error TEXT",
225
+ "last_http_status INTEGER",
226
+ "conflict_reason TEXT",
227
+ "server_updated_at_us BIGINT",
228
+ "enqueued_at_us BIGINT NOT NULL",
229
+ "next_retry_at_us BIGINT",
230
+ "sent_at_us BIGINT",
231
+ "acked_at_us BIGINT",
232
+ "updated_at_us BIGINT NOT NULL",
233
+ ].join(",\n ")}\n);`,
234
+ );
235
+
236
+ // Journal indexes render through the SAME core the pgTable-driven renderer uses
237
+ // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement
238
+ // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable
239
+ // path is the one that quotes) — output stays byte-identical to the former hand-built statements.
240
+ statements.push(
241
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, ["status", "enqueued_at_us"]),
242
+ );
243
+ statements.push(
244
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [
245
+ "status",
246
+ "next_retry_at_us",
247
+ "enqueued_at_us",
248
+ ]),
249
+ );
250
+ statements.push(
251
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
252
+ ...entry.primaryKey.columns,
253
+ "mutation_seq",
254
+ ]),
255
+ );
256
+ statements.push(
257
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
258
+ "entity_key_json",
259
+ "mutation_seq",
260
+ ]),
261
+ );
262
+ statements.push(
263
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [
264
+ "entity_key_json",
265
+ "status",
266
+ "mutation_seq",
267
+ ]),
268
+ );
269
+
270
+ // Trigger: automatically clear overlay + journal entries when the sync
271
+ // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
272
+ // (row removed on server, synced back via Electric).
273
+ const pkMatchSql = (alias: string) =>
274
+ primaryKeyColumns
275
+ .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
276
+ .join(" AND ");
277
+ const pkOverlayMatchSql = primaryKeyColumns
278
+ .map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
279
+ .join(" AND ");
280
+
281
+ // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches
282
+ // the write's acked version — never on a bare key-match, which a stale or reordered echo could
283
+ // satisfy and flip the read model to neither the optimistic nor the converged value. A delete
284
+ // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads
285
+ // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with
286
+ // reconcileTable (mutation.ts), so the two sites cannot drift.
287
+ const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "NEW" });
288
+
289
+ // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table
290
+ // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.
291
+ const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;
292
+
293
+ statements.push(
294
+ `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\n` +
295
+ `BEGIN\n` +
296
+ ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\n` +
297
+ ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\n` +
298
+ ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\n` +
299
+ ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\n` +
300
+ ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\n` +
301
+ ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\n` +
302
+ ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\n` +
303
+ ` DELETE FROM ${projection.journalTable} AS "conflicted"\n` +
304
+ ` USING ${projection.journalTable} AS "resolver"\n` +
305
+ ` WHERE "conflicted".status = 'conflicted' AND (${pkMatchSql("conflicted")})\n` +
306
+ ` AND "resolver".entity_key_json = "conflicted".entity_key_json\n` +
307
+ ` AND "resolver".mutation_seq > "conflicted".mutation_seq\n` +
308
+ ` AND "resolver".status = 'acked';\n` +
309
+ ` DELETE FROM ${projection.journalTable} AS "journal"\n` +
310
+ ` WHERE status = 'acked' AND (${pkMatchSql("journal")})\n` +
311
+ ` AND (\n` +
312
+ ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\n` +
313
+ ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\n` +
314
+ ` );\n` +
315
+ ` DELETE FROM ${projection.overlayTable} AS "overlay"\n` +
316
+ ` WHERE (${pkOverlayMatchSql})\n` +
317
+ ` AND NOT EXISTS (\n` +
318
+ ` SELECT 1 FROM ${projection.journalTable} AS j\n` +
319
+ ` WHERE (${pkMatchSql("j")})\n` +
320
+ ` );\n` +
321
+ ` RETURN COALESCE(NEW, OLD);\n` +
322
+ `END;\n` +
323
+ `$$ LANGUAGE plpgsql;`,
324
+ );
325
+
326
+ statements.push(
327
+ `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\n` +
328
+ `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\n` +
329
+ `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,
330
+ );
331
+
332
+ statements.push(
333
+ `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
334
+ entry,
335
+ projection,
336
+ columns.map((column) => column.name),
337
+ )};`,
338
+ );
339
+
340
+ // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +
341
+ // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the
342
+ // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).
343
+ statements.push(
344
+ `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\n${buildSyncStateView(entry, {
345
+ syncedTable: projection.syncedTable,
346
+ overlayTable: projection.overlayTable,
347
+ journalTable: projection.journalTable,
348
+ })};`,
349
+ );
350
+
351
+ return statements;
352
+ }
353
+
354
+ /**
355
+ * The DURABLE half of the local schema (slice 3): the schema + `pgxsinkit_local_meta` bootstrap, ALL enum
356
+ * types the registry references (enums are persistent DB objects — they live in the durable schema even for
357
+ * ephemeral tables, ADR-0021 §3 — so they belong here and their change invalidates the fingerprint), and the
358
+ * full cluster of every PERSISTENT entry, in registry order. This is the exact statement stream the
359
+ * `local_schema_fingerprint` hashes and the boot fast path may SKIP on a warm store.
360
+ */
361
+ function durableSchemaStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
362
+ const localSchema = getSyncRegistrySchema(registry);
363
+ const statements: string[] = [...localMetaBootstrapStatements(localSchema)];
95
364
 
96
- if (!journalTableName) {
97
- throw new Error(`journal table is required for writable table ${tableKey}`);
365
+ for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
366
+ statements.push(buildCreateEnumTypeSql(enumDefinition));
367
+ }
368
+
369
+ for (const [tableKey, entry] of Object.entries(registry)) {
370
+ if (entry.retention === "ephemeral") {
371
+ continue;
98
372
  }
99
373
 
100
- const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {
101
- const column = columns.find((candidate) => candidate.name === columnName);
374
+ statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
375
+ }
102
376
 
103
- if (!column) {
104
- throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);
105
- }
377
+ return statements;
378
+ }
106
379
 
107
- return column;
108
- });
109
- const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
110
- const journalSequenceName = buildJournalSequenceName(journalTableName);
111
- const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
112
-
113
- statements.push(
114
- `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\n ${[
115
- ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),
116
- "overlay_kind VARCHAR(24) NOT NULL",
117
- "local_updated_at_us BIGINT NOT NULL",
118
- ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),
119
- ].join(",\n ")}\n);`,
120
- );
380
+ /**
381
+ * The EPHEMERAL half of the local schema (slice 3): re-emitted idempotent enum guards for the enums the
382
+ * ephemeral entries reference (a subset of the durable enum header — the `DO $$ IF NOT EXISTS` blocks are
383
+ * cheap no-ops when the durable enums already exist, and re-emitting removes any ordering dependency on the
384
+ * durable portion when this runs standalone on a fingerprint-skipped warm boot), followed by the full TEMP
385
+ * cluster of every EPHEMERAL entry, and finally the registry-wide `pgxsinkit_all_mutations` TEMP VIEW
386
+ * (slice 4) whenever the registry has ≥1 writable table. Always applied on boot (TEMP relations die with the
387
+ * old engine), and empty (`[]`) only when the registry declares no ephemeral entry AND no writable table, so
388
+ * the boot skips the crossing entirely.
389
+ */
390
+ function ephemeralSchemaStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
391
+ const localSchema = getSyncRegistrySchema(registry);
392
+ const ephemeralEntries = Object.entries(registry).filter(([, entry]) => entry.retention === "ephemeral");
121
393
 
122
- statements.push(
123
- `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,
124
- );
394
+ const statements: string[] = [];
125
395
 
126
- statements.push(
127
- `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\n ${[
128
- "mutation_id UUID PRIMARY KEY",
129
- ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),
130
- "entity_key_json TEXT NOT NULL",
131
- `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
132
- "mutation_kind VARCHAR(24) NOT NULL",
133
- "status VARCHAR(24) NOT NULL",
134
- // The registry fingerprint (ADR-0004) this mutation was authored under, so a
135
- // version-boundary crossing is known before sending (ADR-0006 decision 4).
136
- "registry_version TEXT",
137
- // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation
138
- // was authored. The slot lives on the journal (per-mutation, like registry_version above);
139
- // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.
140
- "base_server_version BIGINT",
141
- // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared
142
- // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path
143
- // (an untagged mutation), where the flusher derives mode + unit from the table's static group.
144
- "write_unit TEXT",
145
- "write_mode VARCHAR(24)",
146
- "payload_json TEXT NOT NULL",
147
- "attempt_count INTEGER NOT NULL DEFAULT 0",
148
- "last_error TEXT",
149
- "last_http_status INTEGER",
150
- "conflict_reason TEXT",
151
- "server_updated_at_us BIGINT",
152
- "enqueued_at_us BIGINT NOT NULL",
153
- "next_retry_at_us BIGINT",
154
- "sent_at_us BIGINT",
155
- "acked_at_us BIGINT",
156
- "updated_at_us BIGINT NOT NULL",
157
- ].join(",\n ")}\n);`,
158
- );
396
+ if (ephemeralEntries.length > 0) {
397
+ for (const enumDefinition of collectEnumDefinitionsFromEntries(
398
+ ephemeralEntries.map(([, entry]) => entry),
399
+ localSchema,
400
+ )) {
401
+ statements.push(buildCreateEnumTypeSql(enumDefinition));
402
+ }
159
403
 
160
- // Journal indexes render through the SAME core the pgTable-driven renderer uses
161
- // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement
162
- // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable
163
- // path is the one that quotes) — output stays byte-identical to the former hand-built statements.
164
- statements.push(
165
- renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [
166
- "status",
167
- "enqueued_at_us",
168
- ]),
169
- );
170
- statements.push(
171
- renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [
172
- "status",
173
- "next_retry_at_us",
174
- "enqueued_at_us",
175
- ]),
176
- );
177
- statements.push(
178
- renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
179
- ...entry.primaryKey.columns,
180
- "mutation_seq",
181
- ]),
182
- );
183
- statements.push(
184
- renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
185
- "entity_key_json",
186
- "mutation_seq",
187
- ]),
188
- );
189
- statements.push(
190
- renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [
191
- "entity_key_json",
192
- "status",
193
- "mutation_seq",
194
- ]),
195
- );
404
+ for (const [tableKey, entry] of ephemeralEntries) {
405
+ statements.push(...buildEntryClusterStatements(entry, tableKey, localSchema));
406
+ }
407
+ }
196
408
 
197
- // Trigger: automatically clear overlay + journal entries when the sync
198
- // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
199
- // (row removed on server, synced back via Electric).
200
- const pkMatchSql = (alias: string) =>
201
- primaryKeyColumns
202
- .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
203
- .join(" AND ");
204
- const pkOverlayMatchSql = primaryKeyColumns
205
- .map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
206
- .join(" AND ");
409
+ // The registry-wide cross-journal mutation view (slice 4). Always-applied and TEMP (correction 4): it may
410
+ // reference `pg_temp` ephemeral journals AND persistent journals, so it lives here regardless of whether the
411
+ // registry declares any ephemeral entry. Emitted only when the registry has ≥1 writable table (a journal to
412
+ // union); a registry of only readonly tables emits nothing and this whole portion stays empty.
413
+ statements.push(...allMutationsViewStatements(registry));
207
414
 
208
- // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches
209
- // the write's acked version — never on a bare key-match, which a stale or reordered echo could
210
- // satisfy and flip the read model to neither the optimistic nor the converged value. A delete
211
- // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads
212
- // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with
213
- // reconcileTable (mutation.ts), so the two sites cannot drift.
214
- const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "NEW" });
215
-
216
- // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table
217
- // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.
218
- const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;
219
-
220
- statements.push(
221
- `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\n` +
222
- `BEGIN\n` +
223
- ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\n` +
224
- ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\n` +
225
- ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\n` +
226
- ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\n` +
227
- ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\n` +
228
- ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\n` +
229
- ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\n` +
230
- ` DELETE FROM ${projection.journalTable} AS "conflicted"\n` +
231
- ` USING ${projection.journalTable} AS "resolver"\n` +
232
- ` WHERE "conflicted".status = 'conflicted' AND (${pkMatchSql("conflicted")})\n` +
233
- ` AND "resolver".entity_key_json = "conflicted".entity_key_json\n` +
234
- ` AND "resolver".mutation_seq > "conflicted".mutation_seq\n` +
235
- ` AND "resolver".status = 'acked';\n` +
236
- ` DELETE FROM ${projection.journalTable} AS "journal"\n` +
237
- ` WHERE status = 'acked' AND (${pkMatchSql("journal")})\n` +
238
- ` AND (\n` +
239
- ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\n` +
240
- ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\n` +
241
- ` );\n` +
242
- ` DELETE FROM ${projection.overlayTable} AS "overlay"\n` +
243
- ` WHERE (${pkOverlayMatchSql})\n` +
244
- ` AND NOT EXISTS (\n` +
245
- ` SELECT 1 FROM ${projection.journalTable} AS j\n` +
246
- ` WHERE (${pkMatchSql("j")})\n` +
247
- ` );\n` +
248
- ` RETURN COALESCE(NEW, OLD);\n` +
249
- `END;\n` +
250
- `$$ LANGUAGE plpgsql;`,
251
- );
415
+ return statements;
416
+ }
252
417
 
253
- statements.push(
254
- `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\n` +
255
- `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\n` +
256
- `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,
257
- );
418
+ /**
419
+ * The `CREATE OR REPLACE TEMP VIEW pgxsinkit_all_mutations` statement (slice 4 / proposal §5, option 1), or
420
+ * `[]` when the registry has no writable table. Each branch selects a `table_key` literal plus the shared
421
+ * fixed journal columns ({@link ALL_MUTATIONS_JOURNAL_COLUMNS}) from one writable journal, UNION-ALL-ed.
422
+ * Generated DDL (existing generator style): the branch column list is a fixed identifier set and each
423
+ * `table_key` is a bound string literal — every RUNTIME query authors over {@link getAllMutationsView}
424
+ * (tier ①), never this text. The journal name resolves through the SAME `getClientProjection` the DDL
425
+ * generator uses (ephemeral → bare `pg_temp` name; persistent → schema-qualified), so the two cannot drift.
426
+ */
427
+ function allMutationsViewStatements<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
428
+ const localSchema = getSyncRegistrySchema(registry);
429
+ const branches: string[] = [];
258
430
 
259
- statements.push(
260
- `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
261
- entry,
262
- projection,
263
- columns.map((column) => column.name),
264
- )};`,
265
- );
431
+ for (const [tableKey, entry] of Object.entries(registry)) {
432
+ if (entry.mode === "readonly" || !entry.clientProjection?.journalTable) {
433
+ continue;
434
+ }
435
+
436
+ const objectSchema = entry.retention === "ephemeral" ? "public" : localSchema;
437
+ const projection = getClientProjection(entry, tableKey, objectSchema);
438
+
439
+ if (!projection.journalTable) {
440
+ continue;
441
+ }
266
442
 
267
- // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +
268
- // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the
269
- // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).
270
- statements.push(
271
- `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\n${buildSyncStateView(entry, {
272
- syncedTable: projection.syncedTable,
273
- overlayTable: projection.overlayTable,
274
- journalTable: projection.journalTable,
275
- })};`,
443
+ branches.push(
444
+ `SELECT ${quoteSqlStringLiteral(tableKey)} AS table_key,\n ${ALL_MUTATIONS_JOURNAL_COLUMNS.join(",\n ")}\nFROM ${projection.journalTable}`,
276
445
  );
277
446
  }
278
447
 
279
- return `${statements.join("\n\n")}\n`;
448
+ if (branches.length === 0) {
449
+ return [];
450
+ }
451
+
452
+ return [`CREATE OR REPLACE TEMP VIEW ${ALL_MUTATIONS_VIEW} AS\n${branches.join("\nUNION ALL\n")};`];
453
+ }
454
+
455
+ /** The DURABLE local schema as an executable script (slice 3) — the fingerprint's basis. See {@link durableSchemaStatements}. */
456
+ export function generateDurableLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
457
+ return joinSchemaStatements(durableSchemaStatements(registry));
458
+ }
459
+
460
+ /**
461
+ * The EPHEMERAL (always-applied) local schema as an executable script (slice 3), or `""` when the registry
462
+ * has no ephemeral entry (so the boot skips the crossing). See {@link ephemeralSchemaStatements}.
463
+ */
464
+ export function generateEphemeralLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
465
+ const statements = ephemeralSchemaStatements(registry);
466
+ return statements.length === 0 ? "" : joinSchemaStatements(statements);
467
+ }
468
+
469
+ /**
470
+ * The complete local schema — durable statements then ephemeral statements — the single script the
471
+ * wipe/rebuild paths and every external caller keep using. For an all-persistent registry the durable stream
472
+ * IS the historical stream in registry order, now followed by the always-applied ephemeral portion — which
473
+ * for any registry with a writable table carries the `pgxsinkit_all_mutations` TEMP VIEW (slice 4), so the
474
+ * full script is no longer byte-identical to the pre-slice-4 output (it gains the trailing view). For a MIXED
475
+ * registry it is also idempotent-equivalent, NOT byte-identical to a single-pass interleave: the persistent
476
+ * clusters precede the ephemeral ones and the ephemeral portion re-emits idempotent enum guards — a
477
+ * reordering of independent `IF NOT EXISTS` DDL that executes to the same schema. Equals `durable + ephemeral`
478
+ * by construction (test-covered).
479
+ */
480
+ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
481
+ return joinSchemaStatements([...durableSchemaStatements(registry), ...ephemeralSchemaStatements(registry)]);
482
+ }
483
+
484
+ /**
485
+ * The durable-schema fingerprint value (slice 3 / proposal §3): `lsf1:<FNV-1a hash of the durable SQL>`. The
486
+ * hash is over the generated durable DDL body itself (no composed inputs, no hand-maintained format-version
487
+ * constant), so it auto-invalidates on ANY generator change, registry change, or projection rename — the
488
+ * ADR-0018 apply-function-fingerprint precedent applied to the local schema. Stamped into
489
+ * {@link LOCAL_SCHEMA_FINGERPRINT_KEY} only after a successful durable exec.
490
+ */
491
+ export function computeLocalSchemaFingerprint<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
492
+ return `${LOCAL_SCHEMA_FINGERPRINT_PREFIX}${hashString(generateDurableLocalSchemaSql(registry))}`;
280
493
  }
281
494
 
282
495
  function buildReadModelViewSql(