@pgxsinkit/client 0.1.32 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
package/src/schema.ts CHANGED
@@ -1,21 +1,49 @@
1
- import { getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
1
+ import { getTableConfig, getViewConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
 
3
3
  import {
4
+ buildOverlayResolutionBarrier,
5
+ buildSyncStateView,
4
6
  getLocalSyncPrimaryKeyColumns,
5
7
  getSyncRegistrySchema,
6
8
  getProjectedColumns,
9
+ maybeQuoteIdentifier,
10
+ quoteIdentifier,
11
+ quoteSqlLiteral as quoteSqlStringLiteral,
7
12
  type SyncTableEntry,
8
13
  type SyncTableRegistry,
9
14
  } from "@pgxsinkit/contracts";
10
15
 
16
+ import { buildClearShapeTagsSql, shapeTableId } from "./sync/tags";
17
+
11
18
  /** Internal fully-qualified projection used within schema generation. */
12
19
  interface ResolvedProjection {
13
20
  syncedTable: string;
14
21
  overlayTable?: string;
15
22
  journalTable?: string;
16
23
  readModel: string;
24
+ /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */
25
+ syncState: string;
26
+ /**
27
+ * The reconcile trigger's function — schema-qualified, because a function is a schema object.
28
+ * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a
29
+ * non-public schema's qualified name into invalid SQL).
30
+ */
31
+ reconcileFunction: string;
32
+ /**
33
+ * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it
34
+ * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.
35
+ */
36
+ reconcileTrigger: string;
17
37
  }
18
38
 
39
+ /**
40
+ * Local key/value metadata table. Holds the registry fingerprint the local store was
41
+ * provisioned under (ADR-0006), so a registry change is detected on boot and the read
42
+ * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.
43
+ */
44
+ export const LOCAL_META_TABLE = "pgxsinkit_local_meta";
45
+ export const REGISTRY_FINGERPRINT_KEY = "registry_fingerprint";
46
+
19
47
  type TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number]["column"];
20
48
 
21
49
  export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {
@@ -26,6 +54,13 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
26
54
  statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
27
55
  }
28
56
 
57
+ statements.push(
58
+ `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\n ${[
59
+ "key TEXT PRIMARY KEY",
60
+ "value TEXT NOT NULL",
61
+ ].join(",\n ")}\n);`,
62
+ );
63
+
29
64
  const enumDefinitions = collectEnumDefinitions(registry, localSchema);
30
65
 
31
66
  for (const enumDefinition of enumDefinitions) {
@@ -33,12 +68,20 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
33
68
  }
34
69
 
35
70
  for (const [tableKey, entry] of Object.entries(registry)) {
36
- const projection = getClientProjection(entry, tableKey, localSchema);
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 " : "";
78
+
79
+ const projection = getClientProjection(entry, tableKey, objectSchema);
37
80
  const columns = getProjectedColumns(entry).map(({ column }) => column);
38
81
  const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);
39
82
  const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);
40
83
 
41
- statements.push(`CREATE TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
84
+ statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\n ${baseColumnsSql}\n);`);
42
85
 
43
86
  if (entry.mode === "readonly") {
44
87
  continue;
@@ -65,10 +108,10 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
65
108
  });
66
109
  const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);
67
110
  const journalSequenceName = buildJournalSequenceName(journalTableName);
68
- const qualifiedJournalSequenceName = qualifyIdentifier(localSchema, journalSequenceName);
111
+ const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);
69
112
 
