@jini-ai/db 0.7.2 → 0.7.3-next.2
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/CHANGELOG.md +1 -1
- package/README.md +33 -17
- package/dist/core/index.d.ts +1 -2
- package/dist/core/index.js +0 -1
- package/dist/core/pg-types.d.ts +4 -1
- package/dist/core/pg-types.js +1 -1
- package/dist/core/row-values.d.ts +0 -30
- package/dist/core/row-values.js +1 -41
- package/dist/data-modules/data-module.d.ts +260 -4
- package/dist/data-modules/data-module.js +105 -83
- package/dist/data-modules/disk-headroom.js +1 -1
- package/dist/data-modules/index.d.ts +2 -2
- package/dist/data-modules/index.js +2 -2
- package/dist/data-modules/migration-journal.js +6 -6
- package/dist/data-modules/migration-recovery.js +2 -2
- package/dist/data-modules/plugin-identity.js +5 -5
- package/dist/data-modules/plugin-store.d.ts +4 -4
- package/dist/data-modules/restore.js +5 -5
- package/dist/data-modules/snapshot.d.ts +1 -1
- package/dist/data-modules/snapshot.js +3 -3
- package/dist/events/change-set-repo.sql.d.ts +70 -0
- package/dist/events/change-set-repo.sql.js +72 -0
- package/dist/events/index.d.ts +4 -0
- package/dist/events/index.js +3 -0
- package/dist/events/outbox-repo.sql.d.ts +91 -0
- package/dist/events/outbox-repo.sql.js +108 -0
- package/dist/events/repo.rows.d.ts +44 -0
- package/dist/events/repo.rows.js +59 -0
- package/dist/gated-mutations/index.d.ts +3 -0
- package/dist/gated-mutations/index.js +2 -0
- package/dist/gated-mutations/repo.rows.d.ts +19 -0
- package/dist/gated-mutations/repo.rows.js +23 -0
- package/dist/gated-mutations/repo.sql.d.ts +67 -0
- package/dist/gated-mutations/repo.sql.js +71 -0
- package/dist/kernel/dialect.d.ts +53 -31
- package/dist/kernel/dialect.js +14 -36
- package/dist/kernel/index.d.ts +2 -2
- package/dist/kernel/index.js +1 -7
- package/dist/kernel/kernel-core.d.ts +7 -3
- package/dist/kernel/kernel-core.js +75 -66
- package/dist/kernel/ops.d.ts +9 -3
- package/dist/kernel/ops.js +2 -2
- package/dist/kernel/owned-transaction.d.ts +7 -7
- package/dist/kernel/owned-transaction.js +2 -2
- package/dist/kernel/pglite/driver.d.ts +2 -2
- package/dist/kernel/pglite/driver.js +18 -18
- package/dist/kernel/pglite/ops.d.ts +8 -3
- package/dist/kernel/pglite/ops.js +5 -5
- package/dist/kernel/port.d.ts +9 -76
- package/dist/kernel/port.js +1 -10
- package/dist/kernel/postgres/driver.d.ts +4 -2
- package/dist/kernel/postgres/driver.js +17 -17
- package/dist/kernel/postgres/ops.d.ts +5 -3
- package/dist/kernel/postgres/ops.js +3 -3
- package/dist/kernel/postgres/pglite-socket.d.ts +2 -2
- package/dist/kernel/postgres/pglite-socket.js +13 -13
- package/dist/kernel/schema-scope.d.ts +5 -2
- package/dist/kernel/schema-scope.js +1 -1
- package/dist/kernel/schema-shape.d.ts +7 -3
- package/dist/kernel/schema-shape.js +2 -2
- package/dist/kernel/session-lock.d.ts +6 -6
- package/dist/kernel/sqlite/driver.d.ts +16 -8
- package/dist/kernel/sqlite/driver.js +38 -38
- package/dist/kernel/sqlite/index.d.ts +1 -0
- package/dist/kernel/sqlite/index.js +1 -0
- package/dist/kernel/sqlite/ops.d.ts +4 -2
- package/dist/kernel/sqlite/ops.js +3 -3
- package/dist/kernel/sqlite/sqlite-only.d.ts +81 -0
- package/dist/kernel/sqlite/sqlite-only.js +58 -0
- package/dist/kernel/store-copy.d.ts +7 -7
- package/dist/kernel/store-copy.js +22 -14
- package/dist/kernel/typegen.d.ts +5 -3
- package/dist/kernel/typegen.js +1 -1
- package/dist/migrate/checksum.d.ts +3 -1
- package/dist/migrate/checksum.js +1 -1
- package/dist/migrate/index.d.ts +1 -1
- package/dist/migrate/legacy-ledger.d.ts +4 -4
- package/dist/migrate/runner.d.ts +12 -7
- package/dist/migrate/runner.js +7 -6
- package/dist/migrate/step.d.ts +3 -28
- package/dist/migrate/step.js +3 -3
- package/dist/owner-store/index.d.ts +47 -1
- package/dist/owner-store/index.js +28 -1
- package/dist/owner-store/migrations/0000_owner_store.d.ts +3 -2
- package/dist/owner-store/migrations/index.d.ts +1 -1
- package/dist/pglite/owner.d.ts +12 -4
- package/dist/pglite/owner.js +33 -27
- package/dist/pglite/socket-server.d.ts +5 -1
- package/dist/pglite/socket-server.js +5 -4
- package/dist/recovery/deep-link.d.ts +3 -3
- package/dist/recovery/degraded-banners.d.ts +3 -3
- package/dist/recovery/degraded-banners.js +3 -3
- package/dist/recovery/disclosure.d.ts +6 -6
- package/dist/recovery/disclosure.js +6 -6
- package/dist/recovery/evaluate-boot-migration-policy.d.ts +5 -5
- package/dist/recovery/evaluate-boot-migration-policy.js +5 -5
- package/dist/recovery/lookup-adapters.d.ts +1 -1
- package/dist/recovery/lookup-adapters.js +1 -1
- package/dist/recovery/migrate-forward-execute.d.ts +1 -1
- package/dist/recovery/migrate-forward-execute.js +5 -5
- package/dist/recovery/migrate-forward-hooks.d.ts +6 -6
- package/dist/recovery/migrate-forward-hooks.js +5 -5
- package/dist/recovery/operation-lock.d.ts +11 -11
- package/dist/recovery/operation-lock.js +3 -3
- package/dist/recovery/reconcile-interrupted-migration.d.ts +7 -7
- package/dist/recovery/reconcile-interrupted-migration.js +7 -7
- package/dist/recovery/recovery-orchestrator.d.ts +21 -21
- package/dist/recovery/recovery-orchestrator.js +9 -9
- package/dist/recovery/restore-hooks.d.ts +8 -8
- package/dist/recovery/restore-hooks.js +7 -7
- package/dist/recovery/restore-point-create.d.ts +3 -3
- package/dist/secrets-vault/repo.sql.d.ts +3 -3
- package/dist/secrets-vault/repo.sql.js +5 -4
- package/dist/settings/index.d.ts +3 -0
- package/dist/settings/index.js +2 -0
- package/dist/settings/repo.rows.d.ts +117 -0
- package/dist/settings/repo.rows.js +106 -0
- package/dist/settings/repo.sql.d.ts +99 -0
- package/dist/settings/repo.sql.js +219 -0
- package/dist/sqlite/checked-client.d.ts +1 -1
- package/dist/sqlite/checked-state.d.ts +3 -3
- package/dist/sqlite/db-ops.d.ts +1 -1
- package/dist/sqlite/db-ops.js +1 -1
- package/dist/sqlite/index.d.ts +1 -3
- package/dist/sqlite/index.js +2 -0
- package/dist/sqlite/inspect.d.ts +2 -2
- package/dist/sqlite/inspect.js +1 -1
- package/dist/sqlite/open.d.ts +1 -2
- package/dist/sqlite/stopped.d.ts +46 -0
- package/dist/sqlite/stopped.js +86 -0
- package/dist/sqlite/transaction.d.ts +2 -2
- package/dist/tools/database-catalog.d.ts +2 -2
- package/dist/tools/database-catalog.js +13 -3
- package/dist/tools/read-tools.js +70 -59
- package/dist/tools/restore-points.d.ts +1 -1
- package/dist/tools/transfer-tools.d.ts +0 -1
- package/dist/tools/transfer-tools.js +5 -4
- package/dist/transfer/copy-engine.js +10 -10
- package/dist/transfer/copy-order.d.ts +47 -0
- package/dist/transfer/copy-order.js +103 -0
- package/dist/transfer/index.d.ts +1 -0
- package/dist/transfer/index.js +1 -0
- package/dist/transfer/internal-ddl.d.ts +28 -6
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +6 -6
- package/dist/transfer/sqlite-source.d.ts +2 -3
- package/dist/transfer/sqlite-source.js +1 -1
- package/dist/verified-origin/index.d.ts +4 -0
- package/dist/verified-origin/index.js +3 -0
- package/dist/verified-origin/register.d.ts +43 -0
- package/dist/verified-origin/register.js +51 -0
- package/dist/verified-origin/repo.rows.d.ts +42 -0
- package/dist/verified-origin/repo.rows.js +47 -0
- package/dist/verified-origin/repo.sql.d.ts +67 -0
- package/dist/verified-origin/repo.sql.js +34 -0
- package/package.json +39 -12
- package/dist/sqlite/restore-types.d.ts +0 -46
- package/dist/sqlite/restore-types.js +0 -2
- package/dist/sqlite/sync-types.d.ts +0 -34
- package/dist/sqlite/sync-types.js +0 -2
- package/dist/sqlite/types.d.ts +0 -37
- package/dist/sqlite/types.js +0 -8
package/dist/tools/read-tools.js
CHANGED
|
@@ -6,6 +6,73 @@ import { DATABASE_READ_PERMISSION, getDatabaseAgentToolCatalog } from "./databas
|
|
|
6
6
|
import { DEFAULT_TIMELINE_PAGE_SIZE, getTimeline, MAX_TIMELINE_PAGE_SIZE } from "./timeline.js";
|
|
7
7
|
import { createRestorePoint as createDatabaseRestorePoint, listRestorePoints } from "./restore-points.js";
|
|
8
8
|
import { registrations } from "./registration.js";
|
|
9
|
+
/** Paged ledger timeline; every filter is an optional string and the limit is capped server-side. */
|
|
10
|
+
function queryTimelineHandler({ ports }) {
|
|
11
|
+
const { isRecord, optionalString } = ports.readers;
|
|
12
|
+
return async (ctx) => {
|
|
13
|
+
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
14
|
+
throw new ToolInputError({ message: "input must be an object" });
|
|
15
|
+
const input = isRecord(ctx.input) ? ctx.input : {};
|
|
16
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database-ledger" });
|
|
17
|
+
return getTimeline({
|
|
18
|
+
ledger: ports.ledger,
|
|
19
|
+
filter: {
|
|
20
|
+
kind: optionalString(input, "kind"),
|
|
21
|
+
outcome: optionalString(input, "outcome"),
|
|
22
|
+
fromDate: optionalString(input, "fromDate"),
|
|
23
|
+
toDate: optionalString(input, "toDate"),
|
|
24
|
+
cursor: optionalString(input, "cursor"),
|
|
25
|
+
// The catalog promises "server-capped at 200, defaults to 50": cap here, and refuse 0/-1/2.5
|
|
26
|
+
// as a ToolInputError the model can read instead of getTimeline's redacted plain Error.
|
|
27
|
+
limit: readToolLimit({ input, max: MAX_TIMELINE_PAGE_SIZE, fallback: DEFAULT_TIMELINE_PAGE_SIZE }),
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** Capture a restore point once the caller holds `backup.create`, then record it in the ledger as a manual one. */
|
|
33
|
+
function createRestorePointHandler({ ports, messages }) {
|
|
34
|
+
const { isRecord, optionalBoolean } = ports.readers;
|
|
35
|
+
return async (ctx) => {
|
|
36
|
+
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
37
|
+
throw new ToolInputError({ message: "input must be an object" });
|
|
38
|
+
const input = isRecord(ctx.input) ? ctx.input : {};
|
|
39
|
+
const costAck = optionalBoolean(input, "costAck");
|
|
40
|
+
// `createRestorePoint` (restore-points.ts) has no authorize() call of its own — the real HTTP
|
|
41
|
+
// route (a host module) authorizes inline before calling it, so
|
|
42
|
+
// this handler does the identical inline check.
|
|
43
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: "backup.create", entityType: "restore-point" });
|
|
44
|
+
const capabilities = await ports.dbOps.getCapabilities();
|
|
45
|
+
let captured;
|
|
46
|
+
ctx.signal.throwIfAborted();
|
|
47
|
+
const summary = await createDatabaseRestorePoint({
|
|
48
|
+
costClass: capabilities.restorePoint.costClass,
|
|
49
|
+
kind: capabilities.restorePoint.kind,
|
|
50
|
+
costAck: costAck ?? false,
|
|
51
|
+
capture: async () => {
|
|
52
|
+
captured = await ports.dbOps.captureRestorePoint({ scopeId: ports.workspaceId });
|
|
53
|
+
return captured;
|
|
54
|
+
},
|
|
55
|
+
}, { messages });
|
|
56
|
+
// `createDatabaseRestorePoint` resolves only after awaiting `capture()` (restore-points.ts), so
|
|
57
|
+
// `captured` is always set here; the former `captured?.… ?? null` fallbacks could never apply.
|
|
58
|
+
const { watermarkAtCapture, artifactRef } = captured;
|
|
59
|
+
await ports.restorePoints.save({
|
|
60
|
+
restorePointId: summary.id,
|
|
61
|
+
idempotencyKey: ports.idGen.newId(),
|
|
62
|
+
// Always 'manual' — an agent call is never the system's own pre-migration/template-upgrade
|
|
63
|
+
// auto-snapshot, regardless of what a caller might ask for, so provenance in the ledger can
|
|
64
|
+
// never be mislabeled (see `features/database/agent-tools.ts`'s own schema comment).
|
|
65
|
+
trigger: "manual",
|
|
66
|
+
createdAt: nowIso({ clock: ports.clock }),
|
|
67
|
+
createdBy: ctx.principal.id,
|
|
68
|
+
costClass: summary.costClass,
|
|
69
|
+
kind: summary.kind,
|
|
70
|
+
watermarkAtCapture,
|
|
71
|
+
artifactRef,
|
|
72
|
+
});
|
|
73
|
+
return { restorePoint: summary };
|
|
74
|
+
};
|
|
75
|
+
}
|
|
9
76
|
/**
|
|
10
77
|
* Binds six authorized read/restore-point handlers and their host-facing catalog copy.
|
|
11
78
|
* @param ports Host effects; construction performs no I/O and retains the ports by reference.
|
|
@@ -15,27 +82,9 @@ import { registrations } from "./registration.js";
|
|
|
15
82
|
*/
|
|
16
83
|
export function createDatabaseReadTools(ports, _optional = {}) {
|
|
17
84
|
const messages = _optional.messages ?? defaultDbMessages;
|
|
18
|
-
const { noInput: requireNoInput
|
|
85
|
+
const { noInput: requireNoInput } = ports.readers;
|
|
19
86
|
const handlers = {
|
|
20
|
-
database_query_timeline:
|
|
21
|
-
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
22
|
-
throw new ToolInputError({ message: "input must be an object" });
|
|
23
|
-
const input = isRecord(ctx.input) ? ctx.input : {};
|
|
24
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database-ledger" });
|
|
25
|
-
return getTimeline({
|
|
26
|
-
ledger: ports.ledger,
|
|
27
|
-
filter: {
|
|
28
|
-
kind: optionalString(input, "kind"),
|
|
29
|
-
outcome: optionalString(input, "outcome"),
|
|
30
|
-
fromDate: optionalString(input, "fromDate"),
|
|
31
|
-
toDate: optionalString(input, "toDate"),
|
|
32
|
-
cursor: optionalString(input, "cursor"),
|
|
33
|
-
// The catalog promises "server-capped at 200, defaults to 50": cap here, and refuse 0/-1/2.5
|
|
34
|
-
// as a ToolInputError the model can read instead of getTimeline's redacted plain Error.
|
|
35
|
-
limit: readToolLimit({ input, max: MAX_TIMELINE_PAGE_SIZE, fallback: DEFAULT_TIMELINE_PAGE_SIZE }),
|
|
36
|
-
},
|
|
37
|
-
});
|
|
38
|
-
},
|
|
87
|
+
database_query_timeline: queryTimelineHandler({ ports }),
|
|
39
88
|
database_list_restore_points: async (ctx) => {
|
|
40
89
|
requireNoInput(ctx.input);
|
|
41
90
|
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "restore-point" });
|
|
@@ -56,45 +105,7 @@ export function createDatabaseReadTools(ports, _optional = {}) {
|
|
|
56
105
|
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database" });
|
|
57
106
|
return ports.introspection.listPendingMigrations();
|
|
58
107
|
},
|
|
59
|
-
backup_create_restore_point:
|
|
60
|
-
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
61
|
-
throw new ToolInputError({ message: "input must be an object" });
|
|
62
|
-
const input = isRecord(ctx.input) ? ctx.input : {};
|
|
63
|
-
const costAck = optionalBoolean(input, "costAck");
|
|
64
|
-
// `createRestorePoint` (restore-points.ts) has no authorize() call of its own — the real HTTP
|
|
65
|
-
// route (`routes/admin/database/restore-points.ts`) authorizes inline before calling it, so
|
|
66
|
-
// this handler does the identical inline check.
|
|
67
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission: "backup.create", entityType: "restore-point" });
|
|
68
|
-
const capabilities = await ports.dbOps.getCapabilities();
|
|
69
|
-
let captured;
|
|
70
|
-
const summary = await createDatabaseRestorePoint({
|
|
71
|
-
costClass: capabilities.restorePoint.costClass,
|
|
72
|
-
kind: capabilities.restorePoint.kind,
|
|
73
|
-
costAck: costAck ?? false,
|
|
74
|
-
capture: async () => {
|
|
75
|
-
captured = await ports.dbOps.captureRestorePoint({ scopeId: ports.workspaceId });
|
|
76
|
-
return captured;
|
|
77
|
-
},
|
|
78
|
-
}, { messages });
|
|
79
|
-
// `createDatabaseRestorePoint` resolves only after awaiting `capture()` (restore-points.ts), so
|
|
80
|
-
// `captured` is always set here; the former `captured?.… ?? null` fallbacks could never apply.
|
|
81
|
-
const { watermarkAtCapture, artifactRef } = captured;
|
|
82
|
-
await ports.restorePoints.save({
|
|
83
|
-
restorePointId: summary.id,
|
|
84
|
-
idempotencyKey: ports.idGen.newId(),
|
|
85
|
-
// Always 'manual' — an agent call is never the system's own pre-migration/template-upgrade
|
|
86
|
-
// auto-snapshot, regardless of what a caller might ask for, so provenance in the ledger can
|
|
87
|
-
// never be mislabeled (see `features/database/agent-tools.ts`'s own schema comment).
|
|
88
|
-
trigger: "manual",
|
|
89
|
-
createdAt: nowIso({ clock: ports.clock }),
|
|
90
|
-
createdBy: ctx.principal.id,
|
|
91
|
-
costClass: summary.costClass,
|
|
92
|
-
kind: summary.kind,
|
|
93
|
-
watermarkAtCapture,
|
|
94
|
-
artifactRef,
|
|
95
|
-
});
|
|
96
|
-
return { restorePoint: summary };
|
|
97
|
-
},
|
|
108
|
+
backup_create_restore_point: createRestorePointHandler({ ports, messages }),
|
|
98
109
|
};
|
|
99
110
|
// Classified from the lifted handlers: five repository reads and one capture + persisted record.
|
|
100
111
|
const risks = new Map(Object.keys(handlers).map(id => [id, id === "backup_create_restore_point" ? "mutates-durable-state" : "none"]));
|
|
@@ -79,7 +79,7 @@ export interface RestorePointListPort {
|
|
|
79
79
|
list(): Promise<RestorePointRecord[]>;
|
|
80
80
|
}
|
|
81
81
|
/** Widens `recovery/restore-points.ts`'s `CreateRestorePointRepoPort.save()` shape with the
|
|
82
|
-
* optional descriptive fields
|
|
82
|
+
* optional descriptive fields a host module's create route persists
|
|
83
83
|
* (the real `SqliteRestorePointsRepo.save()` already accepts all of these; this port just names
|
|
84
84
|
* the subset a route composing `database/restore-points.ts`'s `createRestorePoint` needs). Declared
|
|
85
85
|
* independently rather than importing/extending `CreateRestorePointRepoPort` so this file keeps
|
|
@@ -64,7 +64,6 @@ export interface DatabaseTransferToolPorts {
|
|
|
64
64
|
}[];
|
|
65
65
|
captureChatSnapshot(): Promise<Buffer>;
|
|
66
66
|
failureLog(line: string): void;
|
|
67
|
-
describeError(error: unknown): string;
|
|
68
67
|
readonly schemaMismatchGuidance: string;
|
|
69
68
|
readers: Pick<InputReaders, "inputRecord" | "string">;
|
|
70
69
|
surfaces: TransferSurfacePorts;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFile, unlink } from "node:fs/promises";
|
|
2
|
-
import { createApprovalHandler, ToolInputError } from "@jini-ai/core";
|
|
2
|
+
import { createApprovalHandler, describeErrorForLog, ToolInputError } from "@jini-ai/core";
|
|
3
3
|
import { countSourceRows, inspectTarget, runCopy, planTransfer, SourceSchemaMismatchError, IncompleteTransferPlanError, InvalidConnectionStringError, LEFT_OUT_REASON } from "../transfer/index.js";
|
|
4
4
|
import { DOMAIN, PLAN_TOOL_ID, STATUS_TOOL_ID, RUN_PERMISSION, SNAPSHOT_SCOPE_ID, MIN_SERVER_VERSION_NUM, getDatabaseTransferAgentToolCatalog } from "./transfer-catalog.js";
|
|
5
5
|
import { defaultDbMessages } from "../core/messages.js";
|
|
@@ -32,7 +32,7 @@ async function captureSnapshot(deps) {
|
|
|
32
32
|
({ artifactRef } = await deps.ports.dbOps.captureRestorePoint({ scopeId: SNAPSHOT_SCOPE_ID }));
|
|
33
33
|
}
|
|
34
34
|
catch (err) {
|
|
35
|
-
log(deps, `snapshot failed: ${
|
|
35
|
+
log(deps, `snapshot failed: ${describeErrorForLog({ err })}`);
|
|
36
36
|
return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database could not be snapshotted; nothing was copied" };
|
|
37
37
|
}
|
|
38
38
|
let bytes;
|
|
@@ -40,7 +40,7 @@ async function captureSnapshot(deps) {
|
|
|
40
40
|
bytes = await deps.files.readFile(artifactRef);
|
|
41
41
|
}
|
|
42
42
|
catch (err) {
|
|
43
|
-
log(deps, `snapshot read failed: ${
|
|
43
|
+
log(deps, `snapshot read failed: ${describeErrorForLog({ err })}`);
|
|
44
44
|
return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database snapshot could not be read; nothing was copied" };
|
|
45
45
|
}
|
|
46
46
|
finally {
|
|
@@ -161,12 +161,13 @@ async function handlePlan(deps, ctx) {
|
|
|
161
161
|
chatSnapshot = await deps.ports.captureChatSnapshot();
|
|
162
162
|
}
|
|
163
163
|
catch (error) {
|
|
164
|
-
log(deps, `chat snapshot failed: ${
|
|
164
|
+
log(deps, `chat snapshot failed: ${describeErrorForLog({ err: error })}`);
|
|
165
165
|
return { planned: false, code: "DATABASE_SNAPSHOT_FAILED", message: "the chat database could not be snapshotted; nothing was copied" };
|
|
166
166
|
}
|
|
167
167
|
const counted = countSnapshot(deps, snapshot.bytes, chatSnapshot);
|
|
168
168
|
if (!("ok" in counted))
|
|
169
169
|
return { planned: false, ...counted };
|
|
170
|
+
ctx.signal.throwIfAborted();
|
|
170
171
|
const plan = deps.ports.plans.save({
|
|
171
172
|
principalId: ctx.principal.id,
|
|
172
173
|
workspaceId: deps.ports.workspaceId,
|
|
@@ -83,7 +83,7 @@ async function readMarkers(target, TRANSFER_MARKER_TABLE) {
|
|
|
83
83
|
for (const [schema] of listed.value) {
|
|
84
84
|
if (schema === undefined)
|
|
85
85
|
continue;
|
|
86
|
-
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`);
|
|
86
|
+
const rows = await target.query(`SELECT site, snapshot_at, (SELECT count(DISTINCT site) FROM ${qualified({ schema, table: TRANSFER_MARKER_TABLE })}) > 1 FROM ${qualified({ schema, table: TRANSFER_MARKER_TABLE })} ORDER BY copied_at DESC LIMIT 1`);
|
|
87
87
|
// A table merely NAMED like the marker (wrong columns) is someone else's; it never claims a site.
|
|
88
88
|
const [site, snapshotAt, mixed] = rows.ok ? (rows.value[0] ?? []) : [];
|
|
89
89
|
markers.push({ schema, copy: site !== undefined && snapshotAt !== undefined ? { site, snapshotAt } : null, mixed: mixed === "t" });
|
|
@@ -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.name)} (${names.map(quoteIdent).join(", ")}) FROM STDIN;\n`;
|
|
134
|
+
yield `COPY ${qualified({ schema, table: table.name })} (${names.map(quoteIdent).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";
|
|
@@ -159,15 +159,15 @@ function guardSql(schema, site, TRANSFER_MARKER_TABLE, sqlTag) {
|
|
|
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.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(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
167
|
const UNVALIDATED_TABLE = naming.unvalidatedTable.split(".").map(quoteIdent).join(".");
|
|
168
168
|
const tableCounts = JSON.stringify(Object.fromEntries(counts.map(({ table, rows }) => [table.name, rows])));
|
|
169
|
-
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` +
|
|
170
|
-
`INSERT INTO ${qualified(schema, TRANSFER_MARKER_TABLE)} (site, snapshot_at, table_counts, unvalidated) VALUES (${quoteLiteral(marker.site)}, ${quoteLiteral(marker.snapshotAt)}, ${quoteLiteral(tableCounts)}::jsonb, ` +
|
|
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, ` +
|
|
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) {
|
|
@@ -179,17 +179,17 @@ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
|
|
|
179
179
|
yield `DROP SCHEMA IF EXISTS ${quoteIdent(schema)} CASCADE;\n`;
|
|
180
180
|
yield `CREATE SCHEMA ${quoteIdent(schema)};\n`;
|
|
181
181
|
for (const { table } of counts)
|
|
182
|
-
yield createTableSql(schema, table);
|
|
182
|
+
yield createTableSql({ schema, table });
|
|
183
183
|
for (const { source, counts: sourceCounts } of sources) {
|
|
184
184
|
for (const { table } of sourceCounts)
|
|
185
185
|
yield* copyTableData(source, schema, table);
|
|
186
186
|
}
|
|
187
187
|
yield countCheckSql(schema, counts, sqlTag);
|
|
188
188
|
for (const { table } of counts)
|
|
189
|
-
yield reseedIdentitySql(schema, table, sqlTag);
|
|
189
|
+
yield reseedIdentitySql({ schema, table }, { sqlTag });
|
|
190
190
|
for (const { table } of counts)
|
|
191
|
-
yield indexSql(schema, table);
|
|
192
|
-
yield constraintSql(schema, counts.map(({ table }) => table), naming.unvalidatedTable, sqlTag);
|
|
191
|
+
yield indexSql({ schema, table });
|
|
192
|
+
yield constraintSql({ schema, tables: counts.map(({ table }) => table), unvalidatedTable: naming.unvalidatedTable }, { sqlTag });
|
|
193
193
|
yield markerSql(schema, marker, counts, naming);
|
|
194
194
|
yield "COMMIT;\n";
|
|
195
195
|
}
|
|
@@ -198,7 +198,7 @@ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
|
|
|
198
198
|
async function readUnvalidated({ target, schema, markerTable }, _options = {}) {
|
|
199
199
|
const unreadable = { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
|
|
200
200
|
try {
|
|
201
|
-
const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, markerTable)} LIMIT 1`);
|
|
201
|
+
const read = await target.query(`SELECT unvalidated FROM ${qualified({ schema, table: markerTable })} LIMIT 1`);
|
|
202
202
|
const cell = read.ok ? read.value[0]?.[0] : undefined;
|
|
203
203
|
if (cell === undefined)
|
|
204
204
|
return unreadable;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Table copy ordering for a bulk database transfer: a deterministic topological order over
|
|
3
|
+
* caller-supplied table names and foreign-key dependencies, so a copier does not have to invent one.
|
|
4
|
+
* Plain metadata in, plain names out; the host derives the names and edges from its own schema.
|
|
5
|
+
*/
|
|
6
|
+
/** One foreign-key dependency between two tables. An "export name" is the caller's identifier for a
|
|
7
|
+
* table (any unique string); extra fields on a caller's own edge type are ignored. */
|
|
8
|
+
export interface TableCopyDependency {
|
|
9
|
+
/** The table that DECLARES the foreign key (must be copied AFTER `toExportName`). */
|
|
10
|
+
readonly fromExportName: string;
|
|
11
|
+
/** The table the foreign key POINTS AT (must be copied BEFORE `fromExportName`). */
|
|
12
|
+
readonly toExportName: string;
|
|
13
|
+
/** `true` when a table's own foreign key targets itself (a parent/child hierarchy stored in one
|
|
14
|
+
* table). See `topologicalTableCopyOrder`'s doc for why this is excluded from the returned order
|
|
15
|
+
* rather than resolved by it. */
|
|
16
|
+
readonly selfReferencing: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Thrown by `topologicalTableCopyOrder` when the FK graph (excluding self-referencing edges) has a
|
|
19
|
+
* cycle across two or more DIFFERENT tables — no single copy order can then satisfy every constraint,
|
|
20
|
+
* and a copier must break the cycle explicitly (e.g. a deferred/dropped-and-revalidated constraint on
|
|
21
|
+
* one edge of it) rather than have this function guess which edge to ignore. */
|
|
22
|
+
export declare class TableCopyOrderCycleError extends Error {
|
|
23
|
+
readonly stuckExportNames: readonly string[];
|
|
24
|
+
constructor(stuckExportNames: readonly string[]);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Kahn's-algorithm topological sort over an FK graph: table A is ordered before table B whenever B
|
|
28
|
+
* declares a foreign key pointing at A ("referenced tables first"). Pure and synchronous over its
|
|
29
|
+
* inputs — no import-time computation, no module-level constant — so a genuine cycle in a host schema
|
|
30
|
+
* throws only for whichever caller actually asks for the order, never for every importer at import
|
|
31
|
+
* time. Hosts keep their schema-derived wrapper next to their schema; this function stays testable
|
|
32
|
+
* against synthetic edges so a cycle can be proven to throw without a real schema containing one.
|
|
33
|
+
*
|
|
34
|
+
* Self-referencing edges (`edge.selfReferencing`) are excluded from the ordering graph — a table
|
|
35
|
+
* cannot be sequenced "before itself" — but that exclusion does NOT mean a self-referencing table
|
|
36
|
+
* needs no special handling. It still appears exactly once in the returned order, and this function
|
|
37
|
+
* says nothing about the ROW order WITHIN that one table's own copy: a copier must still insert that
|
|
38
|
+
* table's rows in an order that satisfies its own FK (typically: parents before children, e.g. by
|
|
39
|
+
* sorting on the referenced column), or defer/drop-and-revalidate just that one constraint for the
|
|
40
|
+
* duration of that table's copy. That per-table obligation is real and is not discharged by this
|
|
41
|
+
* function returning a table-level order at all.
|
|
42
|
+
*/
|
|
43
|
+
export declare function topologicalTableCopyOrder({ allExportNames, edges }: {
|
|
44
|
+
readonly allExportNames: readonly string[];
|
|
45
|
+
readonly edges: readonly TableCopyDependency[];
|
|
46
|
+
}, _optional?: Record<string, never>): string[];
|
|
47
|
+
//# sourceMappingURL=copy-order.d.ts.map
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Table copy ordering for a bulk database transfer: a deterministic topological order over
|
|
3
|
+
* caller-supplied table names and foreign-key dependencies, so a copier does not have to invent one.
|
|
4
|
+
* Plain metadata in, plain names out; the host derives the names and edges from its own schema.
|
|
5
|
+
*/
|
|
6
|
+
/** Thrown by `topologicalTableCopyOrder` when the FK graph (excluding self-referencing edges) has a
|
|
7
|
+
* cycle across two or more DIFFERENT tables — no single copy order can then satisfy every constraint,
|
|
8
|
+
* and a copier must break the cycle explicitly (e.g. a deferred/dropped-and-revalidated constraint on
|
|
9
|
+
* one edge of it) rather than have this function guess which edge to ignore. */
|
|
10
|
+
export class TableCopyOrderCycleError extends Error {
|
|
11
|
+
stuckExportNames;
|
|
12
|
+
constructor(stuckExportNames) {
|
|
13
|
+
super(`foreign-key graph has a cycle across tables ${stuckExportNames.join(", ")} — no single copy order can ` +
|
|
14
|
+
`satisfy every constraint. This is a schema fact a copier must resolve explicitly, not something this ` +
|
|
15
|
+
`function can order its way out of.`);
|
|
16
|
+
this.stuckExportNames = stuckExportNames;
|
|
17
|
+
this.name = "TableCopyOrderCycleError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Builds `topologicalTableCopyOrder`'s Kahn's-algorithm inputs from the FK edges: for each
|
|
22
|
+
* non-self-referencing edge, records that `toExportName` has `fromExportName` as a dependent,
|
|
23
|
+
* incrementing `fromExportName`'s in-degree once per distinct table it depends on (a table with
|
|
24
|
+
* multiple FKs to the SAME target does not inflate its in-degree past 1 for that target — it only
|
|
25
|
+
* needs that target copied before it once, not once per FK column pointing there).
|
|
26
|
+
*/
|
|
27
|
+
function buildCopyOrderGraph(allExportNames, edges) {
|
|
28
|
+
const dependents = new Map();
|
|
29
|
+
const inDegree = new Map(allExportNames.map((name) => [name, 0]));
|
|
30
|
+
for (const edge of edges) {
|
|
31
|
+
if (edge.selfReferencing)
|
|
32
|
+
continue;
|
|
33
|
+
if (!inDegree.has(edge.fromExportName) || !inDegree.has(edge.toExportName)) {
|
|
34
|
+
throw new Error(`edge references "${edge.fromExportName}" -> "${edge.toExportName}", but allExportNames does not list ` +
|
|
35
|
+
`both — topologicalTableCopyOrder() requires every edge endpoint to be one of the named tables.`);
|
|
36
|
+
}
|
|
37
|
+
let targets = dependents.get(edge.toExportName);
|
|
38
|
+
if (!targets) {
|
|
39
|
+
targets = new Set();
|
|
40
|
+
dependents.set(edge.toExportName, targets);
|
|
41
|
+
}
|
|
42
|
+
if (!targets.has(edge.fromExportName)) {
|
|
43
|
+
targets.add(edge.fromExportName);
|
|
44
|
+
inDegree.set(edge.fromExportName, (inDegree.get(edge.fromExportName) ?? 0) + 1);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { dependents, inDegree };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Inserts `name` into `ready` (kept sorted ascending) at the first position whose current entry
|
|
51
|
+
* sorts after it — re-sorting on insert rather than sorting once at the end keeps the "process
|
|
52
|
+
* alphabetically among currently-ready tables" tie-break correct at every step of
|
|
53
|
+
* `topologicalTableCopyOrder`'s loop below, not just among the initial zero-in-degree set. Mutates
|
|
54
|
+
* `ready` in place.
|
|
55
|
+
*/
|
|
56
|
+
function insertIntoReadyQueue({ ready, name }, _optional = {}) {
|
|
57
|
+
const insertAt = ready.findIndex((n) => n > name);
|
|
58
|
+
if (insertAt === -1)
|
|
59
|
+
ready.push(name);
|
|
60
|
+
else
|
|
61
|
+
ready.splice(insertAt, 0, name);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Kahn's-algorithm topological sort over an FK graph: table A is ordered before table B whenever B
|
|
65
|
+
* declares a foreign key pointing at A ("referenced tables first"). Pure and synchronous over its
|
|
66
|
+
* inputs — no import-time computation, no module-level constant — so a genuine cycle in a host schema
|
|
67
|
+
* throws only for whichever caller actually asks for the order, never for every importer at import
|
|
68
|
+
* time. Hosts keep their schema-derived wrapper next to their schema; this function stays testable
|
|
69
|
+
* against synthetic edges so a cycle can be proven to throw without a real schema containing one.
|
|
70
|
+
*
|
|
71
|
+
* Self-referencing edges (`edge.selfReferencing`) are excluded from the ordering graph — a table
|
|
72
|
+
* cannot be sequenced "before itself" — but that exclusion does NOT mean a self-referencing table
|
|
73
|
+
* needs no special handling. It still appears exactly once in the returned order, and this function
|
|
74
|
+
* says nothing about the ROW order WITHIN that one table's own copy: a copier must still insert that
|
|
75
|
+
* table's rows in an order that satisfies its own FK (typically: parents before children, e.g. by
|
|
76
|
+
* sorting on the referenced column), or defer/drop-and-revalidate just that one constraint for the
|
|
77
|
+
* duration of that table's copy. That per-table obligation is real and is not discharged by this
|
|
78
|
+
* function returning a table-level order at all.
|
|
79
|
+
*/
|
|
80
|
+
export function topologicalTableCopyOrder({ allExportNames, edges }, _optional = {}) {
|
|
81
|
+
const { dependents, inDegree } = buildCopyOrderGraph(allExportNames, edges);
|
|
82
|
+
const ready = [...allExportNames].filter((name) => inDegree.get(name) === 0).sort();
|
|
83
|
+
const order = [];
|
|
84
|
+
const remaining = new Map(inDegree);
|
|
85
|
+
while (ready.length) {
|
|
86
|
+
const next = ready.shift(); // already sorted; shifting keeps output deterministic
|
|
87
|
+
if (next === undefined)
|
|
88
|
+
throw new Error("table copy order has an empty ready queue");
|
|
89
|
+
order.push(next);
|
|
90
|
+
for (const dependent of dependents.get(next) ?? []) {
|
|
91
|
+
const updated = (remaining.get(dependent) ?? 0) - 1;
|
|
92
|
+
remaining.set(dependent, updated);
|
|
93
|
+
if (updated === 0)
|
|
94
|
+
insertIntoReadyQueue({ ready, name: dependent });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (order.length !== allExportNames.length) {
|
|
98
|
+
const stuck = allExportNames.filter((name) => !order.includes(name));
|
|
99
|
+
throw new TableCopyOrderCycleError(stuck);
|
|
100
|
+
}
|
|
101
|
+
return order;
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=copy-order.js.map
|
package/dist/transfer/index.d.ts
CHANGED
package/dist/transfer/index.js
CHANGED
|
@@ -2,25 +2,47 @@ import type { TransferTable } from "./types.js";
|
|
|
2
2
|
/** A session-local table listing constraints left unvalidated; dropped at commit. */
|
|
3
3
|
export declare function quoteIdent(name: string): string;
|
|
4
4
|
export declare function quoteLiteral(value: string): string;
|
|
5
|
-
export declare function qualified(schema
|
|
5
|
+
export declare function qualified({ schema, table }: {
|
|
6
|
+
schema: string;
|
|
7
|
+
table: string;
|
|
8
|
+
}, _optional?: Record<string, never>): string;
|
|
6
9
|
/**
|
|
7
10
|
* The name itself when it fits in 63 bytes; otherwise its first bytes plus 8 hex characters of its
|
|
8
11
|
* SHA-256, so two long names never collapse into one (Postgres would silently cut both to the same
|
|
9
12
|
* prefix).
|
|
10
13
|
*/
|
|
11
|
-
export declare function fitIdentifier(name
|
|
12
|
-
|
|
14
|
+
export declare function fitIdentifier({ name }: {
|
|
15
|
+
name: string;
|
|
16
|
+
}, _optional?: Record<string, never>): string;
|
|
17
|
+
export declare function createTableSql({ schema, table }: {
|
|
18
|
+
schema: string;
|
|
19
|
+
table: TransferTable;
|
|
20
|
+
}, _optional?: Record<string, never>): string;
|
|
13
21
|
/** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
|
|
14
|
-
export declare function reseedIdentitySql(schema
|
|
22
|
+
export declare function reseedIdentitySql({ schema, table }: {
|
|
23
|
+
schema: string;
|
|
24
|
+
table: TransferTable;
|
|
25
|
+
}, { sqlTag }?: {
|
|
26
|
+
sqlTag?: string | undefined;
|
|
27
|
+
}): string;
|
|
15
28
|
/** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
|
|
16
29
|
* @complexity O(index columns plus predicate bytes); emits SQL without executing it.
|
|
17
30
|
*/
|
|
18
|
-
export declare function indexSql(schema
|
|
31
|
+
export declare function indexSql({ schema, table }: {
|
|
32
|
+
schema: string;
|
|
33
|
+
table: TransferTable;
|
|
34
|
+
}, _optional?: Record<string, never>): string;
|
|
19
35
|
/**
|
|
20
36
|
* Every CHECK and foreign key, added NOT VALID and then validated; a failed validation is recorded
|
|
21
37
|
* in {@link UNVALIDATED_TABLE} as `table.constraint` and the constraint stays in place, unvalidated.
|
|
22
38
|
*
|
|
23
39
|
* @complexity O(constraints) statements.
|
|
24
40
|
*/
|
|
25
|
-
export declare function constraintSql(schema
|
|
41
|
+
export declare function constraintSql({ schema, tables, unvalidatedTable }: {
|
|
42
|
+
schema: string;
|
|
43
|
+
tables: readonly TransferTable[];
|
|
44
|
+
unvalidatedTable: string;
|
|
45
|
+
}, { sqlTag }?: {
|
|
46
|
+
sqlTag?: string | undefined;
|
|
47
|
+
}): string;
|
|
26
48
|
//# sourceMappingURL=internal-ddl.d.ts.map
|
|
@@ -25,7 +25,7 @@ export function quoteIdent(name) {
|
|
|
25
25
|
export function quoteLiteral(value) {
|
|
26
26
|
return `'${value.replace(/'/g, "''")}'`;
|
|
27
27
|
}
|
|
28
|
-
export function qualified(schema, table) {
|
|
28
|
+
export function qualified({ schema, table }, _optional = {}) {
|
|
29
29
|
return `${quoteIdent(schema)}.${quoteIdent(table)}`;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -33,7 +33,7 @@ export function qualified(schema, table) {
|
|
|
33
33
|
* SHA-256, so two long names never collapse into one (Postgres would silently cut both to the same
|
|
34
34
|
* prefix).
|
|
35
35
|
*/
|
|
36
|
-
export function fitIdentifier(name) {
|
|
36
|
+
export function fitIdentifier({ name }, _optional = {}) {
|
|
37
37
|
if (Buffer.byteLength(name) <= MAX_IDENTIFIER_BYTES)
|
|
38
38
|
return name;
|
|
39
39
|
const hash = createHash("sha256").update(name).digest("hex").slice(0, 8);
|
|
@@ -47,30 +47,30 @@ function columnSql(column) {
|
|
|
47
47
|
const fallback = column.default === undefined ? "" : ` DEFAULT ${column.default}`;
|
|
48
48
|
return `${quoteIdent(column.name)} ${column.sqlType}${identity}${fallback}${column.notNull ? " NOT NULL" : ""}`;
|
|
49
49
|
}
|
|
50
|
-
export function createTableSql(schema, table) {
|
|
50
|
+
export function createTableSql({ schema, table }, _optional = {}) {
|
|
51
51
|
const columns = table.columns.map(columnSql);
|
|
52
52
|
if (table.primaryKey.length > 0)
|
|
53
53
|
columns.push(`PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(", ")})`);
|
|
54
|
-
return `CREATE TABLE ${qualified(schema, table.name)} (${columns.join(", ")});\n`;
|
|
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. */
|
|
57
|
-
export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
|
|
57
|
+
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.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`;
|
|
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`;
|
|
63
63
|
})
|
|
64
64
|
.join("");
|
|
65
65
|
}
|
|
66
66
|
/** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
|
|
67
67
|
* @complexity O(index columns plus predicate bytes); emits SQL without executing it.
|
|
68
68
|
*/
|
|
69
|
-
export function indexSql(schema, table) {
|
|
69
|
+
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(index.name))} ON ${qualified(schema, table.name)} (${(index.expressions ?? index.columns.map(quoteIdent)).join(", ")})${where};\n`;
|
|
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`;
|
|
74
74
|
})
|
|
75
75
|
.join("");
|
|
76
76
|
}
|
|
@@ -95,14 +95,14 @@ function parentColumns(fk, byName) {
|
|
|
95
95
|
return unique ? columns : null;
|
|
96
96
|
}
|
|
97
97
|
function constraintsOf(schema, table, byName) {
|
|
98
|
-
const checks = table.checks.map((check) => ({ table: table.name, name: fitIdentifier(check.name), add: `CHECK (${check.sql})` }));
|
|
98
|
+
const checks = table.checks.map((check) => ({ table: table.name, name: fitIdentifier({ name: check.name }), add: `CHECK (${check.sql})` }));
|
|
99
99
|
const keys = table.foreignKeys.flatMap((fk) => {
|
|
100
100
|
const parent = parentColumns(fk, byName);
|
|
101
101
|
if (parent === null)
|
|
102
102
|
return [];
|
|
103
103
|
const columns = fk.columns.map(quoteIdent).join(", ");
|
|
104
|
-
const references = `${qualified(schema, fk.foreignTable)} (${parent.map(quoteIdent).join(", ")})`;
|
|
105
|
-
return [{ table: table.name, name: fitIdentifier(fk.name), add: `FOREIGN KEY (${columns}) REFERENCES ${references} ON DELETE ${action(fk.onDelete)} ON UPDATE ${action(fk.onUpdate)}` }];
|
|
104
|
+
const references = `${qualified({ schema, table: fk.foreignTable })} (${parent.map(quoteIdent).join(", ")})`;
|
|
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];
|
|
108
108
|
}
|
|
@@ -112,12 +112,12 @@ function constraintsOf(schema, table, byName) {
|
|
|
112
112
|
*
|
|
113
113
|
* @complexity O(constraints) statements.
|
|
114
114
|
*/
|
|
115
|
-
export function constraintSql(schema, tables, unvalidatedTable, sqlTag = "transfer") {
|
|
115
|
+
export function constraintSql({ schema, tables, unvalidatedTable }, { sqlTag = "transfer" } = {}) {
|
|
116
116
|
const UNVALIDATED_TABLE = unvalidatedTable.split(".").map(quoteIdent).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` +
|
|
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
121
|
` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral(table + "." + name)}); END;\n`);
|
|
122
122
|
return (`CREATE TEMP TABLE ${quoteIdent(unvalidatedTable.split(".").at(-1))} (name text NOT NULL) ON COMMIT DROP;\n` +
|
|
123
123
|
adds.join("") +
|
|
@@ -7,10 +7,10 @@ const tag = (sqlTag = "transfer") => {
|
|
|
7
7
|
};
|
|
8
8
|
export function quoteIdent({ name }, _optional = {}) { return ddl.quoteIdent(name); }
|
|
9
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)); }
|
|
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 }, { sqlTag: tag(optional.sqlTag) }); }
|
|
15
|
+
export function constraintSql({ schema, tables, unvalidatedTable }, optional = {}) { return ddl.constraintSql({ schema, tables, unvalidatedTable }, { sqlTag: tag(optional.sqlTag) }); }
|
|
16
16
|
//# sourceMappingURL=postgres-ddl.js.map
|
|
@@ -81,9 +81,8 @@ export declare function inMemoryReadableBytes({ bytes }: {
|
|
|
81
81
|
bytes: Buffer;
|
|
82
82
|
}, _options?: Record<string, never>): Buffer;
|
|
83
83
|
/** @complexity O(database size) to deserialize the snapshot. */
|
|
84
|
-
export declare function openSqliteSnapshotSource({ bytes }: {
|
|
84
|
+
export declare function openSqliteSnapshotSource({ bytes, open }: {
|
|
85
85
|
bytes: Buffer;
|
|
86
|
-
}, { open }: {
|
|
87
86
|
open: SnapshotOpener;
|
|
88
|
-
}): TransferSource;
|
|
87
|
+
}, _optional?: Record<string, never>): TransferSource;
|
|
89
88
|
//# sourceMappingURL=sqlite-source.d.ts.map
|
|
@@ -59,7 +59,7 @@ function layoutOf(db, table) {
|
|
|
59
59
|
return { virtual, columns, foreignKeys: virtual ? [] : foreignKeysOf(db, table), indexes: virtual ? [] : indexesOf(db, table) };
|
|
60
60
|
}
|
|
61
61
|
/** @complexity O(database size) to deserialize the snapshot. */
|
|
62
|
-
export function openSqliteSnapshotSource({ bytes },
|
|
62
|
+
export function openSqliteSnapshotSource({ bytes, open }, _optional = {}) {
|
|
63
63
|
const db = open(inMemoryReadableBytes({ bytes }), { readonly: true });
|
|
64
64
|
return {
|
|
65
65
|
tableNames() {
|