@jini-ai/db 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE.pglite-socket +176 -0
  3. package/NOTICE.md +27 -0
  4. package/README.md +210 -0
  5. package/dist/core/artifact-naming.d.ts +34 -0
  6. package/dist/core/artifact-naming.js +34 -0
  7. package/dist/core/index.d.ts +8 -0
  8. package/dist/core/index.js +10 -0
  9. package/dist/core/messages.d.ts +43 -0
  10. package/dist/core/messages.js +26 -0
  11. package/dist/core/pg-types.d.ts +22 -0
  12. package/dist/core/pg-types.js +26 -0
  13. package/dist/core/ports.d.ts +70 -0
  14. package/dist/core/ports.js +22 -0
  15. package/dist/core/row-values.d.ts +32 -0
  16. package/dist/core/row-values.js +42 -0
  17. package/dist/core/socket.d.ts +8 -0
  18. package/dist/core/socket.js +8 -0
  19. package/dist/kernel/dialect.d.ts +83 -0
  20. package/dist/kernel/dialect.js +191 -0
  21. package/dist/kernel/index.d.ts +15 -0
  22. package/dist/kernel/index.js +15 -0
  23. package/dist/kernel/kernel-core.d.ts +43 -0
  24. package/dist/kernel/kernel-core.js +98 -0
  25. package/dist/kernel/ops.d.ts +48 -0
  26. package/dist/kernel/ops.js +49 -0
  27. package/dist/kernel/pg-types.d.ts +22 -0
  28. package/dist/kernel/pg-types.js +26 -0
  29. package/dist/kernel/pglite/dialect.d.ts +11 -0
  30. package/dist/kernel/pglite/dialect.js +88 -0
  31. package/dist/kernel/pglite/driver.d.ts +30 -0
  32. package/dist/kernel/pglite/driver.js +47 -0
  33. package/dist/kernel/pglite/index.d.ts +5 -0
  34. package/dist/kernel/pglite/index.js +5 -0
  35. package/dist/kernel/pglite/ops.d.ts +39 -0
  36. package/dist/kernel/pglite/ops.js +78 -0
  37. package/dist/kernel/port.d.ts +82 -0
  38. package/dist/kernel/port.js +11 -0
  39. package/dist/kernel/postgres/driver.d.ts +23 -0
  40. package/dist/kernel/postgres/driver.js +42 -0
  41. package/dist/kernel/postgres/index.d.ts +5 -0
  42. package/dist/kernel/postgres/index.js +5 -0
  43. package/dist/kernel/postgres/ops.d.ts +12 -0
  44. package/dist/kernel/postgres/ops.js +46 -0
  45. package/dist/kernel/postgres/pglite-socket.d.ts +23 -0
  46. package/dist/kernel/postgres/pglite-socket.js +52 -0
  47. package/dist/kernel/postgres-lock.d.ts +8 -0
  48. package/dist/kernel/postgres-lock.js +10 -0
  49. package/dist/kernel/schema-scope.d.ts +14 -0
  50. package/dist/kernel/schema-scope.js +20 -0
  51. package/dist/kernel/schema-shape.d.ts +26 -0
  52. package/dist/kernel/schema-shape.js +83 -0
  53. package/dist/kernel/socket.d.ts +8 -0
  54. package/dist/kernel/socket.js +8 -0
  55. package/dist/kernel/sqlite/driver.d.ts +71 -0
  56. package/dist/kernel/sqlite/driver.js +132 -0
  57. package/dist/kernel/sqlite/index.d.ts +4 -0
  58. package/dist/kernel/sqlite/index.js +4 -0
  59. package/dist/kernel/sqlite/ops.d.ts +12 -0
  60. package/dist/kernel/sqlite/ops.js +40 -0
  61. package/dist/kernel/store-copy.d.ts +82 -0
  62. package/dist/kernel/store-copy.js +240 -0
  63. package/dist/kernel/turn-lock.d.ts +21 -0
  64. package/dist/kernel/turn-lock.js +42 -0
  65. package/dist/kernel/typegen.d.ts +13 -0
  66. package/dist/kernel/typegen.js +76 -0
  67. package/dist/migrate/checksum.d.ts +11 -0
  68. package/dist/migrate/checksum.js +14 -0
  69. package/dist/migrate/index.d.ts +8 -0
  70. package/dist/migrate/index.js +8 -0
  71. package/dist/migrate/runner.d.ts +33 -0
  72. package/dist/migrate/runner.js +126 -0
  73. package/dist/migrate/step.d.ts +37 -0
  74. package/dist/migrate/step.js +31 -0
  75. package/dist/pglite/dialect.d.ts +11 -0
  76. package/dist/pglite/dialect.js +88 -0
  77. package/dist/pglite/driver.d.ts +30 -0
  78. package/dist/pglite/driver.js +46 -0
  79. package/dist/pglite/index.d.ts +5 -0
  80. package/dist/pglite/index.js +4 -0
  81. package/dist/pglite/ops.d.ts +39 -0
  82. package/dist/pglite/ops.js +78 -0
  83. package/dist/pglite/owner.d.ts +107 -0
  84. package/dist/pglite/owner.js +359 -0
  85. package/dist/pglite/socket-server.d.ts +38 -0
  86. package/dist/pglite/socket-server.js +375 -0
  87. package/dist/pglite/types.d.ts +9 -0
  88. package/dist/pglite/types.js +2 -0
  89. package/dist/postgres/driver.d.ts +23 -0
  90. package/dist/postgres/driver.js +41 -0
  91. package/dist/postgres/index.d.ts +3 -0
  92. package/dist/postgres/index.js +3 -0
  93. package/dist/postgres/ops.d.ts +12 -0
  94. package/dist/postgres/ops.js +46 -0
  95. package/dist/postgres/pglite-socket.d.ts +23 -0
  96. package/dist/postgres/pglite-socket.js +51 -0
  97. package/dist/postgres/types.d.ts +53 -0
  98. package/dist/postgres/types.js +14 -0
  99. package/dist/sqlite/db-ops.d.ts +59 -0
  100. package/dist/sqlite/db-ops.js +82 -0
  101. package/dist/sqlite/driver.d.ts +71 -0
  102. package/dist/sqlite/driver.js +132 -0
  103. package/dist/sqlite/index.d.ts +9 -0
  104. package/dist/sqlite/index.js +4 -0
  105. package/dist/sqlite/inspect.d.ts +60 -0
  106. package/dist/sqlite/inspect.js +153 -0
  107. package/dist/sqlite/open.d.ts +58 -0
  108. package/dist/sqlite/open.js +43 -0
  109. package/dist/sqlite/ops.d.ts +12 -0
  110. package/dist/sqlite/ops.js +40 -0
  111. package/dist/sqlite/restore-types.d.ts +42 -0
  112. package/dist/sqlite/restore-types.js +2 -0
  113. package/dist/sqlite/sync-types.d.ts +34 -0
  114. package/dist/sqlite/sync-types.js +2 -0
  115. package/dist/sqlite/types.d.ts +37 -0
  116. package/dist/sqlite/types.js +8 -0
  117. package/dist/tools/database-catalog.d.ts +61 -0
  118. package/dist/tools/database-catalog.js +201 -0
  119. package/dist/tools/destination-port.d.ts +27 -0
  120. package/dist/tools/destination-port.js +2 -0
  121. package/dist/tools/index.d.ts +13 -0
  122. package/dist/tools/index.js +11 -0
  123. package/dist/tools/plan-store.d.ts +61 -0
  124. package/dist/tools/plan-store.js +39 -0
  125. package/dist/tools/read-tools.d.ts +53 -0
  126. package/dist/tools/read-tools.js +97 -0
  127. package/dist/tools/registration.d.ts +18 -0
  128. package/dist/tools/registration.js +10 -0
  129. package/dist/tools/restore-points.d.ts +125 -0
  130. package/dist/tools/restore-points.js +54 -0
  131. package/dist/tools/surface-port.d.ts +43 -0
  132. package/dist/tools/surface-port.js +2 -0
  133. package/dist/tools/timeline.d.ts +63 -0
  134. package/dist/tools/timeline.js +46 -0
  135. package/dist/tools/transfer-catalog.d.ts +25 -0
  136. package/dist/tools/transfer-catalog.js +59 -0
  137. package/dist/tools/transfer-tools.d.ts +82 -0
  138. package/dist/tools/transfer-tools.js +346 -0
  139. package/dist/transfer/copy-engine.d.ts +129 -0
  140. package/dist/transfer/copy-engine.js +233 -0
  141. package/dist/transfer/index.d.ts +9 -0
  142. package/dist/transfer/index.js +9 -0
  143. package/dist/transfer/internal-ddl.d.ts +23 -0
  144. package/dist/transfer/internal-ddl.js +119 -0
  145. package/dist/transfer/plan.d.ts +28 -0
  146. package/dist/transfer/plan.js +19 -0
  147. package/dist/transfer/postgres-ddl.d.ts +36 -0
  148. package/dist/transfer/postgres-ddl.js +16 -0
  149. package/dist/transfer/postgres-target.d.ts +65 -0
  150. package/dist/transfer/postgres-target.js +95 -0
  151. package/dist/transfer/sqlite-source.d.ts +78 -0
  152. package/dist/transfer/sqlite-source.js +79 -0
  153. package/dist/transfer/table-catalog.d.ts +44 -0
  154. package/dist/transfer/table-catalog.js +109 -0
  155. package/dist/transfer/types.d.ts +47 -0
  156. package/dist/transfer/types.js +2 -0
  157. package/package.json +184 -0
