@pgxsinkit/client 0.1.31 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/index.d.ts +421 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7214 -2234
- package/dist/index.js.map +74 -44
- package/dist/lazy-guard.d.ts +58 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +62 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +117 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +49 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +180 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +118 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/worker/attach-sync-client.d.ts +75 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +75 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +260 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +19 -7
- package/skills/core/SKILL.md +197 -0
- package/skills/operating/SKILL.md +243 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/index.ts +1104 -44
- package/src/lazy-guard.ts +121 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +90 -0
- package/src/mutation.ts +1868 -562
- package/src/schema.ts +352 -27
- package/src/shape-sync.ts +477 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1076 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +132 -0
- package/src/sync-auth.ts +117 -0
- package/src/worker/attach-sync-client.ts +558 -0
- package/src/worker/define-sync-worker.ts +596 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +325 -0
- 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
|
-
|
|
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(
|
|
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
|
-
|
|
165
|
+
renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [
|
|
166
|
+
"status",
|
|
167
|
+
"enqueued_at_us",
|
|
168
|
+
]),
|
|
107
169
|
);
|
|
108
170
|
statements.push(
|
|
109
|
-
|
|
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
|
-
|
|
178
|
+
renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [
|
|
179
|
+
...entry.primaryKey.columns,
|
|
180
|
+
"mutation_seq",
|
|
181
|
+
]),
|
|
113
182
|
);
|
|
114
183
|
statements.push(
|
|
115
|
-
|
|
184
|
+
renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [
|
|
185
|
+
"entity_key_json",
|
|
186
|
+
"mutation_seq",
|
|
187
|
+
]),
|
|
116
188
|
);
|
|
117
189
|
statements.push(
|
|
118
|
-
|
|
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 ${
|
|
221
|
+
`CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\n` +
|
|
136
222
|
`BEGIN\n` +
|
|
137
|
-
`
|
|
138
|
-
`
|
|
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 ${
|
|
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 ${
|
|
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" : "";
|
|
@@ -365,6 +578,9 @@ function getClientProjection(entry: SyncTableEntry, tableKey: string, localSchem
|
|
|
365
578
|
...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),
|
|
366
579
|
...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),
|
|
367
580
|
readModel: qualifyIdentifier(localSchema, readModelName),
|
|
581
|
+
syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),
|
|
582
|
+
reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),
|
|
583
|
+
reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),
|
|
368
584
|
};
|
|
369
585
|
}
|
|
370
586
|
|
|
@@ -378,20 +594,129 @@ function baseProjection(entry: SyncTableEntry, tableKey: string) {
|
|
|
378
594
|
|
|
379
595
|
function qualifyIdentifier(schemaName: string, objectName: string) {
|
|
380
596
|
if (schemaName === "public") {
|
|
381
|
-
|
|
597
|
+
// Quote only when required so existing generated SQL stays stable, but a table/view named
|
|
598
|
+
// after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or
|
|
599
|
+
// the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.
|
|
600
|
+
return maybeQuoteIdentifier(objectName);
|
|
382
601
|
}
|
|
383
602
|
|
|
384
603
|
return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;
|
|
385
604
|
}
|
|
386
605
|
|
|
387
|
-
function
|
|
388
|
-
return
|
|
606
|
+
function buildJournalSequenceName(journalTable: string) {
|
|
607
|
+
return `${journalTable}_mutation_seq`;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Drop the reconstructible **read cache** — the synced tables and their read-model views
|
|
612
|
+
* and reconcile triggers/functions — while preserving the authority tables (overlay,
|
|
613
|
+
* journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds
|
|
614
|
+
* the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is
|
|
615
|
+
* the named drop primitive a returning-online upgrade uses after a clean drain.
|
|
616
|
+
*/
|
|
617
|
+
export function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
|
|
618
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
619
|
+
const statements: string[] = [];
|
|
620
|
+
|
|
621
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
622
|
+
const projection = getClientProjection(entry, tableKey, localSchema);
|
|
623
|
+
|
|
624
|
+
if (entry.mode !== "readonly") {
|
|
625
|
+
statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);
|
|
626
|
+
statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);
|
|
627
|
+
statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);
|
|
628
|
+
statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
return `${statements.join("\n")}\n`;
|
|
389
635
|
}
|
|
390
636
|
|
|
391
|
-
|
|
392
|
-
|
|
637
|
+
/**
|
|
638
|
+
* Wipe the **entire** local store provisioned from the registry — the read cache plus the
|
|
639
|
+
* authority tables (overlay, journal, sequences), the enum types, and the local-meta row.
|
|
640
|
+
* This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the
|
|
641
|
+
* drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).
|
|
642
|
+
*/
|
|
643
|
+
export function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {
|
|
644
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
645
|
+
const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];
|
|
646
|
+
|
|
647
|
+
for (const [tableKey, entry] of Object.entries(registry)) {
|
|
648
|
+
if (entry.mode === "readonly") {
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
const projection = getClientProjection(entry, tableKey, localSchema);
|
|
653
|
+
|
|
654
|
+
if (projection.overlayTable) {
|
|
655
|
+
statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (projection.journalTable && entry.clientProjection?.journalTable) {
|
|
659
|
+
statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);
|
|
660
|
+
statements.push(
|
|
661
|
+
`DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,
|
|
662
|
+
);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {
|
|
667
|
+
statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);
|
|
671
|
+
|
|
672
|
+
return `${statements.join("\n")}\n`;
|
|
393
673
|
}
|
|
394
674
|
|
|
395
|
-
|
|
396
|
-
|
|
675
|
+
/**
|
|
676
|
+
* Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns
|
|
677
|
+
* to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and
|
|
678
|
+
* the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),
|
|
679
|
+
* so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`
|
|
680
|
+
* names for an ephemeral cluster, schema-qualified for a persistent one — mirroring
|
|
681
|
+
* {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing
|
|
682
|
+
* re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops
|
|
683
|
+
* un-acked local intent).
|
|
684
|
+
*/
|
|
685
|
+
export function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(
|
|
686
|
+
registry: TRegistry,
|
|
687
|
+
tableKey: string,
|
|
688
|
+
): string {
|
|
689
|
+
const entry = registry[tableKey];
|
|
690
|
+
|
|
691
|
+
if (!entry) {
|
|
692
|
+
throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const localSchema = getSyncRegistrySchema(registry);
|
|
696
|
+
const ephemeral = entry.retention === "ephemeral";
|
|
697
|
+
const objectSchema = ephemeral ? "public" : localSchema;
|
|
698
|
+
const projection = getClientProjection(entry, tableKey, objectSchema);
|
|
699
|
+
const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];
|
|
700
|
+
|
|
701
|
+
if (entry.mode !== "readonly") {
|
|
702
|
+
if (projection.overlayTable) {
|
|
703
|
+
statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
if (projection.journalTable && entry.clientProjection?.journalTable) {
|
|
707
|
+
statements.push(`TRUNCATE TABLE ${projection.journalTable};`);
|
|
708
|
+
statements.push(
|
|
709
|
+
`ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next
|
|
715
|
+
// activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows
|
|
716
|
+
// that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):
|
|
717
|
+
// for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.
|
|
718
|
+
const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;
|
|
719
|
+
statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));
|
|
720
|
+
|
|
721
|
+
return `${statements.join("\n")}\n`;
|
|
397
722
|
}
|