70
113
  statements.push(
71
- `CREATE TABLE IF NOT EXISTS ${projection.overlayTable} (\n ${[
114
+ `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\n ${[
72
115
  ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),
73
116
  "overlay_kind VARCHAR(24) NOT NULL",
74
117
  "local_updated_at_us BIGINT NOT NULL",
@@ -77,17 +120,29 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
77
120
  );
78
121
 
79
122
  statements.push(
80
- `CREATE SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,
123
+ `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,
81
124
  );
82
125
 
83
126
  statements.push(
84
- `CREATE TABLE IF NOT EXISTS ${projection.journalTable} (\n ${[
127
+ `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\n ${[
85
128
  "mutation_id UUID PRIMARY KEY",
86
129
  ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),
87
130
  "entity_key_json TEXT NOT NULL",
88
131
  `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,
89
132
  "mutation_kind VARCHAR(24) NOT NULL",
90
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)",
91
146
  "payload_json TEXT NOT NULL",
92
147
  "attempt_count INTEGER NOT NULL DEFAULT 0",
93
148
  "last_error TEXT",
@@ -102,27 +157,46 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
102
157
  ].join(",\n ")}\n);`,
103
158
  );
104
159
 
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.
105
164
  statements.push(
106
- `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_status_idx ON ${projection.journalTable} (status, enqueued_at_us);`,
165
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [
166
+ "status",
167
+ "enqueued_at_us",
168
+ ]),
107
169
  );
108
170
  statements.push(
109
- `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_status_retry_idx ON ${projection.journalTable} (status, next_retry_at_us, enqueued_at_us);`,
171
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [
172
+ "status",
173
+ "next_retry_at_us",
174
+ "enqueued_at_us",
175
+ ]),
110
176
  );
111
177
  statements.push(
112
- `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_pk_seq_idx ON ${projection.journalTable} (${entry.primaryKey.columns.join(", ")}, mutation_seq);`,
178
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
179
+ ...entry.primaryKey.columns,
180
+ "mutation_seq",
181
+ ]),
113
182
  );
114
183
  statements.push(
115
- `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_seq_idx ON ${projection.journalTable} (entity_key_json, mutation_seq);`,
184
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
185
+ "entity_key_json",
186
+ "mutation_seq",
187
+ ]),
116
188
  );
117
189
  statements.push(
118
- `CREATE INDEX IF NOT EXISTS ${baseProjection(entry, tableKey).journalTable}_entity_status_seq_idx ON ${projection.journalTable} (entity_key_json, status, mutation_seq);`,
190
+ renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [
191
+ "entity_key_json",
192
+ "status",
193
+ "mutation_seq",
194
+ ]),
119
195
  );
120
196
 
121
197
  // Trigger: automatically clear overlay + journal entries when the sync
122
198
  // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE
123
199
  // (row removed on server, synced back via Electric).
124
- const triggerFnName = `${projection.syncedTable}_reconcile_on_sync`;
125
-
126
200
  const pkMatchSql = (alias: string) =>
127
201
  primaryKeyColumns
128
202
  .map((col) => `"${alias}"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
@@ -131,11 +205,40 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
131
205
  .map((col) => `"overlay"."${col.name}" = COALESCE(NEW."${col.name}", OLD."${col.name}")`)
132
206
  .join(" AND ");
133
207
 
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
+
134
220
  statements.push(
135
- `CREATE OR REPLACE FUNCTION ${triggerFnName}() RETURNS TRIGGER AS $$\n` +
221
+ `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\n` +
136
222
  `BEGIN\n` +
137
- ` DELETE FROM ${projection.journalTable}\n` +
138
- ` WHERE status = 'acked' AND (${pkMatchSql(projection.journalTable)});\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` +
139
242
  ` DELETE FROM ${projection.overlayTable} AS "overlay"\n` +
140
243
  ` WHERE (${pkOverlayMatchSql})\n` +
141
244
  ` AND NOT EXISTS (\n` +
@@ -148,18 +251,29 @@ export function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(regi
148
251
  );
149
252
 
150
253
  statements.push(
151
- `CREATE OR REPLACE TRIGGER ${triggerFnName}\n` +
254
+ `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\n` +
152
255
  `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\n` +
153
- `FOR EACH ROW EXECUTE FUNCTION ${triggerFnName}();`,
256
+ `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,
154
257
  );
155
258
 
156
259
  statements.push(
157
- `CREATE OR REPLACE VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
260
+ `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\n${buildReadModelViewSql(
158
261
  entry,
159
262
  projection,
160
263
  columns.map((column) => column.name),
161
264
  )};`,
162
265
  );
266
+
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
+ })};`,
276
+ );
163
277
  }