@@ -0,0 +1,233 @@
1
+ import { createHash } from "node:crypto";
2
+ import { defaultDbMessages } from "../core/messages.js";
3
+ import { constraintSql, createTableSql, indexSql, qualified, quoteIdent, quoteLiteral, reseedIdentitySql } from "./internal-ddl.js";
4
+ import { planTransfer } from "./plan.js";
5
+ /** Postgres truncates identifiers past 63 bytes (NAMEDATALEN - 1). */
6
+ const MAX_IDENTIFIER_BYTES = 63;
7
+ function shortHash(text) {
8
+ return createHash("sha256").update(text).digest("hex").slice(0, 8);
9
+ }
10
+ /**
11
+ * The readable schema a site gets when the host default is taken: its prefix plus the site name lowercased, with
12
+ * every run of other characters turned into one `_`. When that loses information (a character other
13
+ * than a letter, digit, space, `-`, `_` or `.`), is empty, or must be cut to fit 63 bytes, 8 hex
14
+ * characters of the whole name's SHA-256 are appended, so distinct names stay distinct.
15
+ *
16
+ * @complexity O(name length).
17
+ */
18
+ function siteSchemaNameInternal(site, naming) {
19
+ const SCHEMA_PREFIX = naming.schemaPrefix;
20
+ const slug = site.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
21
+ const lossless = /^[A-Za-z0-9 ._-]*$/.test(site);
22
+ if (lossless && slug !== "" && SCHEMA_PREFIX.length + slug.length <= MAX_IDENTIFIER_BYTES)
23
+ return `${SCHEMA_PREFIX}${slug}`;
24
+ return withHash(site, slug, naming);
25
+ }
26
+ function withHash(site, slug, naming) {
27
+ const SCHEMA_PREFIX = naming.schemaPrefix;
28
+ const room = MAX_IDENTIFIER_BYTES - SCHEMA_PREFIX.length - 9;
29
+ const kept = slug.slice(0, room).replace(/_+$/, "");
30
+ return `${SCHEMA_PREFIX}${kept === "" ? "" : `${kept}_`}${shortHash(site)}`;
31
+ }
32
+ /** The schemas a site without a copy may take, in order. */
33
+ function schemaCandidates(site, naming) {
34
+ const slug = site.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
35
+ return [...new Set([naming.defaultSchema, siteSchemaNameInternal(site, naming), withHash(site, slug, naming)])];
36
+ }
37
+ export class SourceSchemaMismatchError extends Error {
38
+ }
39
+ /**
40
+ * Row counts for every table, after checking the source has each table and column the target will
41
+ * get (a site database is migrated at boot, so a gap means the Postgres schema is out of date).
42
+ *
43
+ * @throws {SourceSchemaMismatchError} Naming the first missing table or column.
44
+ * @param _optional.messages Host schema-error formatters; never used in SQL or persisted naming.
45
+ * @complexity O(tables) queries.
46
+ */
47
+ export function countSourceRows({ source, tables }, _optional = {}) {
48
+ const messages = _optional.messages ?? defaultDbMessages;
49
+ return tables.map((table) => {
50
+ const present = source.columns(table.name);
51
+ if (present === null)
52
+ throw new SourceSchemaMismatchError(messages.missingSourceTable({ table: table.name }));
53
+ const missing = table.columns.find((column) => !present.includes(column.name));
54
+ if (missing)
55
+ throw new SourceSchemaMismatchError(messages.missingSourceColumn({ table: table.name, column: missing.name }));
56
+ return { table, rows: source.countRows(table.name, table.keep) };
57
+ });
58
+ }
59
+ /** Every marker on the server: schema, the site of its newest row, and whether any row names a different site. */
60
+ async function readMarkers(target, TRANSFER_MARKER_TABLE) {
61
+ const listed = await target.query(`SELECT n.nspname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = ${quoteLiteral(TRANSFER_MARKER_TABLE)} AND c.relkind = 'r' ORDER BY 1`);
62
+ if (!listed.ok)
63
+ return listed;
64
+ const markers = [];
65
+ for (const [schema] of listed.value) {
66
+ if (schema === undefined)
67
+ continue;
68
+ const rows = await target.query(`SELECT site, snapshot_at, (SELECT count(DISTINCT site) FROM ${qualified(schema, TRANSFER_MARKER_TABLE)}) > 1 FROM ${qualified(schema, TRANSFER_MARKER_TABLE)} ORDER BY copied_at DESC LIMIT 1`);
69
+ // A table merely NAMED like the marker (wrong columns) is someone else's; it never claims a site.
70
+ const [site, snapshotAt, mixed] = rows.ok ? (rows.value[0] ?? []) : [];
71
+ markers.push({ schema, copy: site !== undefined && snapshotAt !== undefined ? { site, snapshotAt } : null, mixed: mixed === "t" });
72
+ }
73
+ return { ok: true, value: markers };
74
+ }
75
+ /**
76
+ * Connects and reads what a plan needs: the server version, whether this user may create a schema,
77
+ * and where this site's copy goes (see this file's header).
78
+ *
79
+ * @complexity Two queries plus one per schema holding a marker.
80
+ */
81
+ export async function inspectTarget({ target, site, naming }, _optional = {}) {
82
+ const state = await target.query(`SELECT current_setting('server_version_num'), has_database_privilege(current_database(), 'CREATE')`);
83
+ if (!state.ok)
84
+ return { ok: false, error: state.error };
85
+ const [version, canCreate] = state.value[0] ?? [];
86
+ const markers = await readMarkers(target, naming.markerTable);
87
+ if (!markers.ok)
88
+ return { ok: false, error: markers.error };
89
+ const base = { ok: true, serverVersionNum: Number(version), canCreateSchema: canCreate === "t" };
90
+ const own = markers.value.find((marker) => marker.copy?.site === site && !marker.mixed);
91
+ if (own !== undefined)
92
+ return { ...base, schemaState: "ours", schema: own.schema, lastCopy: own.copy };
93
+ const candidates = schemaCandidates(site, naming);
94
+ const existing = await target.query(`SELECT nspname FROM pg_namespace WHERE nspname IN (${candidates.map(quoteLiteral).join(", ")})`);
95
+ if (!existing.ok)
96
+ return { ok: false, error: existing.error };
97
+ const taken = new Set(existing.value.map(([name]) => name));
98
+ const free = candidates.find((candidate) => !taken.has(candidate)) ?? null;
99
+ return { ...base, schemaState: free === null ? "foreign" : "absent", schema: free, lastCopy: null };
100
+ }
101
+ /** One value in COPY text format: `\N` for NULL, backslash escapes for the four specials, `\\x<hex>` for bytes. */
102
+ function copyField(value, table, column) {
103
+ if (value === null || value === undefined)
104
+ return "\\N";
105
+ if (typeof value === "number" || typeof value === "bigint")
106
+ return String(value);
107
+ if (typeof value === "string")
108
+ return value.replace(/[\\\n\r\t]/g, (ch) => (ch === "\\" ? "\\\\" : ch === "\n" ? "\\n" : ch === "\r" ? "\\r" : "\\t"));
109
+ if (Buffer.isBuffer(value) && column.sqlType === "bytea")
110
+ return `\\\\x${value.toString("hex")}`;
111
+ throw new SourceSchemaMismatchError(`'${table}.${column.name}' holds binary data, which its Postgres column does not accept`);
112
+ }
113
+ function* copyTableData(source, schema, table) {
114
+ const names = table.columns.map((column) => column.name);
115
+ const columns = table.columns;
116
+ yield `COPY ${qualified(schema, table.name)} (${names.map(quoteIdent).join(", ")}) FROM STDIN;\n`;
117
+ let batch = "";
118
+ for (const row of source.rows(table.name, names, table.keep)) {
119
+ batch += row.map((value, i) => copyField(value, table.name, columns[i])).join("\t") + "\n";
120
+ if (batch.length > 256 * 1024) {
121
+ yield batch;
122
+ batch = "";
123
+ }
124
+ }
125
+ yield `${batch}\\.\n`;
126
+ }
127
+ const FOREIGN_SCHEMA_SIGNAL = "TRANSFER_TARGET_NOT_OURS";
128
+ const COUNT_MISMATCH_SIGNAL = "TRANSFER_COUNT_MISMATCH";
129
+ /**
130
+ * Aborts the transaction unless `schema` is absent or holds only this site's copy. The marker is read
131
+ * with dynamic SQL so a table merely named like it (other columns) also counts as someone else's.
132
+ */
133
+ function guardSql(schema, site, TRANSFER_MARKER_TABLE, sqlTag) {
134
+ const marker = quoteLiteral(`${quoteIdent(schema)}.${quoteIdent(TRANSFER_MARKER_TABLE)}`);
135
+ return (`DO $${sqlTag}$ DECLARE mine bigint; total bigint; BEGIN\n` +
136
+ ` IF to_regnamespace(${quoteLiteral(quoteIdent(schema))}) IS NULL THEN RETURN; END IF;\n` +
137
+ ` IF to_regclass(${marker}) IS NULL THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}'; END IF;\n` +
138
+ ` BEGIN\n` +
139
+ ` EXECUTE format('SELECT count(*) FILTER (WHERE site = %L), count(*) FROM %s', ${quoteLiteral(site)}, ${marker}) INTO mine, total;\n` +
140
+ ` EXCEPTION WHEN undefined_column THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}';\n` +
141
+ ` END;\n` +
142
+ ` IF mine = 0 OR mine <> total THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}'; END IF;\n` +
143
+ `END $${sqlTag}$;\n`);
144
+ }
145
+ function countCheckSql(schema, counts, sqlTag) {
146
+ const checks = counts.map(({ table, rows }) => `SELECT count(*) INTO n FROM ${qualified(schema, table.name)}; IF n <> ${rows} THEN RAISE EXCEPTION ${quoteLiteral(`${COUNT_MISMATCH_SIGNAL} ${table.name}`)}; END IF;`);
147
+ return `DO $${sqlTag}$ DECLARE n bigint; BEGIN ${checks.join(" ")} END $${sqlTag}$;\n`;
148
+ }
149
+ function markerSql(schema, marker, counts, naming) {
150
+ const TRANSFER_MARKER_TABLE = naming.markerTable;
151
+ const UNVALIDATED_TABLE = naming.unvalidatedTable.split(".").map(quoteIdent).join(".");
152
+ const tableCounts = JSON.stringify(Object.fromEntries(counts.map(({ table, rows }) => [table.name, rows])));
153
+ return (`CREATE TABLE ${qualified(schema, TRANSFER_MARKER_TABLE)} (site text NOT NULL, snapshot_at text NOT NULL, copied_at timestamptz NOT NULL DEFAULT now(), table_counts jsonb NOT NULL, unvalidated jsonb NOT NULL);\n` +
154
+ `INSERT INTO ${qualified(schema, TRANSFER_MARKER_TABLE)} (site, snapshot_at, table_counts, unvalidated) VALUES (${quoteLiteral(marker.site)}, ${quoteLiteral(marker.snapshotAt)}, ${quoteLiteral(tableCounts)}::jsonb, ` +
155
+ `(SELECT coalesce(jsonb_agg(name ORDER BY name), '[]'::jsonb) FROM ${UNVALIDATED_TABLE}));\n`);
156
+ }
157
+ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
158
+ const sqlTag = naming.sqlTag ?? "transfer";
159
+ yield "BEGIN;\n";
160
+ yield guardSql(schema, marker.site, naming.markerTable, sqlTag);
161
+ // A first copy must fail if the schema appeared since planning, never delete it.
162
+ if (replaceExisting)
163
+ yield `DROP SCHEMA IF EXISTS ${quoteIdent(schema)} CASCADE;\n`;
164
+ yield `CREATE SCHEMA ${quoteIdent(schema)};\n`;
165
+ for (const { table } of counts)
166
+ yield createTableSql(schema, table);
167
+ for (const { source, counts: sourceCounts } of sources) {
168
+ for (const { table } of sourceCounts)
169
+ yield* copyTableData(source, schema, table);
170
+ }
171
+ yield countCheckSql(schema, counts, sqlTag);
172
+ for (const { table } of counts)
173
+ yield reseedIdentitySql(schema, table, sqlTag);
174
+ for (const { table } of counts)
175
+ yield indexSql(schema, table);
176
+ yield constraintSql(schema, counts.map(({ table }) => table), naming.unvalidatedTable, sqlTag);
177
+ yield markerSql(schema, marker, counts, naming);
178
+ yield "COMMIT;\n";
179
+ }
180
+ /** The constraints the committed copy left NOT VALID, from its marker. */
181
+ async function readUnvalidated(target, schema, TRANSFER_MARKER_TABLE) {
182
+ const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, TRANSFER_MARKER_TABLE)} LIMIT 1`);
183
+ const cell = read.ok ? read.value[0]?.[0] : undefined;
184
+ if (cell === undefined)
185
+ return { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
186
+ return { unvalidatedConstraints: JSON.parse(cell) };
187
+ }
188
+ export async function runCopy(input, _optional = {}) {
189
+ if (!/^[a-z_][a-z0-9_]*$/.test(input.naming.sqlTag ?? "transfer"))
190
+ throw new Error("invalid SQL dollar-quote tag");
191
+ const { sources } = planTransfer({ sources: input.sources });
192
+ const counted = sources.map(entry => {
193
+ const counts = entry.counts ?? countSourceRows({ source: entry.source, tables: entry.tables }, _optional);
194
+ if (counts.length !== entry.tables.length || counts.some((count, index) => count.table.name !== entry.tables[index]?.name || !Number.isSafeInteger(count.rows) || count.rows < 0)) {
195
+ throw new Error(`transfer counts do not cover the planned tables: ${entry.name}`);
196
+ }
197
+ return { source: entry.source, counts: counts.map((count, index) => ({ table: entry.tables[index], rows: count.rows })) };
198
+ });
199
+ const counts = counted.flatMap(entry => entry.counts);
200
+ const names = counts.map(entry => entry.table.name);
201
+ if (new Set(names).size !== names.length)
202
+ throw new Error("multiple transfer sources declare the same target table");
203
+ if (names.includes(input.naming.markerTable))
204
+ throw new Error("transfer table conflicts with its copy marker");
205
+ const { schema } = input;
206
+ if (schema === "public" || !/^[a-z_][a-z0-9_]*$/.test(schema) || Buffer.byteLength(schema) > MAX_IDENTIFIER_BYTES) {
207
+ throw new Error(`runCopy: '${schema}' is not a schema this copier may write`);
208
+ }
209
+ let result;
210
+ try {
211
+ result = await input.target.runScript(copyScript(counted, input.naming, schema, counts, input.marker, input.replaceExisting));
212
+ }
213
+ catch (err) {
214
+ if (err instanceof SourceSchemaMismatchError)
215
+ return { ok: false, code: "COPY_FAILED", message: `${err.message}. Nothing was changed.` };
216
+ throw err;
217
+ }
218
+ if (result.ok)
219
+ return { ok: true, tables: counts.map(({ table, rows }) => ({ name: table.name, rows })), ...(await readUnvalidated(input.target, schema, input.naming.markerTable)) };
220
+ if (result.error.includes(FOREIGN_SCHEMA_SIGNAL)) {
221
+ return { ok: false, code: "TARGET_NOT_OURS", message: `the destination already has a '${schema}' area that holds other data. Nothing was written, and it was left untouched.` };
222
+ }
223
+ const mismatch = new RegExp(`${COUNT_MISMATCH_SIGNAL} (\\S+)`).exec(result.error);
224
+ if (mismatch)
225
+ return { ok: false, code: "COUNT_MISMATCH", message: `the copy of '${mismatch[1]}' did not match, so the whole copy was thrown away. Any earlier copy is untouched.`, logDetail: result.error };
226
+ const where = result.copyTable ? ` while copying '${result.copyTable.replace(`${schema}.`, "")}'` : "";
227
+ return { ok: false, code: "COPY_FAILED", message: `the destination refused the copy${where}, so the whole copy was thrown away. Any earlier copy is untouched.`, logDetail: result.error };
228
+ }
229
+ /** Human-readable schema naming preserves the original hash/63-byte collision rationale above. */
230
+ export function siteSchemaName({ site, naming }, _optional = {}) {
231
+ return siteSchemaNameInternal(site, naming);
232
+ }
233
+ //# sourceMappingURL=copy-engine.js.map
@@ -0,0 +1,9 @@
1
+ /** Driver-free, Kysely-free transfer entry; host schema, order and exclusion policy are injected. */
2
+ export * from "./types.js";
3
+ export * from "./sqlite-source.js";
4
+ export * from "./postgres-target.js";
5
+ export * from "./postgres-ddl.js";
6
+ export * from "./table-catalog.js";
7
+ export * from "./plan.js";
8
+ export * from "./copy-engine.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,9 @@
1
+ /** Driver-free, Kysely-free transfer entry; host schema, order and exclusion policy are injected. */
2
+ export * from "./types.js";
3
+ export * from "./sqlite-source.js";
4
+ export * from "./postgres-target.js";
5
+ export * from "./postgres-ddl.js";
6
+ export * from "./table-catalog.js";
7
+ export * from "./plan.js";
8
+ export * from "./copy-engine.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
1
+ import type { TransferTable } from "./types.js";
2
+ /** A session-local table listing constraints left unvalidated; dropped at commit. */
3
+ export declare function quoteIdent(name: string): string;
4
+ export declare function quoteLiteral(value: string): string;
5
+ export declare function qualified(schema: string, table: string): string;
6
+ /**
7
+ * The name itself when it fits in 63 bytes; otherwise its first bytes plus 8 hex characters of its
8
+ * SHA-256, so two long names never collapse into one (Postgres would silently cut both to the same
9
+ * prefix).
10
+ */
11
+ export declare function fitIdentifier(name: string): string;
12
+ export declare function createTableSql(schema: string, table: TransferTable): string;
13
+ /** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
14
+ export declare function reseedIdentitySql(schema: string, table: TransferTable, sqlTag?: string): string;
15
+ export declare function indexSql(schema: string, table: TransferTable): string;
16
+ /**
17
+ * Every CHECK and foreign key, added NOT VALID and then validated; a failed validation is recorded
18
+ * in {@link UNVALIDATED_TABLE} as `table.constraint` and the constraint stays in place, unvalidated.
19
+ *
20
+ * @complexity O(constraints) statements.
21
+ */
22
+ export declare function constraintSql(schema: string, tables: readonly TransferTable[], unvalidatedTable: string, sqlTag?: string): string;
23
+ //# sourceMappingURL=internal-ddl.d.ts.map
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * @file The Postgres DDL a copy writes around the rows, in the order that keeps a bulk load fast and
4
+ * never lets one bad source row sink the copy:
5
+ * 1. {@link createTableSql} — columns, NOT NULL, defaults, identity, primary key (before the rows);
6
+ * 2. {@link reseedIdentitySql} — after the rows, each identity counter moves past the copied numbers,
7
+ * so the next new row gets max + 1 (a table with none starts at 1);
8
+ * 3. {@link indexSql} — every index and unique constraint;
9
+ * 4. {@link constraintSql} — CHECKs and foreign keys added NOT VALID (still enforced for every new
10
+ * row), then validated one by one; one whose existing rows break it (a row whose parent is gone,
11
+ * which SQLite allows with foreign keys off) stays NOT VALID and is recorded in
12
+ * {@link UNVALIDATED_TABLE}, instead of aborting the copy.
13
+ *
14
+ * A foreign key is left out when its parent table is not copied (logins, saved keys) or its parent
15
+ * columns are neither that table's primary key nor a unique index (Postgres requires one; SQLite does
16
+ * not).
17
+ */
18
+ /** Postgres truncates identifiers past 63 bytes (NAMEDATALEN - 1). */
19
+ const MAX_IDENTIFIER_BYTES = 63;
20
+ /** A session-local table listing constraints left unvalidated; dropped at commit. */
21
+ // The host supplies the session-local table name; never rename an existing copy marker.
22
+ export function quoteIdent(name) {
23
+ return `"${name.replace(/"/g, '""')}"`;
24
+ }
25
+ export function quoteLiteral(value) {
26
+ return `'${value.replace(/'/g, "''")}'`;
27
+ }
28
+ export function qualified(schema, table) {
29
+ return `${quoteIdent(schema)}.${quoteIdent(table)}`;
30
+ }
31
+ /**
32
+ * The name itself when it fits in 63 bytes; otherwise its first bytes plus 8 hex characters of its
33
+ * SHA-256, so two long names never collapse into one (Postgres would silently cut both to the same
34
+ * prefix).
35
+ */
36
+ export function fitIdentifier(name) {
37
+ if (Buffer.byteLength(name) <= MAX_IDENTIFIER_BYTES)
38
+ return name;
39
+ const hash = createHash("sha256").update(name).digest("hex").slice(0, 8);
40
+ let kept = name.slice(0, MAX_IDENTIFIER_BYTES - 9);
41
+ while (Buffer.byteLength(kept) > MAX_IDENTIFIER_BYTES - 9)
42
+ kept = kept.slice(0, -1);
43
+ return `${kept}_${hash}`;
44
+ }
45
+ function columnSql(column) {
46
+ const identity = column.identity === undefined ? "" : ` GENERATED ${column.identity} AS IDENTITY`;
47
+ const fallback = column.default === undefined ? "" : ` DEFAULT ${column.default}`;
48
+ return `${quoteIdent(column.name)} ${column.sqlType}${identity}${fallback}${column.notNull ? " NOT NULL" : ""}`;
49
+ }
50
+ export function createTableSql(schema, table) {
51
+ const columns = table.columns.map(columnSql);
52
+ if (table.primaryKey.length > 0)
53
+ columns.push(`PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(", ")})`);
54
+ return `CREATE TABLE ${qualified(schema, table.name)} (${columns.join(", ")});\n`;
55
+ }
56
+ /** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
57
+ export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
58
+ return table.columns
59
+ .filter((column) => column.identity !== undefined)
60
+ .map((column) => {
61
+ const top = `COALESCE((SELECT max(${quoteIdent(column.name)}) FROM ${qualified(schema, table.name)}), 0)`;
62
+ return `DO $${sqlTag}$ BEGIN PERFORM setval(pg_get_serial_sequence(${quoteLiteral(qualified(schema, table.name))}, ${quoteLiteral(column.name)}), GREATEST(${top}, 1), ${top} >= 1); END $${sqlTag}$;\n`;
63
+ })
64
+ .join("");
65
+ }
66
+ export function indexSql(schema, table) {
67
+ return table.indexes
68
+ .map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${index.columns.map(quoteIdent).join(", ")});\n`)
69
+ .join("");
70
+ }
71
+ const REFERENTIAL_ACTIONS = new Set(["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"]);
72
+ function action(value) {
73
+ const upper = value.toUpperCase();
74
+ return REFERENTIAL_ACTIONS.has(upper) ? upper : "NO ACTION";
75
+ }
76
+ function sameColumns(a, b) {
77
+ return a.length === b.length && [...a].sort().join("\u0000") === [...b].sort().join("\u0000");
78
+ }
79
+ /** The parent columns this key points at, when Postgres will accept it; `null` = leave the key out. */
80
+ function parentColumns(fk, byName) {
81
+ const parent = byName.get(fk.foreignTable);
82
+ if (parent === undefined)
83
+ return null;
84
+ const columns = fk.foreignColumns ?? parent.primaryKey;
85
+ if (columns.length !== fk.columns.length)
86
+ return null;
87
+ const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && sameColumns(index.columns, columns));
88
+ return unique ? columns : null;
89
+ }
90
+ function constraintsOf(schema, table, byName) {
91
+ const checks = table.checks.map((check) => ({ table: table.name, name: fitIdentifier(check.name), add: `CHECK (${check.sql})` }));
92
+ const keys = table.foreignKeys.flatMap((fk) => {
93
+ const parent = parentColumns(fk, byName);
94
+ if (parent === null)
95
+ return [];
96
+ const columns = fk.columns.map(quoteIdent).join(", ");
97
+ const references = `${qualified(schema, fk.foreignTable)} (${parent.map(quoteIdent).join(", ")})`;
98
+ return [{ table: table.name, name: fitIdentifier(fk.name), add: `FOREIGN KEY (${columns}) REFERENCES ${references} ON DELETE ${action(fk.onDelete)} ON UPDATE ${action(fk.onUpdate)}` }];
99
+ });
100
+ return [...checks, ...keys];
101
+ }
102
+ /**
103
+ * Every CHECK and foreign key, added NOT VALID and then validated; a failed validation is recorded
104
+ * in {@link UNVALIDATED_TABLE} as `table.constraint` and the constraint stays in place, unvalidated.
105
+ *
106
+ * @complexity O(constraints) statements.
107
+ */
108
+ export function constraintSql(schema, tables, unvalidatedTable, sqlTag = "transfer") {
109
+ const UNVALIDATED_TABLE = unvalidatedTable.split(".").map(quoteIdent).join(".");
110
+ const byName = new Map(tables.map((table) => [table.name, table]));
111
+ const pending = tables.flatMap((table) => constraintsOf(schema, table, byName));
112
+ const adds = pending.map(({ table, name, add }) => `ALTER TABLE ${qualified(schema, table)} ADD CONSTRAINT ${quoteIdent(name)} ${add} NOT VALID;\n`);
113
+ const validations = pending.map(({ table, name }) => ` BEGIN ALTER TABLE ${qualified(schema, table)} VALIDATE CONSTRAINT ${quoteIdent(name)};\n` +
114
+ ` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral(`${table}.${name}`)}); END;\n`);
115
+ return (`CREATE TEMP TABLE ${quoteIdent(unvalidatedTable.split(".").at(-1))} (name text NOT NULL) ON COMMIT DROP;\n` +
116
+ adds.join("") +
117
+ (validations.length === 0 ? "" : `DO $${sqlTag}$ BEGIN\n${validations.join("")}END $${sqlTag}$;\n`));
118
+ }
119
+ //# sourceMappingURL=internal-ddl.js.map
@@ -0,0 +1,28 @@
1
+ /** Every physical source must account for every table before a copy can be planned. */
2
+ import type { TransferSource } from "./sqlite-source.js";
3
+ import type { SnapshotTablePlan } from "./table-catalog.js";
4
+ export interface TransferPlanSource extends SnapshotTablePlan {
5
+ readonly name: string;
6
+ readonly source: TransferSource;
7
+ /** Optional frozen counts from a prior plan; checked inside the destination transaction. */
8
+ readonly counts?: readonly import("./copy-engine.js").TableCount[];
9
+ }
10
+ export declare class IncompleteTransferPlanError extends Error {
11
+ readonly missing: readonly {
12
+ source: string;
13
+ table: string;
14
+ }[];
15
+ constructor({ missing }: {
16
+ missing: readonly {
17
+ source: string;
18
+ table: string;
19
+ }[];
20
+ }, _optional?: {});
21
+ }
22
+ /** O(source tables): completeness is per source; a catalog in another DB cannot conceal a gap. */
23
+ export declare function planTransfer({ sources }: {
24
+ sources: readonly TransferPlanSource[];
25
+ }, _optional?: {}): {
26
+ sources: readonly TransferPlanSource[];
27
+ };
28
+ //# sourceMappingURL=plan.d.ts.map
@@ -0,0 +1,19 @@
1
+ export class IncompleteTransferPlanError extends Error {
2
+ missing;
3
+ constructor({ missing }, _optional = {}) {
4
+ super(`incomplete transfer plan: ${missing.map(entry => `${entry.source}: ${entry.table}`).join(", ")}`);
5
+ this.name = "IncompleteTransferPlanError";
6
+ this.missing = missing;
7
+ }
8
+ }
9
+ /** O(source tables): completeness is per source; a catalog in another DB cannot conceal a gap. */
10
+ export function planTransfer({ sources }, _optional = {}) {
11
+ const missing = sources.flatMap(({ name, source, tables, leftOut }) => {
12
+ const accounted = new Set([...tables.map(table => table.name), ...leftOut.filter(entry => entry.reason.trim() !== "").map(entry => entry.table)]);
13
+ return source.tableNames().filter(table => !accounted.has(table)).map(table => ({ source: name, table }));
14
+ });
15
+ if (missing.length > 0)
16
+ throw new IncompleteTransferPlanError({ missing });
17
+ return { sources };
18
+ }
19
+ //# sourceMappingURL=plan.js.map
@@ -0,0 +1,36 @@
1
+ import type { TransferTable } from "./types.js";
2
+ export declare function quoteIdent({ name }: {
3
+ name: string;
4
+ }, _optional?: {}): string;
5
+ export declare function quoteLiteral({ value }: {
6
+ value: string;
7
+ }, _optional?: {}): string;
8
+ export declare function qualified({ schema, table }: {
9
+ schema: string;
10
+ table: string;
11
+ }, _optional?: {}): string;
12
+ export declare function fitIdentifier({ name }: {
13
+ name: string;
14
+ }, _optional?: {}): string;
15
+ export declare function createTableSql({ schema, table }: {
16
+ schema: string;
17
+ table: TransferTable;
18
+ }, _optional?: {}): string;
19
+ export declare function indexSql({ schema, table }: {
20
+ schema: string;
21
+ table: TransferTable;
22
+ }, _optional?: {}): string;
23
+ export declare function reseedIdentitySql({ schema, table }: {
24
+ schema: string;
25
+ table: TransferTable;
26
+ }, optional?: {
27
+ sqlTag?: string | undefined;
28
+ }): string;
29
+ export declare function constraintSql({ schema, tables, unvalidatedTable }: {
30
+ schema: string;
31
+ tables: readonly TransferTable[];
32
+ unvalidatedTable: string;
33
+ }, optional?: {
34
+ sqlTag?: string | undefined;
35
+ }): string;
36
+ //# sourceMappingURL=postgres-ddl.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Public named-argument DDL API; the moved ordering/constraint rationale is in internal-ddl.ts. */
2
+ import * as ddl from "./internal-ddl.js";
3
+ const tag = (sqlTag = "transfer") => {
4
+ if (!/^[a-z_][a-z0-9_]*$/.test(sqlTag))
5
+ throw new Error("invalid SQL dollar-quote tag");
6
+ return sqlTag;
7
+ };
8
+ export function quoteIdent({ name }, _optional = {}) { return ddl.quoteIdent(name); }
9
+ export function quoteLiteral({ value }, _optional = {}) { return ddl.quoteLiteral(value); }
10
+ export function qualified({ schema, table }, _optional = {}) { return ddl.qualified(schema, table); }
11
+ export function fitIdentifier({ name }, _optional = {}) { return ddl.fitIdentifier(name); }
12
+ export function createTableSql({ schema, table }, _optional = {}) { return ddl.createTableSql(schema, table); }
13
+ export function indexSql({ schema, table }, _optional = {}) { return ddl.indexSql(schema, table); }
14
+ export function reseedIdentitySql({ schema, table }, optional = {}) { return ddl.reseedIdentitySql(schema, table, tag(optional.sqlTag)); }
15
+ export function constraintSql({ schema, tables, unvalidatedTable }, optional = {}) { return ddl.constraintSql(schema, tables, unvalidatedTable, tag(optional.sqlTag)); }
16
+ //# sourceMappingURL=postgres-ddl.js.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @file The Postgres side of a database transfer, behind a port, plus its P0 adapter.
3
+ *
4
+ * The adapter shells out to `psql` rather than selecting a driver. Historically P0 had no installed
5
+ * Postgres driver, and adding `pg` was a supply-chain decision for later slices (see
6
+ * `ADS-memory/reports/2026-09-27-assistant-db-transfer-plan.md` §3.3). The port is what the copier
7
+ * depends on, so swapping in `pg` later touches only this file.
8
+ *
9
+ * The connection string never reaches `psql`'s argv (visible to `ps`): it is split into libpq's own
10
+ * `PG*` environment variables, and every inherited `PG*` variable is dropped first so a stray
11
+ * `PGPASSWORD` in the server's environment can never apply to a user's database.
12
+ */
13
+ /** What may be shown about a destination: never the password. */
14
+ export interface TargetDescription {
15
+ readonly host: string;
16
+ readonly port: string;
17
+ readonly database: string;
18
+ readonly user: string;
19
+ }
20
+ /** `error` is psql's first ERROR line with every quoted part blanked (Postgres quotes the offending
21
+ * value there); `copyTable` names the table a failed `COPY` was loading. */
22
+ export type TargetResult<T> = {
23
+ readonly ok: true;
24
+ readonly value: T;
25
+ } | {
26
+ readonly ok: false;
27
+ readonly error: string;
28
+ readonly copyTable?: string;
29
+ };
30
+ export interface PostgresTargetPort {
31
+ describe(): TargetDescription;
32
+ /** One statement; rows as tab-separated text cells. */
33
+ query(sql: string): Promise<TargetResult<string[][]>>;
34
+ /** A psql script fed through stdin, chunk by chunk, stopping at the first error. */
35
+ runScript(chunks: Iterable<string>): Promise<TargetResult<null>>;
36
+ }
37
+ export declare class InvalidConnectionStringError extends Error {
38
+ }
39
+ interface ParsedConnection {
40
+ readonly description: TargetDescription;
41
+ readonly env: Readonly<Record<string, string>>;
42
+ }
43
+ /**
44
+ * Splits a `postgres://` / `postgresql://` URL into libpq environment variables.
45
+ *
46
+ * @throws {InvalidConnectionStringError} With a message that never quotes the string itself.
47
+ */
48
+ export declare function parseConnectionString({ raw }: {
49
+ raw: string;
50
+ }, { applicationName }?: {
51
+ applicationName?: string;
52
+ }): ParsedConnection;
53
+ /**
54
+ * The P0 adapter: every call is one short-lived `psql` process.
55
+ *
56
+ * @throws {InvalidConnectionStringError} When the string cannot be parsed.
57
+ */
58
+ export declare function createPsqlPostgresTarget({ connectionString }: {
59
+ connectionString: string;
60
+ }, { parentEnv, applicationName }?: {
61
+ parentEnv?: NodeJS.ProcessEnv;
62
+ applicationName?: string;
63
+ }): PostgresTargetPort;
64
+ export {};
65
+ //# sourceMappingURL=postgres-target.d.ts.map