@jini-ai/db 0.7.3-next.2 → 0.7.3-next.3
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 +46 -1
- package/dist/core/ports.d.ts +2 -2
- package/dist/core/ports.js +2 -2
- package/dist/data-modules/data-module.d.ts +2 -46
- package/dist/data-modules/plugin-identity.d.ts +2 -11
- package/dist/data-modules/snapshot.d.ts +5 -3
- package/dist/data-modules/snapshot.js +5 -3
- package/dist/events/change-set-repo.sql.d.ts +18 -5
- package/dist/events/change-set-repo.sql.js +25 -8
- package/dist/events/index.d.ts +1 -1
- package/dist/events/outbox-repo.sql.d.ts +26 -1
- package/dist/events/outbox-repo.sql.js +36 -2
- package/dist/events/repo.rows.d.ts +22 -4
- package/dist/events/repo.rows.js +32 -4
- package/dist/kernel/idle-turn.d.ts +62 -0
- package/dist/kernel/idle-turn.js +32 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.js +28 -0
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/sqlite/driver.js +2 -0
- package/dist/kernel/turn-lock.d.ts +2 -0
- package/dist/kernel/turn-lock.js +7 -0
- package/dist/pglite/copy-source.d.ts +45 -0
- package/dist/pglite/copy-source.js +36 -0
- package/dist/pglite/index.d.ts +1 -0
- package/dist/pglite/index.js +1 -0
- package/dist/react/recovery/Recovery.d.ts +205 -0
- package/dist/react/recovery/Recovery.js +141 -0
- package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
- package/dist/react/recovery/Recovery.restore-steps.js +71 -0
- package/dist/recovery/agent-tools.d.ts +33 -0
- package/dist/recovery/agent-tools.js +166 -0
- package/dist/recovery/drift.d.ts +47 -0
- package/dist/recovery/drift.js +51 -0
- package/dist/recovery/journal-kernel.d.ts +80 -0
- package/dist/recovery/journal-kernel.js +40 -0
- package/dist/recovery/journal-repo.sql.d.ts +154 -0
- package/dist/recovery/journal-repo.sql.js +303 -0
- package/dist/recovery/journal-schema.d.ts +37 -0
- package/dist/recovery/journal-schema.js +110 -0
- package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
- package/dist/recovery/migrate-forward-hooks.js +3 -3
- package/dist/recovery/operation-lock.d.ts +2 -17
- package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
- package/dist/recovery/reconcile-interrupted-migration.js +0 -30
- package/dist/recovery/restore-hooks.d.ts +4 -0
- package/dist/recovery/restore-hooks.js +1 -1
- package/dist/recovery/tool-registrations.d.ts +175 -0
- package/dist/recovery/tool-registrations.js +295 -0
- package/dist/site/repo.memory.d.ts +149 -0
- package/dist/site/repo.memory.js +162 -0
- package/dist/site/tool-registrations.d.ts +130 -0
- package/dist/site/tool-registrations.js +185 -0
- package/dist/sqlite/backup-policy.d.ts +14 -0
- package/dist/sqlite/backup-policy.js +47 -3
- package/dist/sqlite/compaction-steps.d.ts +43 -0
- package/dist/sqlite/compaction-steps.js +73 -0
- package/dist/sqlite/compaction.d.ts +63 -0
- package/dist/sqlite/compaction.js +263 -0
- package/dist/sqlite/index.d.ts +2 -1
- package/dist/sqlite/index.js +2 -1
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/plan-store.d.ts +1 -1
- package/dist/tools/plan-store.js +10 -6
- package/dist/tools/site-db-messages.d.ts +10 -0
- package/dist/tools/site-db-messages.js +23 -0
- package/dist/tools/site-transfer-messages.d.ts +9 -0
- package/dist/tools/site-transfer-messages.js +20 -0
- package/dist/transfer/confirmation-ui.d.ts +19 -0
- package/dist/transfer/confirmation-ui.js +39 -0
- package/dist/transfer/copy-engine.js +11 -11
- package/dist/transfer/destination-store.d.ts +69 -0
- package/dist/transfer/destination-store.js +75 -0
- package/dist/transfer/index.d.ts +2 -0
- package/dist/transfer/index.js +2 -0
- package/dist/transfer/internal-ddl.d.ts +6 -2
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +2 -2
- package/dist/transfer/schema-catalog.d.ts +148 -0
- package/dist/transfer/schema-catalog.js +141 -0
- package/dist/transfer/sqlite-backup.d.ts +27 -0
- package/dist/transfer/sqlite-backup.js +31 -0
- package/dist/transfer/table-catalog.js +1 -0
- package/dist/watermark/kernel.d.ts +64 -0
- package/dist/watermark/kernel.js +45 -0
- package/package.json +104 -9
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Site wording for the `@jini-ai/db/tools` transfer tools. The package defaults speak of "the
|
|
3
|
+
* source"; a host that serves one site has its transfer tools say "this site", and the four
|
|
4
|
+
* descriptions are the bytes the host's descriptor snapshot pins from the pre-extraction catalog.
|
|
5
|
+
* `plan` names the real schemas from the host's `TransferNaming` (its default schema and per-site prefix).
|
|
6
|
+
*/
|
|
7
|
+
export const SITE_TRANSFER_MESSAGES = {
|
|
8
|
+
planIdDescription: "The planId database_transfer_plan returned. Single-use; valid for 10 minutes.",
|
|
9
|
+
plan: ({ naming }) => `Plans a COPY of this site's data into a Postgres database (for example 'move/transfer/copy my data to Postgres'). The site keeps running on its built-in storage; this only makes a copy, into the site's own private area (Postgres schema) on that database: '${naming.defaultSchema}' for the first site copied there, '${naming.schemaPrefix}<site name>' for any other, and always the same one for this site afterwards. Several sites can share one database; each copy replaces only its own area. Read-only: it snapshots the site database, connects to the saved destination, and counts what would be copied. Logins, saved keys and secret settings are never copied; photos and files stay where they are. No input: the destination is the one the human saved with database_transfer_set_destination. Returns {planned: true, planId, expiresAt, destination: {host, port, database, user}, area (the schema), snapshotAt, tableCount, rowCount, replaces (the earlier copy's time, or null), leftOut, notes, nextStep}, or {planned: false, code, message} (codes: NO_DESTINATION, UNREACHABLE, SERVER_TOO_OLD, NO_CREATE_PERMISSION, TARGET_NOT_OURS, DATABASE_SNAPSHOT_FAILED, SCHEMA_MISMATCH, UNAVAILABLE). Tell the human in plain words what will be copied, then call database_transfer_run with the planId.`,
|
|
10
|
+
setDestination: "Asks the human where a copy of this site's data should go: shows a private form where they paste a Postgres database address. HUMAN-GATED: this one call shows the form and WAITS. You never see the address, and must never ask for it in chat; if the human pastes one into the chat anyway, do not repeat it, call this tool, and suggest they change that database password. Checks that the database can be reached before saving it (one destination per site; saving replaces the earlier one). Returns {saved: true, destination: {host, port, database, user}, replaces (the time of a copy this site already made there, or null)}, {saved: false, code, message} (INVALID_CONNECTION_STRING, UNREACHABLE, SERVER_TOO_OLD, NO_CREATE_PERMISSION, TARGET_NOT_OURS), or {saved: false, reason} (cancelled, expired, abandoned). Then call database_transfer_plan.",
|
|
11
|
+
status: "Reports where this site's data copy goes and how the last copy went ('is my data copied?', 'when was the last copy?'). Read-only. Returns {destination: {host, port, database, user} or null, lastRun: {copied: true, snapshotAt, tableCount, rowCount} or {copied: false, snapshotAt, code, message} or null (since the server started), copyOnDestination: {site, snapshotAt} or null, or {unreachable: message}}.",
|
|
12
|
+
run: "Copies the data planned by database_transfer_plan. A first copy runs immediately without a confirmation card. Replacing an earlier copy permanently deletes its destination schema: this one call shows a Copy/Cancel card and WAITS; there is no second call. On Copy it writes the planned snapshot as one transaction into this site's private area (this site's earlier copy is replaced; other sites' copies and anything else in the database are untouched), checks every table's row count, and returns {copied: true, destination, area, snapshotAt, tableCount, rowCount, tables: [{name, rows}]}. Any failure throws the copy away and keeps the earlier one: {copied: false, cancelled: false, code, message} (TARGET_NOT_OURS, COPY_FAILED, COUNT_MISMATCH, PLAN_NOT_FOUND, PLAN_EXPIRED). Cancel returns {copied: false, cancelled: true}.",
|
|
13
|
+
privateAreasTaken: ({ where }) => `every private area this site could use in ${where} already holds other data. Nothing will be overwritten.`,
|
|
14
|
+
noDestination: "no destination database is saved for this site yet",
|
|
15
|
+
uncheckedLinks: "Some copied rows point at records that no longer exist in this site's data. Those links are kept but marked unchecked on the destination; everything was still copied.",
|
|
16
|
+
destinationSaved: ({ database, host }) => `Copies of this site's data will go to ${database} on ${host}.`,
|
|
17
|
+
missingSourceTable: ({ table }) => `this site's database has no '${table}' table`,
|
|
18
|
+
missingSourceColumn: ({ table, column }) => `this site's database has no '${table}.${column}' column`,
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=site-transfer-messages.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { HumanConfirmSpec } from "@jini-ai/core/contracts/site/human-confirm";
|
|
2
|
+
import type { DatabaseTransferPlan } from "../tools/index.js";
|
|
3
|
+
/**
|
|
4
|
+
* @file The card `database_transfer_run` raises before anything is written. Same held-open exchange
|
|
5
|
+
* as `site backup confirmation`: Copy/Cancel carry `SURFACE_EXCHANGE_ID_PARAM` back to the same
|
|
6
|
+
* tool call. Plain words only (no "schema", "role" or "connection string"): where the copy goes, how
|
|
7
|
+
* much, what is left out, and that the site itself does not change.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DATABASE_TRANSFER_RUN_TOOL_ID = "database_transfer_run";
|
|
10
|
+
/** `3:41 PM, Sep 27` in the server's locale-neutral English. */
|
|
11
|
+
export declare function formatSnapshotTime({ iso }: {
|
|
12
|
+
iso: string;
|
|
13
|
+
}, _optional?: {}): string;
|
|
14
|
+
/** `spec.expiresAtMs` is the exchange's deadline, so the chat counts the card down and closes it — as
|
|
15
|
+
* `requireHumanConfirm` does. @complexity O(left-out tables). */
|
|
16
|
+
export declare function describeTransferApproval({ plan }: {
|
|
17
|
+
plan: DatabaseTransferPlan;
|
|
18
|
+
}, _optional?: {}): HumanConfirmSpec;
|
|
19
|
+
//# sourceMappingURL=confirmation-ui.d.ts.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The card `database_transfer_run` raises before anything is written. Same held-open exchange
|
|
3
|
+
* as `site backup confirmation`: Copy/Cancel carry `SURFACE_EXCHANGE_ID_PARAM` back to the same
|
|
4
|
+
* tool call. Plain words only (no "schema", "role" or "connection string"): where the copy goes, how
|
|
5
|
+
* much, what is left out, and that the site itself does not change.
|
|
6
|
+
*/
|
|
7
|
+
export const DATABASE_TRANSFER_RUN_TOOL_ID = "database_transfer_run";
|
|
8
|
+
/** `3:41 PM, Sep 27` in the server's locale-neutral English. */
|
|
9
|
+
export function formatSnapshotTime({ iso }, _optional = {}) {
|
|
10
|
+
const date = new Date(iso);
|
|
11
|
+
if (Number.isNaN(date.getTime()))
|
|
12
|
+
return iso;
|
|
13
|
+
return date.toLocaleString("en-US", { hour: "numeric", minute: "2-digit", month: "short", day: "numeric" });
|
|
14
|
+
}
|
|
15
|
+
function plural({ n, one, many }, _optional = {}) {
|
|
16
|
+
return `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
|
|
17
|
+
}
|
|
18
|
+
/** `spec.expiresAtMs` is the exchange's deadline, so the chat counts the card down and closes it — as
|
|
19
|
+
* `requireHumanConfirm` does. @complexity O(left-out tables). */
|
|
20
|
+
export function describeTransferApproval({ plan }, _optional = {}) {
|
|
21
|
+
const where = `${plan.destination.database} on ${plan.destination.host}`;
|
|
22
|
+
const leftOutRows = plan.leftOut.reduce((sum, entry) => sum + entry.rows, 0);
|
|
23
|
+
const details = [
|
|
24
|
+
{ label: "Destination", value: where },
|
|
25
|
+
{ label: "Copies", value: `${plural({ n: plan.tableCount, one: "table", many: "tables" })}, ${plural({ n: plan.rowCount, one: "row", many: "rows" })}, as of ${formatSnapshotTime({ iso: plan.snapshotAt })}` },
|
|
26
|
+
{ label: "Goes into", value: `A private area named "${plan.schema}". Nothing else in that database is touched.` },
|
|
27
|
+
{ label: "Replaces", value: plan.replaces === null ? "Nothing. This is the first copy." : `The earlier copy from ${formatSnapshotTime({ iso: plan.replaces })}` },
|
|
28
|
+
{ label: "Left out", value: `Logins and saved keys (${plural({ n: leftOutRows, one: "row", many: "rows" })}). Photos and files stay where they are.` },
|
|
29
|
+
];
|
|
30
|
+
return {
|
|
31
|
+
toolId: DATABASE_TRANSFER_RUN_TOOL_ID, errorCode: "DATABASE_TRANSFER",
|
|
32
|
+
title: `Copy this site's data to ${where}?`,
|
|
33
|
+
description: "Your site keeps running on its built-in storage. This only makes a copy.",
|
|
34
|
+
details,
|
|
35
|
+
...(plan.replaces === null ? {} : { warning: `The earlier copy from ${formatSnapshotTime({ iso: plan.replaces })} is replaced once this copy has been checked.` }),
|
|
36
|
+
confirmLabel: "Copy", cancelLabel: "Cancel",
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=confirmation-ui.js.map
|
|
@@ -76,7 +76,7 @@ export function countSourceRows({ source, tables }, _optional = {}) {
|
|
|
76
76
|
}
|
|
77
77
|
/** Every marker on the server: schema, the site of its newest row, and whether any row names a different site. */
|
|
78
78
|
async function readMarkers(target, TRANSFER_MARKER_TABLE) {
|
|
79
|
-
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`);
|
|
79
|
+
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({ value: TRANSFER_MARKER_TABLE })} AND c.relkind = 'r' ORDER BY 1`);
|
|
80
80
|
if (!listed.ok)
|
|
81
81
|
return listed;
|
|
82
82
|
const markers = [];
|
|
@@ -109,7 +109,7 @@ export async function inspectTarget({ target, site, naming }, _optional = {}) {
|
|
|
109
109
|
if (own !== undefined)
|
|
110
110
|
return { ...base, schemaState: "ours", schema: own.schema, lastCopy: own.copy };
|
|
111
111
|
const candidates = schemaCandidates(site, naming);
|
|
112
|
-
const existing = await target.query(`SELECT nspname FROM pg_namespace WHERE nspname IN (${candidates.map(quoteLiteral).join(", ")})`);
|
|
112
|
+
const existing = await target.query(`SELECT nspname FROM pg_namespace WHERE nspname IN (${candidates.map((value) => quoteLiteral({ value })).join(", ")})`);
|
|
113
113
|
if (!existing.ok)
|
|
114
114
|
return { ok: false, error: existing.error };
|
|
115
115
|
const taken = new Set(existing.value.map(([name]) => name));
|
|
@@ -131,7 +131,7 @@ function copyField(value, table, column) {
|
|
|
131
131
|
function* copyTableData(source, schema, table) {
|
|
132
132
|
const names = table.columns.map((column) => column.name);
|
|
133
133
|
const columns = table.columns;
|
|
134
|
-
yield `COPY ${qualified({ schema, table: table.name })} (${names.map(quoteIdent).join(", ")}) FROM STDIN;\n`;
|
|
134
|
+
yield `COPY ${qualified({ schema, table: table.name })} (${names.map((name) => quoteIdent({ name })).join(", ")}) FROM STDIN;\n`;
|
|
135
135
|
let batch = "";
|
|
136
136
|
for (const row of source.rows(table.name, names, table.keep)) {
|
|
137
137
|
batch += row.map((value, i) => copyField(value, table.name, columns[i])).join("\t") + "\n";
|
|
@@ -147,27 +147,27 @@ function* copyTableData(source, schema, table) {
|
|
|
147
147
|
* with dynamic SQL so a table merely named like it (other columns) also counts as someone else's.
|
|
148
148
|
*/
|
|
149
149
|
function guardSql(schema, site, TRANSFER_MARKER_TABLE, sqlTag) {
|
|
150
|
-
const marker = quoteLiteral(`${quoteIdent(schema)}.${quoteIdent(TRANSFER_MARKER_TABLE)}`);
|
|
150
|
+
const marker = quoteLiteral({ value: `${quoteIdent({ name: schema })}.${quoteIdent({ name: TRANSFER_MARKER_TABLE })}` });
|
|
151
151
|
return (`DO $${sqlTag}$ DECLARE mine bigint; total bigint; BEGIN\n` +
|
|
152
|
-
` IF to_regnamespace(${quoteLiteral(quoteIdent(schema))}) IS NULL THEN RETURN; END IF;\n` +
|
|
152
|
+
` IF to_regnamespace(${quoteLiteral({ value: quoteIdent({ name: schema }) })}) IS NULL THEN RETURN; END IF;\n` +
|
|
153
153
|
` IF to_regclass(${marker}) IS NULL THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}'; END IF;\n` +
|
|
154
154
|
` BEGIN\n` +
|
|
155
|
-
` EXECUTE format('SELECT count(*) FILTER (WHERE site = %L), count(*) FROM %s', ${quoteLiteral(site)}, ${marker}) INTO mine, total;\n` +
|
|
155
|
+
` EXECUTE format('SELECT count(*) FILTER (WHERE site = %L), count(*) FROM %s', ${quoteLiteral({ value: site })}, ${marker}) INTO mine, total;\n` +
|
|
156
156
|
` EXCEPTION WHEN undefined_column THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}';\n` +
|
|
157
157
|
` END;\n` +
|
|
158
158
|
` IF mine = 0 OR mine <> total THEN RAISE EXCEPTION '${FOREIGN_SCHEMA_SIGNAL}'; END IF;\n` +
|
|
159
159
|
`END $${sqlTag}$;\n`);
|
|
160
160
|
}
|
|
161
161
|
function countCheckSql(schema, counts, sqlTag) {
|
|
162
|
-
const checks = counts.map(({ table, rows }) => `SELECT count(*) INTO n FROM ${qualified({ schema, table: table.name })}; IF n <> ${rows} THEN RAISE EXCEPTION ${quoteLiteral(COUNT_MISMATCH_SIGNAL + " " + table.name)}; END IF;`);
|
|
162
|
+
const checks = counts.map(({ table, rows }) => `SELECT count(*) INTO n FROM ${qualified({ schema, table: table.name })}; IF n <> ${rows} THEN RAISE EXCEPTION ${quoteLiteral({ value: COUNT_MISMATCH_SIGNAL + " " + table.name })}; END IF;`);
|
|
163
163
|
return `DO $${sqlTag}$ DECLARE n bigint; BEGIN ${checks.join(" ")} END $${sqlTag}$;\n`;
|
|
164
164
|
}
|
|
165
165
|
function markerSql(schema, marker, counts, naming) {
|
|
166
166
|
const TRANSFER_MARKER_TABLE = naming.markerTable;
|
|
167
|
-
const UNVALIDATED_TABLE = naming.unvalidatedTable.split(".").map(quoteIdent).join(".");
|
|
167
|
+
const UNVALIDATED_TABLE = naming.unvalidatedTable.split(".").map((name) => quoteIdent({ name })).join(".");
|
|
168
168
|
const tableCounts = JSON.stringify(Object.fromEntries(counts.map(({ table, rows }) => [table.name, rows])));
|
|
169
169
|
return (`CREATE TABLE ${qualified({ schema, table: 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` +
|
|
170
|
-
`INSERT INTO ${qualified({ schema, table: TRANSFER_MARKER_TABLE })} (site, snapshot_at, table_counts, unvalidated) VALUES (${quoteLiteral(marker.site)}, ${quoteLiteral(marker.snapshotAt)}, ${quoteLiteral(tableCounts)}::jsonb, ` +
|
|
170
|
+
`INSERT INTO ${qualified({ schema, table: TRANSFER_MARKER_TABLE })} (site, snapshot_at, table_counts, unvalidated) VALUES (${quoteLiteral({ value: marker.site })}, ${quoteLiteral({ value: marker.snapshotAt })}, ${quoteLiteral({ value: tableCounts })}::jsonb, ` +
|
|
171
171
|
`(SELECT coalesce(jsonb_agg(name ORDER BY name), '[]'::jsonb) FROM ${UNVALIDATED_TABLE}));\n`);
|
|
172
172
|
}
|
|
173
173
|
function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
|
|
@@ -176,8 +176,8 @@ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
|
|
|
176
176
|
yield guardSql(schema, marker.site, naming.markerTable, sqlTag);
|
|
177
177
|
// A first copy must fail if the schema appeared since planning, never delete it.
|
|
178
178
|
if (replaceExisting)
|
|
179
|
-
yield `DROP SCHEMA IF EXISTS ${quoteIdent(schema)} CASCADE;\n`;
|
|
180
|
-
yield `CREATE SCHEMA ${quoteIdent(schema)};\n`;
|
|
179
|
+
yield `DROP SCHEMA IF EXISTS ${quoteIdent({ name: schema })} CASCADE;\n`;
|
|
180
|
+
yield `CREATE SCHEMA ${quoteIdent({ name: schema })};\n`;
|
|
181
181
|
for (const { table } of counts)
|
|
182
182
|
yield createTableSql({ schema, table });
|
|
183
183
|
for (const { source, counts: sourceCounts } of sources) {
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { CredentialTokenHint } from "@jini-ai/core/contracts/site/secrets-credential-token";
|
|
2
|
+
import type { SecretsVaultService } from "@jini-ai/core/contracts/site/secrets-credential-sets";
|
|
3
|
+
import { type VaultRepoPort, type VaultContext, type VaultMetaParser } from "@jini-ai/core/contracts/vault";
|
|
4
|
+
import type { TargetDescription } from "./postgres-target.js";
|
|
5
|
+
export interface SavedDatabaseDestination {
|
|
6
|
+
readonly connectionString: string;
|
|
7
|
+
readonly tokenHint?: CredentialTokenHint;
|
|
8
|
+
readonly description: TargetDescription;
|
|
9
|
+
readonly savedAt: string;
|
|
10
|
+
}
|
|
11
|
+
/** What `database_transfer_status` reports about the last run. Never row data, never the address. */
|
|
12
|
+
export type DatabaseTransferRunSummary = {
|
|
13
|
+
readonly copied: true;
|
|
14
|
+
readonly snapshotAt: string;
|
|
15
|
+
readonly tableCount: number;
|
|
16
|
+
readonly rowCount: number;
|
|
17
|
+
} | {
|
|
18
|
+
readonly copied: false;
|
|
19
|
+
readonly snapshotAt: string;
|
|
20
|
+
readonly code: string;
|
|
21
|
+
readonly message: string;
|
|
22
|
+
};
|
|
23
|
+
export interface DatabaseDestinationStorePort {
|
|
24
|
+
/** @throws {DestinationUnreadableError} When a saved address exists but cannot be opened. */
|
|
25
|
+
get(workspaceId: string): Promise<SavedDatabaseDestination | null>;
|
|
26
|
+
/** Replaces any earlier destination for the workspace, and forgets its last run. */
|
|
27
|
+
save(workspaceId: string, destination: SavedDatabaseDestination): Promise<void>;
|
|
28
|
+
lastRun(workspaceId: string): Promise<DatabaseTransferRunSummary | null>;
|
|
29
|
+
recordRun(workspaceId: string, summary: DatabaseTransferRunSummary): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/** A saved address that no longer opens: another site key, or a row moved between workspaces. */
|
|
32
|
+
export declare class DestinationUnreadableError extends Error {
|
|
33
|
+
constructor();
|
|
34
|
+
}
|
|
35
|
+
/** Internal persistence follows the shared vault port; public store methods stay unchanged.
|
|
36
|
+
* The destination is a singleton (`secrets_vault_singleton`), so it is read with `findOne`, never
|
|
37
|
+
* `findDefault`: 0012 copied legacy rows with is_default=false (the old table had no such column),
|
|
38
|
+
* and a default-only read made an upgraded site's destination invisible (parity finding R1). */
|
|
39
|
+
export type DatabaseDestinationRepoPort = VaultRepoPort & Required<Pick<VaultRepoPort, "findOne">>;
|
|
40
|
+
export declare class SealedDatabaseDestinationStore implements DatabaseDestinationStorePort {
|
|
41
|
+
private readonly deps;
|
|
42
|
+
constructor(deps: {
|
|
43
|
+
readonly repo: DatabaseDestinationRepoPort;
|
|
44
|
+
readonly vault: Pick<SecretsVaultService, "findOne" | "put" | "patchMeta">;
|
|
45
|
+
readonly scope: {
|
|
46
|
+
readonly kind: VaultContext["kind"];
|
|
47
|
+
readonly ownerKey: string;
|
|
48
|
+
readonly principalId: null;
|
|
49
|
+
readonly provider: null;
|
|
50
|
+
readonly binding: null;
|
|
51
|
+
};
|
|
52
|
+
readonly parseMeta: VaultMetaParser;
|
|
53
|
+
readonly normalizeAddress: (required: {
|
|
54
|
+
value: string;
|
|
55
|
+
}) => string;
|
|
56
|
+
}, _optional?: {});
|
|
57
|
+
/** One indexed singleton read and at most one open; raw crypto errors never leave the store. */
|
|
58
|
+
get(workspaceId: string): Promise<SavedDatabaseDestination | null>;
|
|
59
|
+
/** Replaces the singleton through Jini's seal/CAS lifecycle and clears the previous last run. */
|
|
60
|
+
save(workspaceId: string, destination: SavedDatabaseDestination): Promise<void>;
|
|
61
|
+
/** Status is validated metadata, so it remains readable even when the site key is unavailable. */
|
|
62
|
+
lastRun(workspaceId: string): Promise<DatabaseTransferRunSummary | null>;
|
|
63
|
+
/** Targeted jsonSet + CAS never rewrites a credential. A replacement or deletion wins over the
|
|
64
|
+
* old run; competing metadata patches may retry against the same envelope, at most three times.
|
|
65
|
+
* @complexity At most three indexed reads/validated CAS patches, no decryption.
|
|
66
|
+
*/
|
|
67
|
+
recordRun(workspaceId: string, summary: DatabaseTransferRunSummary): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=destination-store.d.ts.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { VaultError } from "@jini-ai/core/contracts/vault";
|
|
2
|
+
/** A saved address that no longer opens: another site key, or a row moved between workspaces. */
|
|
3
|
+
export class DestinationUnreadableError extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super("the saved destination database could not be unlocked (the site's key may have changed); save it again with database_transfer_set_destination");
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export class SealedDatabaseDestinationStore {
|
|
9
|
+
deps;
|
|
10
|
+
constructor(deps, _optional = {}) {
|
|
11
|
+
this.deps = deps;
|
|
12
|
+
}
|
|
13
|
+
/** One indexed singleton read and at most one open; raw crypto errors never leave the store. */
|
|
14
|
+
async get(workspaceId) {
|
|
15
|
+
try {
|
|
16
|
+
const opened = await this.deps.vault.findOne({ ...this.deps.scope, workspaceId });
|
|
17
|
+
if (!opened)
|
|
18
|
+
return null;
|
|
19
|
+
if (typeof opened.payload?.connectionString !== "string")
|
|
20
|
+
throw new VaultError({ code: "invalid-record" });
|
|
21
|
+
const meta = opened.summary.meta;
|
|
22
|
+
// An address is not a token: even its length or suffix can expose connection details.
|
|
23
|
+
return { connectionString: opened.payload.connectionString, description: meta.description,
|
|
24
|
+
savedAt: (meta.savedAt ?? opened.summary.createdAt) };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
throw new DestinationUnreadableError();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Replaces the singleton through Jini's seal/CAS lifecycle and clears the previous last run. */
|
|
31
|
+
async save(workspaceId, destination) {
|
|
32
|
+
const existing = await this.deps.repo.findOne({ ...this.deps.scope, workspaceId });
|
|
33
|
+
if (destination.connectionString === '' && existing)
|
|
34
|
+
return;
|
|
35
|
+
const connectionString = this.deps.normalizeAddress({ value: destination.connectionString });
|
|
36
|
+
await this.deps.vault.put({ ...this.deps.scope, workspaceId, ...(existing ? { id: existing.id } : {}),
|
|
37
|
+
expectedRevision: existing?.revision ?? null, label: existing?.label ?? "Database destination", isDefault: true,
|
|
38
|
+
meta: { ...existing?.meta, description: { ...destination.description }, savedAt: destination.savedAt, lastRun: null },
|
|
39
|
+
payload: { connectionString } });
|
|
40
|
+
}
|
|
41
|
+
/** Status is validated metadata, so it remains readable even when the site key is unavailable. */
|
|
42
|
+
async lastRun(workspaceId) {
|
|
43
|
+
const existing = await this.deps.repo.findOne({ ...this.deps.scope, workspaceId });
|
|
44
|
+
if (!existing)
|
|
45
|
+
return null;
|
|
46
|
+
const meta = this.deps.parseMeta({ meta: existing.meta });
|
|
47
|
+
return meta.lastRun;
|
|
48
|
+
}
|
|
49
|
+
/** Targeted jsonSet + CAS never rewrites a credential. A replacement or deletion wins over the
|
|
50
|
+
* old run; competing metadata patches may retry against the same envelope, at most three times.
|
|
51
|
+
* @complexity At most three indexed reads/validated CAS patches, no decryption.
|
|
52
|
+
*/
|
|
53
|
+
async recordRun(workspaceId, summary) {
|
|
54
|
+
let original = null;
|
|
55
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
56
|
+
const existing = await this.deps.repo.findOne({ ...this.deps.scope, workspaceId });
|
|
57
|
+
if (!existing || (original && !isSameDestination({ existing, original })))
|
|
58
|
+
return;
|
|
59
|
+
original ??= existing;
|
|
60
|
+
try {
|
|
61
|
+
await this.deps.vault.patchMeta({ ...this.deps.scope, workspaceId, id: existing.id,
|
|
62
|
+
expectedRevision: existing.revision, patch: { lastRun: { ...summary } } });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (!(error instanceof VaultError) || error.code !== "conflict" || attempt === 2)
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function isSameDestination({ existing, original }, _options = {}) {
|
|
73
|
+
return existing.id === original.id && JSON.stringify(existing.sealed) === JSON.stringify(original.sealed);
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=destination-store.js.map
|
package/dist/transfer/index.d.ts
CHANGED
|
@@ -4,7 +4,9 @@ export * from "./sqlite-source.js";
|
|
|
4
4
|
export * from "./postgres-target.js";
|
|
5
5
|
export * from "./postgres-ddl.js";
|
|
6
6
|
export * from "./table-catalog.js";
|
|
7
|
+
export * from "./schema-catalog.js";
|
|
7
8
|
export * from "./plan.js";
|
|
8
9
|
export * from "./copy-order.js";
|
|
9
10
|
export * from "./copy-engine.js";
|
|
11
|
+
export * from "./sqlite-backup.js";
|
|
10
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/transfer/index.js
CHANGED
|
@@ -4,7 +4,9 @@ export * from "./sqlite-source.js";
|
|
|
4
4
|
export * from "./postgres-target.js";
|
|
5
5
|
export * from "./postgres-ddl.js";
|
|
6
6
|
export * from "./table-catalog.js";
|
|
7
|
+
export * from "./schema-catalog.js";
|
|
7
8
|
export * from "./plan.js";
|
|
8
9
|
export * from "./copy-order.js";
|
|
9
10
|
export * from "./copy-engine.js";
|
|
11
|
+
export * from "./sqlite-backup.js";
|
|
10
12
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import type { TransferTable } from "./types.js";
|
|
2
2
|
/** A session-local table listing constraints left unvalidated; dropped at commit. */
|
|
3
|
-
export declare function quoteIdent(name
|
|
4
|
-
|
|
3
|
+
export declare function quoteIdent({ name }: {
|
|
4
|
+
name: string;
|
|
5
|
+
}, _optional?: Record<string, never>): string;
|
|
6
|
+
export declare function quoteLiteral({ value }: {
|
|
7
|
+
value: string;
|
|
8
|
+
}, _optional?: Record<string, never>): string;
|
|
5
9
|
export declare function qualified({ schema, table }: {
|
|
6
10
|
schema: string;
|
|
7
11
|
table: string;
|
|
@@ -19,14 +19,14 @@ import { createHash } from "node:crypto";
|
|
|
19
19
|
const MAX_IDENTIFIER_BYTES = 63;
|
|
20
20
|
/** A session-local table listing constraints left unvalidated; dropped at commit. */
|
|
21
21
|
// The host supplies the session-local table name; never rename an existing copy marker.
|
|
22
|
-
export function quoteIdent(name) {
|
|
22
|
+
export function quoteIdent({ name }, _optional = {}) {
|
|
23
23
|
return `"${name.replace(/"/g, '""')}"`;
|
|
24
24
|
}
|
|
25
|
-
export function quoteLiteral(value) {
|
|
25
|
+
export function quoteLiteral({ value }, _optional = {}) {
|
|
26
26
|
return `'${value.replace(/'/g, "''")}'`;
|
|
27
27
|
}
|
|
28
28
|
export function qualified({ schema, table }, _optional = {}) {
|
|
29
|
-
return `${quoteIdent(schema)}.${quoteIdent(table)}`;
|
|
29
|
+
return `${quoteIdent({ name: schema })}.${quoteIdent({ name: table })}`;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
32
32
|
* The name itself when it fits in 63 bytes; otherwise its first bytes plus 8 hex characters of its
|
|
@@ -45,12 +45,12 @@ export function fitIdentifier({ name }, _optional = {}) {
|
|
|
45
45
|
function columnSql(column) {
|
|
46
46
|
const identity = column.identity === undefined ? "" : ` GENERATED ${column.identity} AS IDENTITY`;
|
|
47
47
|
const fallback = column.default === undefined ? "" : ` DEFAULT ${column.default}`;
|
|
48
|
-
return `${quoteIdent(column.name)} ${column.sqlType}${identity}${fallback}${column.notNull ? " NOT NULL" : ""}`;
|
|
48
|
+
return `${quoteIdent({ name: column.name })} ${column.sqlType}${identity}${fallback}${column.notNull ? " NOT NULL" : ""}`;
|
|
49
49
|
}
|
|
50
50
|
export function createTableSql({ schema, table }, _optional = {}) {
|
|
51
51
|
const columns = table.columns.map(columnSql);
|
|
52
52
|
if (table.primaryKey.length > 0)
|
|
53
|
-
columns.push(`PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(", ")})`);
|
|
53
|
+
columns.push(`PRIMARY KEY (${table.primaryKey.map((name) => quoteIdent({ name })).join(", ")})`);
|
|
54
54
|
return `CREATE TABLE ${qualified({ schema, table: table.name })} (${columns.join(", ")});\n`;
|
|
55
55
|
}
|
|
56
56
|
/** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
|
|
@@ -58,8 +58,8 @@ export function reseedIdentitySql({ schema, table }, { sqlTag = "transfer" } = {
|
|
|
58
58
|
return table.columns
|
|
59
59
|
.filter((column) => column.identity !== undefined)
|
|
60
60
|
.map((column) => {
|
|
61
|
-
const top = `COALESCE((SELECT max(${quoteIdent(column.name)}) FROM ${qualified({ schema, table: table.name })}), 0)`;
|
|
62
|
-
return `DO $${sqlTag}$ BEGIN PERFORM setval(pg_get_serial_sequence(${quoteLiteral(qualified({ schema, table: table.name }))}, ${quoteLiteral(column.name)}), GREATEST(${top}, 1), ${top} >= 1); END $${sqlTag}$;\n`;
|
|
61
|
+
const top = `COALESCE((SELECT max(${quoteIdent({ name: column.name })}) FROM ${qualified({ schema, table: table.name })}), 0)`;
|
|
62
|
+
return `DO $${sqlTag}$ BEGIN PERFORM setval(pg_get_serial_sequence(${quoteLiteral({ value: qualified({ schema, table: table.name }) })}, ${quoteLiteral({ value: column.name })}), GREATEST(${top}, 1), ${top} >= 1); END $${sqlTag}$;\n`;
|
|
63
63
|
})
|
|
64
64
|
.join("");
|
|
65
65
|
}
|
|
@@ -70,7 +70,7 @@ export function indexSql({ schema, table }, _optional = {}) {
|
|
|
70
70
|
return table.indexes
|
|
71
71
|
.map((index) => {
|
|
72
72
|
const where = index.where === undefined ? "" : " WHERE " + index.where;
|
|
73
|
-
return `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier({ name: index.name }))} ON ${qualified({ schema, table: table.name })} (${(index.expressions ?? index.columns.map(quoteIdent)).join(", ")})${where};\n`;
|
|
73
|
+
return `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent({ name: fitIdentifier({ name: index.name }) })} ON ${qualified({ schema, table: table.name })} (${(index.expressions ?? index.columns.map((name) => quoteIdent({ name }))).join(", ")})${where};\n`;
|
|
74
74
|
})
|
|
75
75
|
.join("");
|
|
76
76
|
}
|
|
@@ -100,8 +100,8 @@ function constraintsOf(schema, table, byName) {
|
|
|
100
100
|
const parent = parentColumns(fk, byName);
|
|
101
101
|
if (parent === null)
|
|
102
102
|
return [];
|
|
103
|
-
const columns = fk.columns.map(quoteIdent).join(", ");
|
|
104
|
-
const references = `${qualified({ schema, table: fk.foreignTable })} (${parent.map(quoteIdent).join(", ")})`;
|
|
103
|
+
const columns = fk.columns.map((name) => quoteIdent({ name })).join(", ");
|
|
104
|
+
const references = `${qualified({ schema, table: fk.foreignTable })} (${parent.map((name) => quoteIdent({ name })).join(", ")})`;
|
|
105
105
|
return [{ table: table.name, name: fitIdentifier({ name: fk.name }), add: `FOREIGN KEY (${columns}) REFERENCES ${references} ON DELETE ${action(fk.onDelete)} ON UPDATE ${action(fk.onUpdate)}` }];
|
|
106
106
|
});
|
|
107
107
|
return [...checks, ...keys];
|
|
@@ -113,13 +113,13 @@ function constraintsOf(schema, table, byName) {
|
|
|
113
113
|
* @complexity O(constraints) statements.
|
|
114
114
|
*/
|
|
115
115
|
export function constraintSql({ schema, tables, unvalidatedTable }, { sqlTag = "transfer" } = {}) {
|
|
116
|
-
const UNVALIDATED_TABLE = unvalidatedTable.split(".").map(quoteIdent).join(".");
|
|
116
|
+
const UNVALIDATED_TABLE = unvalidatedTable.split(".").map((name) => quoteIdent({ name })).join(".");
|
|
117
117
|
const byName = new Map(tables.map((table) => [table.name, table]));
|
|
118
118
|
const pending = tables.flatMap((table) => constraintsOf(schema, table, byName));
|
|
119
|
-
const adds = pending.map(({ table, name, add }) => `ALTER TABLE ${qualified({ schema, table })} ADD CONSTRAINT ${quoteIdent(name)} ${add} NOT VALID;\n`);
|
|
120
|
-
const validations = pending.map(({ table, name }) => ` BEGIN ALTER TABLE ${qualified({ schema, table })} VALIDATE CONSTRAINT ${quoteIdent(name)};\n` +
|
|
121
|
-
` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral(table + "." + name)}); END;\n`);
|
|
122
|
-
return (`CREATE TEMP TABLE ${quoteIdent(unvalidatedTable.split(".").at(-1))} (name text NOT NULL) ON COMMIT DROP;\n` +
|
|
119
|
+
const adds = pending.map(({ table, name, add }) => `ALTER TABLE ${qualified({ schema, table })} ADD CONSTRAINT ${quoteIdent({ name })} ${add} NOT VALID;\n`);
|
|
120
|
+
const validations = pending.map(({ table, name }) => ` BEGIN ALTER TABLE ${qualified({ schema, table })} VALIDATE CONSTRAINT ${quoteIdent({ name })};\n` +
|
|
121
|
+
` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral({ value: table + "." + name })}); END;\n`);
|
|
122
|
+
return (`CREATE TEMP TABLE ${quoteIdent({ name: unvalidatedTable.split(".").at(-1) })} (name text NOT NULL) ON COMMIT DROP;\n` +
|
|
123
123
|
adds.join("") +
|
|
124
124
|
(validations.length === 0 ? "" : `DO $${sqlTag}$ BEGIN\n${validations.join("")}END $${sqlTag}$;\n`));
|
|
125
125
|
}
|
|
@@ -5,8 +5,8 @@ const tag = (sqlTag = "transfer") => {
|
|
|
5
5
|
throw new Error("invalid SQL dollar-quote tag");
|
|
6
6
|
return sqlTag;
|
|
7
7
|
};
|
|
8
|
-
export function quoteIdent({ name }, _optional = {}) { return ddl.quoteIdent(name); }
|
|
9
|
-
export function quoteLiteral({ value }, _optional = {}) { return ddl.quoteLiteral(value); }
|
|
8
|
+
export function quoteIdent({ name }, _optional = {}) { return ddl.quoteIdent({ name }); }
|
|
9
|
+
export function quoteLiteral({ value }, _optional = {}) { return ddl.quoteLiteral({ value }); }
|
|
10
10
|
export function qualified({ schema, table }, _optional = {}) { return ddl.qualified({ schema, table }); }
|
|
11
11
|
export function fitIdentifier({ name }, _optional = {}) { return ddl.fitIdentifier({ name }); }
|
|
12
12
|
export function createTableSql({ schema, table }, _optional = {}) { return ddl.createTableSql({ schema, table }); }
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { type SnapshotTablePlan } from "./table-catalog.js";
|
|
2
|
+
import type { TransferSource } from "./sqlite-source.js";
|
|
3
|
+
import type { TransferTable } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* @file The generic half of "what a copy carries" for a host schema declared in some ORM: the host
|
|
6
|
+
* injects a structural {@link CatalogIntrospection} (so this package imports no ORM), its exclusion
|
|
7
|
+
* tables and its naming; this module projects the schema into {@link TransferTable}s and plans the snapshot.
|
|
8
|
+
*
|
|
9
|
+
* Every table in the snapshot is either a {@link TransferTable} (with its full Postgres layout: columns,
|
|
10
|
+
* defaults, identity, primary key, indexes, foreign keys and checks) or left out with a reason, never
|
|
11
|
+
* silently dropped ({@link planCatalogSnapshotTables}).
|
|
12
|
+
*
|
|
13
|
+
* - Core tables take their layout from the host's declared schema.
|
|
14
|
+
* - Every other table (a plugin's own tables, for example) takes the layout the snapshot itself declares,
|
|
15
|
+
* translated by SQLite type affinity (see `introspectedTable`).
|
|
16
|
+
*/
|
|
17
|
+
/** One index term: a plain column (the name can be missing in a malformed declaration) or a raw SQL expression. */
|
|
18
|
+
export type CatalogIndexTerm = {
|
|
19
|
+
readonly kind: "column";
|
|
20
|
+
readonly name: string | undefined;
|
|
21
|
+
} | {
|
|
22
|
+
readonly kind: "sql";
|
|
23
|
+
readonly sql: unknown;
|
|
24
|
+
};
|
|
25
|
+
export interface CatalogColumnConfig {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly sqlType: string;
|
|
28
|
+
readonly notNull: boolean;
|
|
29
|
+
/** Inline (single-column) primary key. */
|
|
30
|
+
readonly primary: boolean;
|
|
31
|
+
readonly isUnique: boolean;
|
|
32
|
+
readonly uniqueName?: string;
|
|
33
|
+
readonly hasDefault: boolean;
|
|
34
|
+
/** The declared default: an ORM SQL value, a string, a number or a boolean. */
|
|
35
|
+
readonly default?: unknown;
|
|
36
|
+
readonly identity?: "always" | "byDefault";
|
|
37
|
+
}
|
|
38
|
+
export interface CatalogIndexConfig {
|
|
39
|
+
readonly name?: string;
|
|
40
|
+
readonly terms: readonly CatalogIndexTerm[];
|
|
41
|
+
readonly unique: boolean;
|
|
42
|
+
/** Partial-index predicate as an ORM SQL value. */
|
|
43
|
+
readonly where?: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface CatalogForeignKeyConfig {
|
|
46
|
+
readonly name: string;
|
|
47
|
+
readonly columns: readonly string[];
|
|
48
|
+
readonly foreignTable: string;
|
|
49
|
+
readonly foreignColumns: readonly string[];
|
|
50
|
+
readonly onDelete?: string;
|
|
51
|
+
readonly onUpdate?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface CatalogTableConfig {
|
|
54
|
+
readonly name: string;
|
|
55
|
+
readonly columns: readonly CatalogColumnConfig[];
|
|
56
|
+
readonly indexes: readonly CatalogIndexConfig[];
|
|
57
|
+
readonly uniqueConstraints: readonly {
|
|
58
|
+
readonly name?: string;
|
|
59
|
+
readonly columns: readonly string[];
|
|
60
|
+
}[];
|
|
61
|
+
/** Composite primary keys, one entry per declared key. */
|
|
62
|
+
readonly primaryKeys: readonly {
|
|
63
|
+
readonly columns: readonly string[];
|
|
64
|
+
}[];
|
|
65
|
+
/** Resolved when the table is read, never earlier: foreign keys may reference tables declared later. */
|
|
66
|
+
readonly foreignKeys: () => readonly CatalogForeignKeyConfig[];
|
|
67
|
+
readonly checks: readonly {
|
|
68
|
+
readonly name: string;
|
|
69
|
+
readonly value: unknown;
|
|
70
|
+
}[];
|
|
71
|
+
}
|
|
72
|
+
/** Everything this module needs to read from the host's ORM; the host builds it from its own library. */
|
|
73
|
+
export interface CatalogIntrospection {
|
|
74
|
+
/** The SQL table name, without resolving the table's foreign keys. */
|
|
75
|
+
tableName(table: unknown): string;
|
|
76
|
+
tableConfig(table: unknown): CatalogTableConfig;
|
|
77
|
+
/** True for a value the ORM declares as a table. */
|
|
78
|
+
isTable(value: unknown): boolean;
|
|
79
|
+
/** True for an ORM raw-SQL value (a default expression, for example). */
|
|
80
|
+
isSql(value: unknown): boolean;
|
|
81
|
+
/** Render an ORM SQL value as Postgres SQL. `indexTerm` renders an expression with parameters inlined and table qualifiers omitted. */
|
|
82
|
+
renderSql(args: {
|
|
83
|
+
value: unknown;
|
|
84
|
+
indexTerm?: boolean;
|
|
85
|
+
}): string;
|
|
86
|
+
}
|
|
87
|
+
export interface CatalogSchemaPorts {
|
|
88
|
+
readonly introspection: CatalogIntrospection;
|
|
89
|
+
/** The host schema's exports by name; `undefined` marks an export that is missing. */
|
|
90
|
+
readonly schema: Readonly<Record<string, unknown>>;
|
|
91
|
+
readonly copyOrder: () => readonly string[];
|
|
92
|
+
readonly derivedNames: ReadonlySet<string>;
|
|
93
|
+
/** Label naming the host schema file in error messages. */
|
|
94
|
+
readonly schemaLabel: string;
|
|
95
|
+
/** Tables carried whole-minus-rows: only the rows matching the source-side `keep` predicate are copied. */
|
|
96
|
+
readonly partiallyExcluded: Readonly<Record<string, {
|
|
97
|
+
readonly keep: string;
|
|
98
|
+
} | undefined>>;
|
|
99
|
+
/** Tables left out entirely, keyed by table name, valued by the disclosed reason. */
|
|
100
|
+
readonly excludedTables: Readonly<Record<string, string>>;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The core tables a copy carries, in foreign-key-safe order, logins and saved keys removed.
|
|
104
|
+
*
|
|
105
|
+
* @complexity O(tables + foreign keys).
|
|
106
|
+
*/
|
|
107
|
+
export declare function collectCatalogTransferTables({ catalog }: {
|
|
108
|
+
catalog: CatalogSchemaPorts;
|
|
109
|
+
}, _optional?: Record<string, never>): TransferTable[];
|
|
110
|
+
/**
|
|
111
|
+
* EVERY table the host schema declares, in the same foreign-key-safe order, nothing left out:
|
|
112
|
+
* the full schema a fresh Postgres database is created with.
|
|
113
|
+
*
|
|
114
|
+
* @complexity O(tables + foreign keys).
|
|
115
|
+
*/
|
|
116
|
+
export declare function collectCatalogSchemaTables({ catalog }: {
|
|
117
|
+
catalog: CatalogSchemaPorts;
|
|
118
|
+
}, _optional?: Record<string, never>): TransferTable[];
|
|
119
|
+
/** Host naming and policy for planning the snapshot of the content database (its schema is the catalog). */
|
|
120
|
+
export interface CatalogSnapshotPolicy {
|
|
121
|
+
/** Migration ledgers stay behind: the target's runner owns its applied history. */
|
|
122
|
+
readonly migrationLedgers: ReadonlySet<string>;
|
|
123
|
+
/** Tables another database owns and copies; declared here too, they are reported left out with `chatReason`. */
|
|
124
|
+
readonly foreignOwnedTables: readonly string[];
|
|
125
|
+
/**
|
|
126
|
+
* Why `foreignOwnedTables` are not copied from this database. A table declared from both files makes
|
|
127
|
+
* `runCopy` refuse the whole copy, so exactly one database is the copy source for each.
|
|
128
|
+
*/
|
|
129
|
+
readonly foreignOwnedReason: string;
|
|
130
|
+
readonly bookkeepingPrefixes: readonly string[];
|
|
131
|
+
readonly secretColumnPattern: RegExp;
|
|
132
|
+
}
|
|
133
|
+
export declare function planCatalogSnapshotTables({ source, catalog, policy }: {
|
|
134
|
+
source: TransferSource;
|
|
135
|
+
catalog: CatalogSchemaPorts;
|
|
136
|
+
policy: CatalogSnapshotPolicy;
|
|
137
|
+
}, _optional?: {}): SnapshotTablePlan;
|
|
138
|
+
/**
|
|
139
|
+
* A database whose raw-SQL schema is introspected separately, never through a host ORM catalog.
|
|
140
|
+
* `ownedTables` are copied first, in that order, then everything else by name.
|
|
141
|
+
*/
|
|
142
|
+
export declare function planIntrospectedSnapshotTables({ source, ownedTables, migrationLedgers, bookkeepingPrefixes }: {
|
|
143
|
+
source: TransferSource;
|
|
144
|
+
ownedTables: readonly string[];
|
|
145
|
+
migrationLedgers: ReadonlySet<string>;
|
|
146
|
+
bookkeepingPrefixes: readonly string[];
|
|
147
|
+
}, _optional?: {}): SnapshotTablePlan;
|
|
148
|
+
//# sourceMappingURL=schema-catalog.d.ts.map
|