164
278
 
165
279
  return `${statements.join("\n\n")}\n`;
@@ -205,6 +319,105 @@ function buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[]
205
319
  ].join(",\n ");
206
320
  }
207
321
 
322
+ /**
323
+ * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a
324
+ * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery
325
+ * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that
326
+ * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified
327
+ * when it declares a schema and bare otherwise (per the table object). Column types come from each
328
+ * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing
329
+ * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry
330
+ * none, but the path is shared with the local-store generator so it must stay honest.
331
+ *
332
+ * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,
333
+ * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table
334
+ * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.
335
+ */
336
+ export function renderCreateTableSql(table: AnyPgTable): string[] {
337
+ const config = getTableConfig(table);
338
+ const schemaName = config.schema ?? "public";
339
+ const qualifiedTableName = qualifyIdentifier(schemaName, config.name);
340
+ const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);
341
+ const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);
342
+
343
+ const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\n ${columnSql}\n);`];
344
+
345
+ for (const index of config.indexes) {
346
+ statements.push(renderCreateIndexSql(qualifiedTableName, index));
347
+ }
348
+
349
+ return statements;
350
+ }
351
+
352
+ /** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */
353
+ function collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {
354
+ const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);
355
+ const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));
356
+ return [...columnLevel, ...composite];
357
+ }
358
+
359
+ function renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>["indexes"][number]) {
360
+ const { name, unique, columns, where, method, with: withParams } = index.config;
361
+ if (!name) {
362
+ throw new Error("renderCreateIndexSql: anonymous indexes are not supported (declare a name)");
363
+ }
364
+ // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not
365
+ // render must fail loudly — silently dropping one would produce a local index that differs from the
366
+ // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).
367
+ if (where) {
368
+ throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);
369
+ }
370
+ if (method && method.toLowerCase() !== "btree") {
371
+ throw new Error(
372
+ `renderCreateIndexSql: non-btree index methods (.using "${method}") are not supported (index ${name})`,
373
+ );
374
+ }
375
+ if (withParams && Object.keys(withParams).length > 0) {
376
+ throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);
377
+ }
378
+ const columnExpressions = columns.map((column) => {
379
+ const columnName = (column as { name?: unknown }).name;
380
+ if (typeof columnName !== "string") {
381
+ throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);
382
+ }
383
+ const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;
384
+ if (indexConfig?.order === "desc") {
385
+ throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);
386
+ }
387
+ // Drizzle fills `nulls` with the ascending-btree default ("last") on every column; only an
388
+ // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).
389
+ if (indexConfig?.nulls === "first") {
390
+ throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);
391
+ }
392
+ if (indexConfig?.opClass) {
393
+ throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);
394
+ }
395
+ return maybeQuoteIdentifier(columnName);
396
+ });
397
+
398
+ return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });
399
+ }
400
+
401
+ /**
402
+ * The shared `CREATE INDEX` core: assemble one
403
+ * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an
404
+ * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the
405
+ * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in
406
+ * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in
407
+ * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via
408
+ * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —
409
+ * this core only fixes the surrounding statement text.
410
+ */
411
+ function renderCreateIndexStatement(
412
+ qualifiedTableName: string,
413
+ indexName: string,
414
+ columnExpressions: readonly string[],
415
+ options: { unique?: boolean } = {},
416
+ ): string {
417
+ const uniqueSql = options.unique ? "UNIQUE " : "";
418
+ return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(", ")});`;
419
+ }
420
+
208
421
  function buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {
209
422
  const typeSql = mapColumnType(column, localSchema);
210
423
  const notNullSql = column.notNull ? " NOT NULL" : "";
@@ -254,9 +467,20 @@ type EnumDefinition = {
254
467
  };
255
468
 
256
469
  function collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {
470
+ return collectEnumDefinitionsFromEntries(Object.values(registry), localSchema);
471
+ }
472
+
473
+ /**
474
+ * Collect the distinct enum types referenced by a GIVEN set of registry entries (deduped by name, values
475
+ * cross-checked for conflicts, sorted for stable output). Factored out of {@link collectEnumDefinitions} so
476
+ * the Data export (ADR-0035) can emit ONLY the enums its `-t` allowlist tables reference — the whole-registry
477
+ * caller passes every entry, the data export passes just its owning persistent entries — through one honest
478
+ * implementation, never a second enum-scanning path that could drift on the conflict/sort rules.
479
+ */
480
+ function collectEnumDefinitionsFromEntries(entries: SyncTableEntry[], localSchema: string) {
257
481
  const enumDefinitionsByName = new Map<string, EnumDefinition>();
258
482
 
259
- for (const entry of Object.values(registry)) {
483
+ for (const entry of entries) {
260
484
  const columns = getProjectedColumns(entry).map(({ column }) => column);
261
485
 
262
486
  for (const column of columns) {
@@ -284,6 +508,114 @@ function collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string
284
508
  return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));
285
509
  }
286
510
 
511
+ /**
512
+ * Does this entry OWN a physical, persistent synced table — i.e. is it a `-t` allowlist candidate for the
513
+ * Data export (ADR-0035 decision 1)? Two entries are excluded:
514
+ *
515
+ * - a **read PROJECTION** (`readProjection`) owns no table (its `table` is another entry's), so it must
516
+ * never be listed — it would double-target the owner's physical table;
517
+ * - an **ephemeral** entry's cluster is emitted as `pg_temp` TEMP objects (ADR-0021 §3), absent from the
518
+ * throwaway clone by construction — and a `pg_dump -t` pattern that matches NOTHING makes `pg_dump` fail,
519
+ * so an ephemeral table must not appear in the allowlist at all.
520
+ *
521
+ * Overlay/journal/meta tables, read-model/sync-state views, and reconcile functions are excluded by `-t`
522
+ * semantics automatically (they are neither the synced table nor matched by its name), so they need no
523
+ * filter here.
524
+ */
525
+ function ownsPersistentSyncedTable(entry: SyncTableEntry): boolean {
526
+ return !entry.readProjection && entry.retention !== "ephemeral";
527
+ }
528
+
529
+ /**
530
+ * The `-t` allowlist for a Data export (ADR-0035 decision 1): the schema-qualified PHYSICAL synced table
531
+ * name for every registry entry that owns one, resolved through the SAME `getClientProjection` the local
532
+ * DDL generator uses — NOT re-derived by string convention. This is deliberately the physical `syncedTable`,
533
+ * never the read-model view (whose name can carry the entry name while the table differs): `-t` must target
534
+ * the tables that hold the rows. Read-projection and ephemeral entries are excluded (see
535
+ * {@link ownsPersistentSyncedTable}).
536
+ */
537
+ export function collectDataExportSyncedTableNames<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {
538
+ const localSchema = getSyncRegistrySchema(registry);
539
+ const names: string[] = [];
540
+
541
+ for (const [tableKey, entry] of Object.entries(registry)) {
542
+ if (!ownsPersistentSyncedTable(entry)) {
543
+ continue;
544
+ }
545
+
546
+ names.push(getClientProjection(entry, tableKey, localSchema).syncedTable);
547
+ }
548
+
549
+ return names;
550
+ }
551
+
552
+ /**
553
+ * The clone-cleanup SQL a Data export runs on its THROWAWAY clone before `pg_dump -t` (ADR-0035). The
554
+ * reconcile trigger sits ON the synced table (`AFTER INSERT/UPDATE/DELETE ON <syncedTable>`), so
555
+ * `pg_dump -t <syncedTable>` pulls the trigger into the dump — but its function is pgxsinkit machinery the
556
+ * data export deliberately EXCLUDES, so the artefact would carry a trigger referencing a missing function
557
+ * and fail to load into a vanilla Postgres. Because the clone is a memory-backed throwaway we fully own, we
558
+ * drop each reconcile trigger (and its now-unreferenced function) on it first, so `-t` yields clean,
559
+ * portable tables. Overlay/journal/views/metadata are NOT captured by `-t <syncedTable>` at all (a probe
560
+ * confirmed only the table, its PK, its data, and this trigger appear), so nothing else needs dropping.
561
+ * Returns `""` when the registry declares no writable owning table.
562
+ */
563
+ export function buildDataExportCloneCleanupSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
564
+ const localSchema = getSyncRegistrySchema(registry);
565
+ const statements: string[] = [];
566
+
567
+ for (const [tableKey, entry] of Object.entries(registry)) {
568
+ if (!ownsPersistentSyncedTable(entry) || entry.mode === "readonly") {
569
+ continue;
570
+ }
571
+
572
+ const projection = getClientProjection(entry, tableKey, localSchema);
573
+ // Drop the trigger first, then its now-unreferenced function (drop order avoids a dependency error).
574
+ statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);
575
+ statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);
576
+ }
577
+
578
+ return statements.join("\n");
579
+ }
580
+
581
+ /**
582
+ * The enum DDL header for a Data export artefact (ADR-0035 decision 1). `pg_dump -t <table>` emits the
583
+ * tables but NOT the enum types their columns reference, so the portable artefact is this generated header
584
+ * concatenated ahead of the `pg_dump` output. It reuses the SAME `CREATE TYPE` generation the local-schema
585
+ * generator emits ({@link buildCreateEnumTypeSql}) — every enum wrapped in an idempotent `IF NOT EXISTS`
586
+ * guard — restricted to the enums actually referenced by the exported (owning, persistent) tables, so a
587
+ * dropped/ephemeral-only enum never bloats the artefact. When the registry uses a non-`public` schema, a
588
+ * `CREATE SCHEMA IF NOT EXISTS` precedes the types (they live in that schema, and the header runs before
589
+ * `pg_dump`'s own schema creation), so the header is self-contained against a bare Postgres. Returns `""`
590
+ * when no exported table references an enum.
591
+ */
592
+ export function buildDataExportEnumHeaderSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
593
+ const localSchema = getSyncRegistrySchema(registry);
594
+ const exportedEntries = Object.values(registry).filter(ownsPersistentSyncedTable);
595
+ const enumDefinitions = collectEnumDefinitionsFromEntries(exportedEntries, localSchema);
596
+
597
+ if (enumDefinitions.length === 0) {
598
+ return "";
599
+ }
600
+
601
+ const statements: string[] = [
602
+ "-- Enum types referenced by the exported tables. `pg_dump -t` does not emit the enum types",
603
+ "-- its tables depend on, so pgxsinkit generates them here from the sync registry (ADR-0035).",
604
+ ];
605
+
606
+ // A non-public schema must exist before its `CREATE TYPE` runs — this header precedes pg_dump's own
607
+ // schema creation, so create it ourselves (idempotent), mirroring `generateLocalSchemaSql`.
608
+ if (localSchema !== "public") {
609
+ statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);
610
+ }
611
+
612
+ for (const enumDefinition of enumDefinitions) {
613
+ statements.push(buildCreateEnumTypeSql(enumDefinition));
614
+ }
615
+
616
+ return `${statements.join("\n")}\n`;
617
+ }
618
+
287
619
  function buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {
288
620
  const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);
289
621
  const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(", ");
@@ -365,6 +697,9 @@ function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchem
365
697
  ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),
366
698
  ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),
367
699
  readModel: qualifyIdentifier(localSchema, readModelName),
700
+ syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),
701
+ reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),
702
+ reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),
368
703
  };
369
704
  }
370
705
 
@@ -378,20 +713,129 @@ function baseProjection(entry: SyncTableEntry, tableKey: string) {
378
713
 
379
714
  function qualifyIdentifier(schemaName: string, objectName: string) {
380
715
  if (schemaName === "public") {
381
- return objectName;
716
+ // Quote only when required so existing generated SQL stays stable, but a table/view named
717
+ // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or
718
+ // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.
719
+ return maybeQuoteIdentifier(objectName);
382
720
  }
383
721
 
384
722
  return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;
385
723
  }
386
724
 
387
- function quoteIdentifier(value: string) {
388
- return `"${value.replace(/"/g, '""')}"`;
725
+ function buildJournalSequenceName(journalTable: string) {
726
+ return `${journalTable}_mutation_seq`;
389
727
  }
390
728
 
391
- function quoteSqlStringLiteral(value: string) {
392
- return `'${value.replace(/'/g, "''")}'`;
729
+ /**
730
+ * Drop the reconstructible **read cache** — the synced tables and their read-model views
731
+ * and reconcile triggers/functions — while preserving the authority tables (overlay,
732
+ * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds
733
+ * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is
734
+ * the named drop primitive a returning-online upgrade uses after a clean drain.
735
+ */
736
+ export function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
737
+ const localSchema = getSyncRegistrySchema(registry);
738
+ const statements: string[] = [];
739
+
740
+ for (const [tableKey, entry] of Object.entries(registry)) {
741
+ const projection = getClientProjection(entry, tableKey, localSchema);
742
+
743
+ if (entry.mode !== "readonly") {
744
+ statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);
745
+ statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);
746
+ statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);
747
+ statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);
748
+ }
749
+
750
+ statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);
751
+ }
752
+
753
+ return `${statements.join("\n")}\n`;
393
754
  }
394
755
 
395
- function buildJournalSequenceName(journalTable: string) {
396
- return `${journalTable}_mutation_seq`;
756
+ /**
757
+ * Wipe the **entire** local store provisioned from the registry — the read cache plus the
758
+ * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.
759
+ * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the
760
+ * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).
761
+ */
762
+ export function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
763
+ const localSchema = getSyncRegistrySchema(registry);
764
+ const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];
765
+
766
+ for (const [tableKey, entry] of Object.entries(registry)) {
767
+ if (entry.mode === "readonly") {
768
+ continue;
769
+ }
770
+
771
+ const projection = getClientProjection(entry, tableKey, localSchema);
772
+
773
+ if (projection.overlayTable) {
774
+ statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);
775
+ }
776
+
777
+ if (projection.journalTable && entry.clientProjection?.journalTable) {
778
+ statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);
779
+ statements.push(
780
+ `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,
781
+ );
782
+ }
783
+ }
784
+
785
+ for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
786
+ statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);
787
+ }
788
+
789
+ statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);
790
+
791
+ return `${statements.join("\n")}\n`;
792
+ }
793
+
794
+ /**
795
+ * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns
796
+ * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and
797
+ * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),
798
+ * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`
799
+ * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring
800
+ * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing
801
+ * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops
802
+ * un-acked local intent).
803
+ */
804
+ export function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(
805
+ registry: TRegistry,
806
+ tableKey: string,
807
+ ): string {
808
+ const entry = registry[tableKey];
809
+
810
+ if (!entry) {
811
+ throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);
812
+ }
813
+
814
+ const localSchema = getSyncRegistrySchema(registry);
815
+ const ephemeral = entry.retention === "ephemeral";
816
+ const objectSchema = ephemeral ? "public" : localSchema;
817
+ const projection = getClientProjection(entry, tableKey, objectSchema);
818
+ const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];
819
+
820
+ if (entry.mode !== "readonly") {
821
+ if (projection.overlayTable) {
822
+ statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);
823
+ }
824
+
825
+ if (projection.journalTable && entry.clientProjection?.journalTable) {
826
+ statements.push(`TRUNCATE TABLE ${projection.journalTable};`);
827
+ statements.push(
828
+ `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,
829
+ );
830
+ }
831
+ }
832
+
833
+ // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next
834
+ // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows
835
+ // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):
836
+ // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.
837
+ const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;
838
+ statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));
839
+
840
+ return `${statements.join("\n")}\n`;
397
841
  }