@jini-ai/db 0.6.15-rc.2 → 0.6.15
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 +16 -0
- package/dist/kernel/dialect.d.ts +19 -0
- package/dist/kernel/dialect.js +17 -3
- package/dist/kernel/kernel-core.js +5 -5
- package/dist/kernel/owned-transaction.d.ts +10 -1
- package/dist/kernel/owned-transaction.js +11 -1
- package/dist/kernel/pglite/ops.js +4 -2
- package/dist/kernel/schema-scope.js +2 -4
- package/dist/kernel/schema-shape.js +6 -2
- package/dist/kernel/sqlite/driver.js +19 -16
- package/dist/kernel/store-copy.js +9 -2
- package/dist/kernel/typegen.js +3 -1
- package/dist/migrate/ddl.d.ts +2 -10
- package/dist/migrate/ddl.js +2 -12
- package/dist/migrate/ledger-contracts.d.ts +31 -0
- package/dist/migrate/ledger-contracts.js +2 -0
- package/dist/migrate/legacy-ledger.d.ts +2 -15
- package/dist/migrate/runner.d.ts +1 -40
- package/dist/migrate/runner.js +9 -5
- package/dist/owner-store/migrations/0000_owner_store.js +2 -1
- package/dist/pglite/owner.js +1 -1
- package/dist/pglite/socket-server.js +3 -1
- package/dist/secrets-vault/repo.sql.d.ts +1 -4
- package/dist/secrets-vault/repo.sql.js +21 -3
- package/dist/shared/ddl.adapter.d.ts +3 -0
- package/dist/shared/ddl.adapter.js +3 -0
- package/dist/sqlite/inspect.js +3 -6
- package/dist/tools/database-catalog.d.ts +3 -0
- package/dist/tools/database-catalog.js +9 -7
- package/dist/tools/read-tools.js +6 -6
- package/dist/transfer/copy-engine.d.ts +2 -5
- package/dist/transfer/copy-engine.js +24 -7
- package/dist/transfer/internal-ddl.js +5 -2
- package/dist/transfer/plan.d.ts +2 -1
- package/dist/transfer/plan.js +1 -1
- package/dist/transfer/postgres-target.js +9 -2
- package/dist/transfer/table-catalog.js +14 -9
- package/dist/transfer/types.d.ts +4 -0
- package/package.json +6 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
## 0.6.15
|
|
2
|
+
|
|
3
|
+
### Minor Changes
|
|
4
|
+
|
|
5
|
+
- BREAKING (`@jini-ai/server/owner-store`): the owner store is now a read-only legacy reader. Shared keys are project
|
|
6
|
+
references in the host, so nothing writes, migrates, grants, syncs or revokes an owner store any more. Removed:
|
|
7
|
+
`openOwnerStore`, `OwnerStoreService`, `exportOwnerStore`, `restoreOwnerStore`, `OwnerRevocationPendingError`,
|
|
8
|
+
`OwnerUnreconciledError`, `OWNER_REVOCATION_AUTO_ATTEMPTS` and their types. Added: `countLegacyOwnerStore`
|
|
9
|
+
(entry/grant counts, no key), `readLegacyOwnerStore` (decrypted entries plus recorded destinations, opened with
|
|
10
|
+
SQLite's read-only mode and never migrated) and `readLegacyOwnerBackup` (authenticates and validates a v1 or v2
|
|
11
|
+
backup exactly as restore did, without writing). `OwnerStoreRecoveryError`, `OwnerStoreBackupError`,
|
|
12
|
+
`OWNER_WORKSPACE_ID` and `ownerContext` stay. `@jini-ai/db/owner-store` drops the unpublished
|
|
13
|
+
`0001_owner_revocations` step (`ownerRevocationsDdl`, `ownerRevocationsMigration`); `0000_owner_store` stays.
|
|
14
|
+
|
|
15
|
+
Migration: hosts that opened an owner store import its entries into their own store through the reader.
|
|
16
|
+
|
|
1
17
|
## 0.6.13
|
|
2
18
|
|
|
3
19
|
### Patch Changes
|
package/dist/kernel/dialect.d.ts
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
import { type Expression, type RawBuilder } from "kysely";
|
|
2
2
|
import type { StorageDialect, StorageKernel } from "./port.js";
|
|
3
|
+
/**
|
|
4
|
+
* @file Dialect helpers: the few places SQLite and Postgres spell the same thing differently, as
|
|
5
|
+
* Kysely `sql` fragments or kernel queries. A repo that needs one of these calls the helper with
|
|
6
|
+
* `kernel.dialect`; it never writes the dialect's own spelling (the raw-SQLite guard enforces the
|
|
7
|
+
* SQLite side). Idea from EmDash's `dialect-helpers.ts`, re-implemented here.
|
|
8
|
+
*
|
|
9
|
+
* Upserts need no helper: Kysely's `onConflict(oc => oc.column(…).doUpdateSet(…))` compiles to the
|
|
10
|
+
* same `ON CONFLICT … DO UPDATE` on both; "the value being inserted" is `eb.ref("excluded.col")`.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
14
|
+
* transaction. Shared adapter so independent migration domains need no Kysely import.
|
|
15
|
+
* @throws Propagates kernel execution failures; the caller's transaction owns rollback.
|
|
16
|
+
* @complexity O(n) time and space in DDL length, plus the database's execution cost.
|
|
17
|
+
*/
|
|
18
|
+
export declare function executeDdl({ kernel, ddl }: {
|
|
19
|
+
kernel: StorageKernel<unknown>;
|
|
20
|
+
ddl: string;
|
|
21
|
+
}, _options?: {}): Promise<void>;
|
|
3
22
|
/**
|
|
4
23
|
* A SCALAR at `path` inside a JSON text/jsonb column, as TEXT with the same spelling on both
|
|
5
24
|
* dialects: strings as themselves, integers in decimal, booleans as `'true'`/`'false'`, and SQL NULL
|
package/dist/kernel/dialect.js
CHANGED
|
@@ -8,7 +8,21 @@ import { sql } from "kysely";
|
|
|
8
8
|
* Upserts need no helper: Kysely's `onConflict(oc => oc.column(…).doUpdateSet(…))` compiles to the
|
|
9
9
|
* same `ON CONFLICT … DO UPDATE` on both; "the value being inserted" is `eb.ref("excluded.col")`.
|
|
10
10
|
*/
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
13
|
+
* transaction. Shared adapter so independent migration domains need no Kysely import.
|
|
14
|
+
* @throws Propagates kernel execution failures; the caller's transaction owns rollback.
|
|
15
|
+
* @complexity O(n) time and space in DDL length, plus the database's execution cost.
|
|
16
|
+
*/
|
|
17
|
+
export async function executeDdl({ kernel, ddl }, _options = {}) {
|
|
18
|
+
// Kysely executes one SQLite statement at a time.
|
|
19
|
+
for (const statement of ddl.split(";").filter(part => part.trim())) {
|
|
20
|
+
await kernel.execute(sql.raw(statement));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const JSON_KEY = /^\w+$/;
|
|
24
|
+
/** json_type() names SQLite reports for a JSON scalar of each JS type; strings are "text". */
|
|
25
|
+
const SQLITE_JSON_TYPES = { number: ["integer", "real"], boolean: ["true", "false"] };
|
|
12
26
|
function checkedPath(path) {
|
|
13
27
|
if (path.length === 0)
|
|
14
28
|
throw new Error("JSON path must name at least one key");
|
|
@@ -47,8 +61,8 @@ export function jsonText(dialect, column, path) {
|
|
|
47
61
|
export function jsonScalarEquals(dialect, column, path, value) {
|
|
48
62
|
if (dialect === "postgres")
|
|
49
63
|
return sql `((${column}::jsonb #> ${pgPath(path)}) = ${JSON.stringify(value)}::jsonb)`;
|
|
50
|
-
const bound = typeof value === "boolean" ? (value
|
|
51
|
-
const types =
|
|
64
|
+
const bound = typeof value === "boolean" ? Number(value) : value;
|
|
65
|
+
const types = SQLITE_JSON_TYPES[typeof value] ?? ["text"];
|
|
52
66
|
const at = sqlitePath(path);
|
|
53
67
|
return sql `(json_type(${column}, ${at}) IN (${sql.join(types)}) AND json_extract(${column}, ${at}) = ${bound})`;
|
|
54
68
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { UnsupportedCapabilityError, } from "./port.js";
|
|
3
3
|
import { TurnLock } from "./turn-lock.js";
|
|
4
|
-
import {
|
|
4
|
+
import { registerOwnedTransaction } from "./owned-transaction.js";
|
|
5
5
|
/** The turn locks the caller's async context holds, across every kernel in the process. */
|
|
6
6
|
const heldLocks = new AsyncLocalStorage();
|
|
7
7
|
/**
|
|
@@ -107,10 +107,10 @@ export function buildKernel(driver) {
|
|
|
107
107
|
},
|
|
108
108
|
close: () => driver.close(),
|
|
109
109
|
};
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
110
|
+
registerOwnedTransaction({ kernel: kernel, control: {
|
|
111
|
+
assertAvailable: assertOwnedAvailable,
|
|
112
|
+
transaction: (work, optional = {}) => transaction(work, optional),
|
|
113
|
+
} });
|
|
114
114
|
return kernel;
|
|
115
115
|
}
|
|
116
116
|
//# sourceMappingURL=kernel-core.js.map
|
|
@@ -7,7 +7,16 @@ export interface OwnedTransactionControl {
|
|
|
7
7
|
onSettled?: () => void;
|
|
8
8
|
}): Promise<T>;
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
/** Records the control of a kernel built by buildKernel. */
|
|
11
|
+
export declare function registerOwnedTransaction({ kernel, control }: {
|
|
12
|
+
kernel: StorageKernel<unknown>;
|
|
13
|
+
control: OwnedTransactionControl;
|
|
14
|
+
}): void;
|
|
15
|
+
/** A kernel derived from another (schema-scoped, owned connection) shares its control, when it has one. */
|
|
16
|
+
export declare function inheritOwnedTransaction({ from, to }: {
|
|
17
|
+
from: StorageKernel<unknown>;
|
|
18
|
+
to: StorageKernel<unknown>;
|
|
19
|
+
}): void;
|
|
11
20
|
/** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
|
|
12
21
|
export declare function ownedTransactionOf({ kernel }: {
|
|
13
22
|
kernel: StorageKernel<unknown>;
|
|
@@ -1,4 +1,14 @@
|
|
|
1
|
-
|
|
1
|
+
const ownedTransactions = new WeakMap();
|
|
2
|
+
/** Records the control of a kernel built by buildKernel. */
|
|
3
|
+
export function registerOwnedTransaction({ kernel, control }) {
|
|
4
|
+
ownedTransactions.set(kernel, control);
|
|
5
|
+
}
|
|
6
|
+
/** A kernel derived from another (schema-scoped, owned connection) shares its control, when it has one. */
|
|
7
|
+
export function inheritOwnedTransaction({ from, to }) {
|
|
8
|
+
const control = ownedTransactions.get(from);
|
|
9
|
+
if (control !== undefined)
|
|
10
|
+
ownedTransactions.set(to, control);
|
|
11
|
+
}
|
|
2
12
|
/** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
|
|
3
13
|
export function ownedTransactionOf({ kernel }, _optional = {}) {
|
|
4
14
|
const control = ownedTransactions.get(kernel);
|
|
@@ -22,8 +22,10 @@ export function pgliteOps(kernel, required, optional = {}) {
|
|
|
22
22
|
return {
|
|
23
23
|
async copyTo(targetPath) {
|
|
24
24
|
outsideTransaction("copyTo");
|
|
25
|
-
if (owner !== undefined)
|
|
26
|
-
|
|
25
|
+
if (owner !== undefined) {
|
|
26
|
+
await copyServedPgliteTo(owner, targetPath, required);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
27
29
|
await restoreDataDir(targetPath, required, async () => {
|
|
28
30
|
const tarball = `${targetPath}.${randomUUID()}.tar`;
|
|
29
31
|
try {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { inheritOwnedTransaction } from "./owned-transaction.js";
|
|
2
2
|
/**
|
|
3
3
|
* @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
|
|
4
4
|
* `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
|
|
@@ -17,9 +17,7 @@ export function scopeToSchema(kernel, schema) {
|
|
|
17
17
|
...kernel,
|
|
18
18
|
run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
|
|
19
19
|
};
|
|
20
|
-
|
|
21
|
-
if (control !== undefined)
|
|
22
|
-
ownedTransactions.set(scoped, control);
|
|
20
|
+
inheritOwnedTransaction({ from: kernel, to: scoped });
|
|
23
21
|
return scoped;
|
|
24
22
|
}
|
|
25
23
|
//# sourceMappingURL=schema-scope.js.map
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { sql } from "kysely";
|
|
2
|
+
/** A column default as it appears in the shape text; absent defaults add nothing. */
|
|
3
|
+
function defaultClause(value) {
|
|
4
|
+
return value === null ? "" : " DEFAULT " + value;
|
|
5
|
+
}
|
|
2
6
|
const squash = (text) => text.replace(/\s+/g, " ").trim();
|
|
3
7
|
/** Every user table's shape (internal and `sqlite_`/`pg_` tables excluded), keyed by table name. */
|
|
4
8
|
export async function readSchemaShape(kernel, optional = {}) {
|
|
@@ -31,7 +35,7 @@ async function sqliteShape(kernel) {
|
|
|
31
35
|
});
|
|
32
36
|
constraints.push(`DEFINITION ${squash(object.sql)}`);
|
|
33
37
|
tables[object.name] = {
|
|
34
|
-
columns: columns.map((c) => `${c.name} ${c.type.toLowerCase()}${c.notnull ? " NOT NULL" : ""}${c.dflt_value
|
|
38
|
+
columns: columns.map((c) => `${c.name} ${c.type.toLowerCase()}${c.notnull ? " NOT NULL" : ""}${defaultClause(c.dflt_value)}${c.pk ? " PK" + c.pk : ""}`),
|
|
35
39
|
indexes: indexTexts.sort(),
|
|
36
40
|
constraints: constraints.sort(),
|
|
37
41
|
};
|
|
@@ -67,7 +71,7 @@ async function postgresShape(kernel) {
|
|
|
67
71
|
const tables = {};
|
|
68
72
|
const table = (name) => (tables[name] ??= { columns: [], indexes: [], constraints: [] });
|
|
69
73
|
for (const c of columns) {
|
|
70
|
-
table(c.table_name).columns.push(`${c.column_name} ${c.data_type.toLowerCase()}${c.is_nullable === "NO" ? " NOT NULL" : ""}${c.column_default
|
|
74
|
+
table(c.table_name).columns.push(`${c.column_name} ${c.data_type.toLowerCase()}${c.is_nullable === "NO" ? " NOT NULL" : ""}${defaultClause(c.column_default)}`);
|
|
71
75
|
}
|
|
72
76
|
for (const i of indexes)
|
|
73
77
|
table(i.tablename).indexes.push(`${i.indexname} ${squash(i.indexdef).replace(/ ON \S+\./, " ON ")}`);
|
|
@@ -2,7 +2,7 @@ import path from "node:path";
|
|
|
2
2
|
import { Kysely, SqliteDialect } from "kysely";
|
|
3
3
|
import { buildKernel, TurnLock } from "../index.js";
|
|
4
4
|
import { checkedClients, checkedStates, connectionsByKernel, rawKernelClients } from "../../sqlite/checked-state.js";
|
|
5
|
-
import {
|
|
5
|
+
import { inheritOwnedTransaction } from "../owned-transaction.js";
|
|
6
6
|
const kernels = new WeakMap();
|
|
7
7
|
/** One turn lock per database FILE, shared by every connection to it in this process. */
|
|
8
8
|
const fileTurnLocks = new Map();
|
|
@@ -21,7 +21,22 @@ function turnLockFor(client) {
|
|
|
21
21
|
export function sqliteClientOf(source) {
|
|
22
22
|
return "$client" in source ? source.$client : source;
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
/** Rolls back a failed transaction; a checked kernel reports a failing rollback with the original error. */
|
|
25
|
+
function rollbackAfterFailure({ client, error, checked }) {
|
|
26
|
+
if (!checked) {
|
|
27
|
+
if (client.inTransaction)
|
|
28
|
+
client.exec("ROLLBACK");
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
if (client.inTransaction)
|
|
33
|
+
client.exec("ROLLBACK");
|
|
34
|
+
}
|
|
35
|
+
catch (cleanup) {
|
|
36
|
+
throw new AggregateError([error, cleanup], "SQLite transaction and rollback failed");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const bindable = (value) => (typeof value === "boolean" ? Number(value) : value);
|
|
25
40
|
/** better-sqlite3 as Kysely's `SqliteDatabase`, with booleans bound as integers. */
|
|
26
41
|
function bindingShim(client) {
|
|
27
42
|
return {
|
|
@@ -65,17 +80,7 @@ export function sqliteKernel(source) {
|
|
|
65
80
|
return result;
|
|
66
81
|
}
|
|
67
82
|
catch (error) {
|
|
68
|
-
|
|
69
|
-
try {
|
|
70
|
-
if (client.inTransaction)
|
|
71
|
-
client.exec("ROLLBACK");
|
|
72
|
-
}
|
|
73
|
-
catch (cleanup) {
|
|
74
|
-
throw new AggregateError([error, cleanup], "SQLite transaction and rollback failed");
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
else if (client.inTransaction)
|
|
78
|
-
client.exec("ROLLBACK");
|
|
83
|
+
rollbackAfterFailure({ client, error, checked });
|
|
79
84
|
throw error;
|
|
80
85
|
}
|
|
81
86
|
},
|
|
@@ -127,9 +132,7 @@ export function openSqliteFileKernel(required, optional = {}) {
|
|
|
127
132
|
close: async () => closeSqliteConnection(client),
|
|
128
133
|
};
|
|
129
134
|
connectionsByKernel.set(owned, client);
|
|
130
|
-
|
|
131
|
-
if (control !== undefined)
|
|
132
|
-
ownedTransactions.set(owned, control);
|
|
135
|
+
inheritOwnedTransaction({ from: kernel, to: owned });
|
|
133
136
|
return owned;
|
|
134
137
|
}
|
|
135
138
|
/**
|
|
@@ -146,15 +146,22 @@ async function copyRows(source, target, table) {
|
|
|
146
146
|
return copied;
|
|
147
147
|
// Bind text before the catalog type cast: PGlite's bytea serializer accepts bytes, not text.
|
|
148
148
|
// The server's input functions decode the unchanged text, including nulls, JSON and arrays.
|
|
149
|
-
const values = sql.join(rows.map((row) =>
|
|
149
|
+
const values = sql.join(rows.map((row) => {
|
|
150
|
+
const cells = columns.map((c) => sql `${row[c.name]}::text::${sql.raw(c.type)}`);
|
|
151
|
+
return sql `(${sql.join(cells)})`;
|
|
152
|
+
}));
|
|
150
153
|
await target.execute(sql `INSERT INTO ${tableRef(table)} (${into}) OVERRIDING SYSTEM VALUE VALUES ${values}`);
|
|
151
154
|
copied += rows.length;
|
|
152
155
|
after = rows[rows.length - 1].__ctid;
|
|
153
156
|
}
|
|
154
157
|
}
|
|
158
|
+
/** Each primary-key column as text, for the fingerprint's key concatenation. */
|
|
159
|
+
function primaryKeyTexts(table) {
|
|
160
|
+
return table.primaryKey.map((c) => sql `${sql.ref(c)}::text`);
|
|
161
|
+
}
|
|
155
162
|
/** Row count and an order-independent checksum of the primary keys (count only without one). */
|
|
156
163
|
async function fingerprint(kernel, table) {
|
|
157
|
-
const key = table.primaryKey.length === 0 ? sql `''` : sql `concat_ws(E'\\t', ${sql.join(table
|
|
164
|
+
const key = table.primaryKey.length === 0 ? sql `''` : sql `concat_ws(E'\\t', ${sql.join(primaryKeyTexts(table))})`;
|
|
158
165
|
const [row] = await kernel.query(sql `SELECT count(*)::int AS n, md5(coalesce(string_agg(k, E'\\n' ORDER BY k COLLATE "C"), '')) AS sum
|
|
159
166
|
FROM (SELECT ${key} AS k FROM ${tableRef(table)}) keyed`);
|
|
160
167
|
return `${row.n}:${row.sum}`;
|
package/dist/kernel/typegen.js
CHANGED
|
@@ -22,8 +22,10 @@ function pascal(name) {
|
|
|
22
22
|
function columnType(column) {
|
|
23
23
|
const nullable = column.is_nullable === "YES";
|
|
24
24
|
const generated = column.column_default !== null || column.is_identity === "YES";
|
|
25
|
+
if (column.data_type === "boolean" && nullable)
|
|
26
|
+
return "NullableBool";
|
|
25
27
|
if (column.data_type === "boolean")
|
|
26
|
-
return
|
|
28
|
+
return generated ? "GeneratedBool" : "Bool";
|
|
27
29
|
const scalar = SCALAR[column.data_type];
|
|
28
30
|
if (scalar === undefined) {
|
|
29
31
|
throw new Error(`typegen: no TypeScript type for ${column.table_name}.${column.column_name} (${column.data_type})`);
|
package/dist/migrate/ddl.d.ts
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
4
|
-
* transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
|
|
5
|
-
* @complexity O(statements).
|
|
6
|
-
*/
|
|
7
|
-
export declare function executeDdl({ kernel, ddl }: {
|
|
8
|
-
kernel: StorageKernel<unknown>;
|
|
9
|
-
ddl: string;
|
|
10
|
-
}, _options?: {}): Promise<void>;
|
|
1
|
+
/** Compatibility entry for the kernel's shared database DDL adapter. */
|
|
2
|
+
export { executeDdl } from "../kernel/dialect.js";
|
|
11
3
|
//# sourceMappingURL=ddl.d.ts.map
|
package/dist/migrate/ddl.js
CHANGED
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
4
|
-
* transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
|
|
5
|
-
* @complexity O(statements).
|
|
6
|
-
*/
|
|
7
|
-
export async function executeDdl({ kernel, ddl }, _options = {}) {
|
|
8
|
-
// Kysely executes one SQLite statement at a time.
|
|
9
|
-
for (const statement of ddl.split(";").filter(part => part.trim())) {
|
|
10
|
-
await kernel.execute(sql.raw(statement));
|
|
11
|
-
}
|
|
12
|
-
}
|
|
1
|
+
/** Compatibility entry for the kernel's shared database DDL adapter. */
|
|
2
|
+
export { executeDdl } from "../kernel/dialect.js";
|
|
13
3
|
//# sourceMappingURL=ddl.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Kysely } from "kysely";
|
|
2
|
+
export interface LedgerRow {
|
|
3
|
+
id: string;
|
|
4
|
+
checksum: string;
|
|
5
|
+
applied_at: string;
|
|
6
|
+
}
|
|
7
|
+
type LedgerDb = Record<string, LedgerRow>;
|
|
8
|
+
/** Persisted identities remain host-owned; no existing row is rewritten. */
|
|
9
|
+
export interface LegacyLedgerMapping {
|
|
10
|
+
columns: {
|
|
11
|
+
version: string;
|
|
12
|
+
name: string;
|
|
13
|
+
checksum: string;
|
|
14
|
+
appliedAt: string;
|
|
15
|
+
};
|
|
16
|
+
identities: Readonly<Record<string, {
|
|
17
|
+
version: number;
|
|
18
|
+
name: string;
|
|
19
|
+
}>>;
|
|
20
|
+
timestamps?: "database-default" | "iso";
|
|
21
|
+
}
|
|
22
|
+
/** Where one history's ledger lives, resolved from {@link MigrationOptions}. */
|
|
23
|
+
export interface Ledger {
|
|
24
|
+
readonly table: string;
|
|
25
|
+
readonly schema: string | undefined;
|
|
26
|
+
readonly lockKey: string;
|
|
27
|
+
readonly mapping: LegacyLedgerMapping | undefined;
|
|
28
|
+
run<T>(fn: (db: Kysely<LedgerDb>) => Promise<T>): Promise<T>;
|
|
29
|
+
}
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=ledger-contracts.d.ts.map
|
|
@@ -1,20 +1,7 @@
|
|
|
1
1
|
import type { MigrationStep } from "./step.js";
|
|
2
|
-
import type { Ledger, LedgerRow } from "./
|
|
2
|
+
import type { Ledger, LedgerRow, LegacyLedgerMapping } from "./ledger-contracts.js";
|
|
3
|
+
export type { LegacyLedgerMapping } from "./ledger-contracts.js";
|
|
3
4
|
import type { StorageDialect } from "../kernel/port.js";
|
|
4
|
-
/** Persisted identities remain host-owned; no existing row is rewritten. */
|
|
5
|
-
export interface LegacyLedgerMapping {
|
|
6
|
-
columns: {
|
|
7
|
-
version: string;
|
|
8
|
-
name: string;
|
|
9
|
-
checksum: string;
|
|
10
|
-
appliedAt: string;
|
|
11
|
-
};
|
|
12
|
-
identities: Readonly<Record<string, {
|
|
13
|
-
version: number;
|
|
14
|
-
name: string;
|
|
15
|
-
}>>;
|
|
16
|
-
timestamps?: "database-default" | "iso";
|
|
17
|
-
}
|
|
18
5
|
/** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
|
|
19
6
|
export declare function validateLegacyMapping({ mapping, steps }: {
|
|
20
7
|
mapping: LegacyLedgerMapping;
|
package/dist/migrate/runner.d.ts
CHANGED
|
@@ -1,38 +1,8 @@
|
|
|
1
|
-
import { type Kysely } from "kysely";
|
|
2
1
|
import { type Clock } from "@jini-ai/core/primitives";
|
|
3
2
|
import { type StorageKernel } from "../kernel/index.js";
|
|
4
3
|
import { type LegacyLedgerMapping } from "./legacy-ledger.js";
|
|
4
|
+
export type { Ledger, LedgerRow } from "./ledger-contracts.js";
|
|
5
5
|
import { type MigrationStep } from "./step.js";
|
|
6
|
-
/**
|
|
7
|
-
* @file The migration runner: applies an ordered list of {@link MigrationStep}s to one database on
|
|
8
|
-
* any dialect and records each in a ledger table the consumer names (required, no default: this
|
|
9
|
-
* package ships no tables, so no name of its own can leak into a consumer's database).
|
|
10
|
-
*
|
|
11
|
-
* - Default ledger `<ledgerTable>(id, checksum, applied_at)`, created by the runner inside the first step's
|
|
12
|
-
* transaction (so a step's pre-change backup has no trace of the runner), same on every dialect.
|
|
13
|
-
* - Before anything is applied, every recorded id must be one this runtime knows
|
|
14
|
-
* (unless an additive history opts into `allowUnknownApplied`)
|
|
15
|
-
* ({@link UnknownAppliedMigrationError}) with the checksum this runtime has
|
|
16
|
-
* ({@link MigrationChecksumError}). Nothing is applied on a mismatch.
|
|
17
|
-
* - Serialized: by default each pending step runs in ONE kernel transaction that first takes
|
|
18
|
-
* `lockKey(<ledgerTable>)` (Postgres advisory lock; SQLite's `BEGIN IMMEDIATE` write lock) and
|
|
19
|
-
* re-reads and verifies the full ledger, so two processes starting at once apply a step exactly once
|
|
20
|
-
* and an older runtime refuses history committed by a newer one while it was waiting.
|
|
21
|
-
* - A kernel without interactive transactions is refused (`require`), never downgraded.
|
|
22
|
-
* - Given {@link MigrationOptions.backupPath}, a database that already holds tables is copied there
|
|
23
|
-
* once, outside any transaction, before the first pending step (ledger absent or behind). Nothing
|
|
24
|
-
* pending, an empty database or a driver without `backup` (Postgres): no copy.
|
|
25
|
-
* - One runner, several histories: each history names its own ledger
|
|
26
|
-
* ({@link MigrationOptions.ledgerTable}) and, on Postgres, may name the schema that ledger lives in
|
|
27
|
-
* ({@link MigrationOptions.schema}). Ledger statements
|
|
28
|
-
* go through Kysely `withSchema`, never `SET search_path` (no session state on a shared PGlite).
|
|
29
|
-
*/
|
|
30
|
-
export interface LedgerRow {
|
|
31
|
-
id: string;
|
|
32
|
-
checksum: string;
|
|
33
|
-
applied_at: string;
|
|
34
|
-
}
|
|
35
|
-
type LedgerDb = Record<string, LedgerRow>;
|
|
36
6
|
export interface MigrationOptions {
|
|
37
7
|
/** The ledger table (REQUIRED, no default); also the migration lock's key. */
|
|
38
8
|
ledgerTable: string;
|
|
@@ -53,14 +23,6 @@ export interface MigrationOptions {
|
|
|
53
23
|
/** Explicit persisted identities and column names for an existing version/name ledger. */
|
|
54
24
|
legacyLedger?: LegacyLedgerMapping;
|
|
55
25
|
}
|
|
56
|
-
/** Where one history's ledger lives, resolved from {@link MigrationOptions}. */
|
|
57
|
-
export interface Ledger {
|
|
58
|
-
readonly table: string;
|
|
59
|
-
readonly schema: string | undefined;
|
|
60
|
-
readonly lockKey: string;
|
|
61
|
-
readonly mapping: LegacyLedgerMapping | undefined;
|
|
62
|
-
run<T>(fn: (db: Kysely<LedgerDb>) => Promise<T>): Promise<T>;
|
|
63
|
-
}
|
|
64
26
|
export interface MigrationReport {
|
|
65
27
|
/** Steps this call applied, in order. */
|
|
66
28
|
applied: string[];
|
|
@@ -87,5 +49,4 @@ export declare function migrate(required: {
|
|
|
87
49
|
export declare function runMigrations(kernel: StorageKernel<unknown>, steps: readonly MigrationStep[], options: MigrationOptions): Promise<MigrationReport>;
|
|
88
50
|
/** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
|
|
89
51
|
export declare function hasLedger(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<boolean>;
|
|
90
|
-
export {};
|
|
91
52
|
//# sourceMappingURL=runner.d.ts.map
|
package/dist/migrate/runner.js
CHANGED
|
@@ -41,8 +41,10 @@ export function assertValidSteps(steps) {
|
|
|
41
41
|
async function ensureLedger(kernel, ledger) {
|
|
42
42
|
if (ledger.schema !== undefined)
|
|
43
43
|
await kernel.run((db) => db.schema.createSchema(ledger.schema).ifNotExists().execute());
|
|
44
|
-
if (ledger.mapping !== undefined)
|
|
45
|
-
|
|
44
|
+
if (ledger.mapping !== undefined) {
|
|
45
|
+
await ensureLegacyLedger({ ledger, mapping: ledger.mapping, dialect: kernel.dialect });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
46
48
|
await ledger.run((db) => db.schema
|
|
47
49
|
.createTable(ledger.table)
|
|
48
50
|
.ifNotExists()
|
|
@@ -74,8 +76,10 @@ function verifyRecorded(rows, steps, options) {
|
|
|
74
76
|
}
|
|
75
77
|
async function insertRow({ ledger, step, options }, _optional = {}) {
|
|
76
78
|
const timestamp = () => options.clock === undefined ? new Date().toISOString() : nowIso({ clock: options.clock });
|
|
77
|
-
if (ledger.mapping !== undefined)
|
|
78
|
-
|
|
79
|
+
if (ledger.mapping !== undefined) {
|
|
80
|
+
await insertLegacyRow({ ledger, mapping: ledger.mapping, step, timestamp });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
79
83
|
await ledger.run((db) => db.insertInto(ledger.table).values({ id: step.id, checksum: step.checksum, applied_at: timestamp() }).execute());
|
|
80
84
|
}
|
|
81
85
|
async function recordedStep({ ledger, step, steps, options }, _optional = {}) {
|
|
@@ -189,7 +193,7 @@ async function backUpBeforeChange(kernel, context) {
|
|
|
189
193
|
async function ledgerExists(kernel, ledger) {
|
|
190
194
|
if (ledger.schema === undefined)
|
|
191
195
|
return tableExists(kernel, ledger.table);
|
|
192
|
-
const [row] = await kernel.query(sql `SELECT to_regclass(${
|
|
196
|
+
const [row] = await kernel.query(sql `SELECT to_regclass(${ledger.schema + "." + ledger.table})::text AS found`);
|
|
193
197
|
return row?.found != null;
|
|
194
198
|
}
|
|
195
199
|
/** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { executeDdl } from "../../migrate/ddl.js";
|
|
2
1
|
/** Owner-only history: no site tables or foreign workspace records are required. */
|
|
3
2
|
export const ownerStoreDdl = `
|
|
4
3
|
CREATE TABLE secrets_vault (
|
|
@@ -30,6 +29,8 @@ export const ownerStoreMigration = {
|
|
|
30
29
|
id: "0000_owner_store",
|
|
31
30
|
checksum: "ea2c33cf1835f6b1db0f52a4de3419aaf8c1a2e2edeece1e2b3240c517592446",
|
|
32
31
|
async up(kernel) {
|
|
32
|
+
// Reading migration metadata must not load the SQL adapter or its optional Kysely peer.
|
|
33
|
+
const { executeDdl } = await import("../../shared/ddl.adapter.js");
|
|
33
34
|
await executeDdl({ kernel, ddl: ownerStoreDdl });
|
|
34
35
|
},
|
|
35
36
|
};
|
package/dist/pglite/owner.js
CHANGED
|
@@ -47,7 +47,7 @@ export class PgliteOwnerLockedError extends Error {
|
|
|
47
47
|
constructor(dataDir,
|
|
48
48
|
/** Undefined while the other starter's lock has no pid in it yet. */
|
|
49
49
|
pid) {
|
|
50
|
-
super(`the PGlite data dir ${dataDir} is already open by ${pid === undefined ? "another process" :
|
|
50
|
+
super(`the PGlite data dir ${dataDir} is already open by ${pid === undefined ? "another process" : "process " + pid}; only one process may own it (connect to its socket instead)`);
|
|
51
51
|
this.dataDir = dataDir;
|
|
52
52
|
this.pid = pid;
|
|
53
53
|
this.name = "PgliteOwnerLockedError";
|
|
@@ -389,7 +389,9 @@ export class PgliteSocketServer {
|
|
|
389
389
|
endSocket(socket, false);
|
|
390
390
|
return;
|
|
391
391
|
}
|
|
392
|
-
const
|
|
392
|
+
const id = this.nextId;
|
|
393
|
+
this.nextId += 1;
|
|
394
|
+
const connection = new Connection(id, socket, this.options.db, this.queue, (closed) => this.connections.delete(closed.id));
|
|
393
395
|
this.connections.set(connection.id, connection);
|
|
394
396
|
}
|
|
395
397
|
}
|
|
@@ -32,10 +32,6 @@ export interface SecretsVaultTable {
|
|
|
32
32
|
export interface SecretsVaultDatabase {
|
|
33
33
|
secrets_vault: SecretsVaultTable;
|
|
34
34
|
}
|
|
35
|
-
/** One Kysely adapter for SQLite and Postgres/PGlite. Workspace lock `secrets_vault:<workspaceId>`
|
|
36
|
-
* serializes every writer, including targeted patches and boot rotation. Nested transactions join
|
|
37
|
-
* the host's transaction, allowing MCP payload/pointer/status writes to commit together.
|
|
38
|
-
*/
|
|
39
35
|
export declare class SqlSecretsVaultRepo implements VaultRepoPort {
|
|
40
36
|
private readonly kernel;
|
|
41
37
|
constructor({ kernel }: {
|
|
@@ -57,6 +53,7 @@ export declare class SqlSecretsVaultRepo implements VaultRepoPort {
|
|
|
57
53
|
applyBatch({ ops }: {
|
|
58
54
|
ops: readonly VaultBatchOp[];
|
|
59
55
|
}, _options?: VaultOptions): Promise<VaultBatchResult[]>;
|
|
56
|
+
private applyOp;
|
|
60
57
|
/** One indexed exact-group lookup; ciphertext is loaded only for the chosen default.
|
|
61
58
|
* The group is restated in the default index's normalized expressions and `is_default` is a
|
|
62
59
|
* literal, else neither SQLite nor a generic Postgres plan can match the partial index (host
|
|
@@ -32,6 +32,17 @@ function toRow(record) {
|
|
|
32
32
|
* serializes every writer, including targeted patches and boot rotation. Nested transactions join
|
|
33
33
|
* the host's transaction, allowing MCP payload/pointer/status writes to commit together.
|
|
34
34
|
*/
|
|
35
|
+
function batchOpWorkspaceId(op) {
|
|
36
|
+
if ("put" in op)
|
|
37
|
+
return op.put.record.workspaceId;
|
|
38
|
+
return "delete" in op ? op.delete.workspaceId : op.patchMeta.workspaceId;
|
|
39
|
+
}
|
|
40
|
+
/** Code-unit order, independent of any database collation. */
|
|
41
|
+
function compareIds(a, b) {
|
|
42
|
+
if (a === b)
|
|
43
|
+
return 0;
|
|
44
|
+
return a < b ? -1 : 1;
|
|
45
|
+
}
|
|
35
46
|
export class SqlSecretsVaultRepo {
|
|
36
47
|
kernel;
|
|
37
48
|
constructor({ kernel }, _options = {}) { this.kernel = kernel; }
|
|
@@ -76,16 +87,23 @@ export class SqlSecretsVaultRepo {
|
|
|
76
87
|
*/
|
|
77
88
|
async applyBatch({ ops }, _options = {}) {
|
|
78
89
|
return this.kernel.transaction(async () => {
|
|
79
|
-
const workspaces = ops.map(
|
|
90
|
+
const workspaces = ops.map(batchOpWorkspaceId);
|
|
80
91
|
for (const workspaceId of [...new Set(workspaces)].sort())
|
|
81
92
|
await this.kernel.lockKey(`secrets_vault:${workspaceId}`);
|
|
82
93
|
const results = [];
|
|
83
94
|
for (const op of ops) {
|
|
84
|
-
results.push(
|
|
95
|
+
results.push(await this.applyOp(op));
|
|
85
96
|
}
|
|
86
97
|
return results;
|
|
87
98
|
});
|
|
88
99
|
}
|
|
100
|
+
applyOp(op) {
|
|
101
|
+
if ("put" in op)
|
|
102
|
+
return this.put(op.put);
|
|
103
|
+
if ("delete" in op)
|
|
104
|
+
return this.delete(op.delete);
|
|
105
|
+
return this.patchMeta(op.patchMeta);
|
|
106
|
+
}
|
|
89
107
|
/** One indexed exact-group lookup; ciphertext is loaded only for the chosen default.
|
|
90
108
|
* The group is restated in the default index's normalized expressions and `is_default` is a
|
|
91
109
|
* literal, else neither SQLite nor a generic Postgres plan can match the partial index (host
|
|
@@ -100,7 +118,7 @@ export class SqlSecretsVaultRepo {
|
|
|
100
118
|
async list(input, _options = {}) {
|
|
101
119
|
const rows = await this.kernel.run(db => this.scoped({ db, input }).selectAll().execute());
|
|
102
120
|
// Sort identifiers in JS to avoid host database collation changing the memory contract.
|
|
103
|
-
return rows.map(fromRow).sort((a, b) => a.id
|
|
121
|
+
return rows.map(fromRow).sort((a, b) => compareIds(a.id, b.id));
|
|
104
122
|
}
|
|
105
123
|
async assertLabelAvailable({ record, existing, moved, scope }, _options = {}) {
|
|
106
124
|
// Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
|
package/dist/sqlite/inspect.js
CHANGED
|
@@ -114,7 +114,7 @@ async function sumFileSizes(paths) {
|
|
|
114
114
|
function sanitizeTableName(name) {
|
|
115
115
|
// Allow ASCII alphanumerics + underscore; SQLite identifier sanity check. Prevents accidental
|
|
116
116
|
// SQL injection if a malicious migration ever invents a hostile table name.
|
|
117
|
-
if (!/^[A-Za-z_]
|
|
117
|
+
if (!/^[A-Za-z_]\w*$/.test(name))
|
|
118
118
|
return null;
|
|
119
119
|
return name;
|
|
120
120
|
}
|
|
@@ -134,11 +134,8 @@ function readIntegrityIssues({ db, pragma }, { strict = false } = {}) {
|
|
|
134
134
|
// SQLite returns the string under either `integrity_check`, `quick_check`, or just the
|
|
135
135
|
// first column. Normalise to the first string-valued field.
|
|
136
136
|
const message = (row[pragma] ?? Object.values(row)[0]);
|
|
137
|
-
if (typeof message
|
|
138
|
-
|
|
139
|
-
if (message.toLowerCase() === 'ok')
|
|
140
|
-
continue;
|
|
141
|
-
issues.push({ kind: 'integrity', message });
|
|
137
|
+
if (typeof message === 'string' && message.toLowerCase() !== 'ok')
|
|
138
|
+
issues.push({ kind: 'integrity', message });
|
|
142
139
|
}
|
|
143
140
|
}
|
|
144
141
|
catch (err) {
|
|
@@ -46,6 +46,9 @@
|
|
|
46
46
|
*/
|
|
47
47
|
import type { AgentToolDefinition } from "@jini-ai/core";
|
|
48
48
|
import { type DbMessages } from "../core/messages.js";
|
|
49
|
+
/** No arguments — shared by every parameterless read tool in this catalog. */
|
|
50
|
+
/** The permission every read-only database tool requires. */
|
|
51
|
+
export declare const DATABASE_READ_PERMISSION = "database.read";
|
|
49
52
|
/**
|
|
50
53
|
* The Database domain's fixed agent-tool contracts (D4), with fresh host-facing prose.
|
|
51
54
|
* @param _optional.messages Host copy; omitted messages use the neutral defaultDbMessages.
|
|
@@ -46,6 +46,8 @@
|
|
|
46
46
|
*/
|
|
47
47
|
import { defaultDbMessages } from "../core/messages.js";
|
|
48
48
|
/** No arguments — shared by every parameterless read tool in this catalog. */
|
|
49
|
+
/** The permission every read-only database tool requires. */
|
|
50
|
+
export const DATABASE_READ_PERMISSION = "database.read";
|
|
49
51
|
const NO_INPUT_SCHEMA = {
|
|
50
52
|
type: "object",
|
|
51
53
|
additionalProperties: false,
|
|
@@ -106,7 +108,7 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
|
|
|
106
108
|
name: "database_get_health",
|
|
107
109
|
description: messages.databaseHealth,
|
|
108
110
|
sideEffects: "none",
|
|
109
|
-
authorization: { permission:
|
|
111
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
110
112
|
inputSchema: NO_INPUT_SCHEMA,
|
|
111
113
|
},
|
|
112
114
|
{
|
|
@@ -117,7 +119,7 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
|
|
|
117
119
|
name: "database_get_schema_state",
|
|
118
120
|
description: messages.databaseSchemaState,
|
|
119
121
|
sideEffects: "none",
|
|
120
|
-
authorization: { permission:
|
|
122
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
121
123
|
inputSchema: NO_INPUT_SCHEMA,
|
|
122
124
|
},
|
|
123
125
|
{
|
|
@@ -128,21 +130,21 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
|
|
|
128
130
|
name: "database_list_pending_migrations",
|
|
129
131
|
description: messages.databasePendingMigrations,
|
|
130
132
|
sideEffects: "none",
|
|
131
|
-
authorization: { permission:
|
|
133
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
132
134
|
inputSchema: NO_INPUT_SCHEMA,
|
|
133
135
|
},
|
|
134
136
|
{
|
|
135
137
|
name: "database_query_timeline",
|
|
136
138
|
description: "Returns a filtered, cursor-paginated page of the append-only database ledger (migrations, snapshots, restores, interrupted migrations), newest first.",
|
|
137
139
|
sideEffects: "none",
|
|
138
|
-
authorization: { permission:
|
|
140
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
139
141
|
inputSchema: TIMELINE_QUERY_SCHEMA,
|
|
140
142
|
},
|
|
141
143
|
{
|
|
142
144
|
name: "database_list_restore_points",
|
|
143
145
|
description: messages.databaseRestorePoints,
|
|
144
146
|
sideEffects: "none",
|
|
145
|
-
authorization: { permission:
|
|
147
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
146
148
|
inputSchema: NO_INPUT_SCHEMA,
|
|
147
149
|
},
|
|
148
150
|
{
|
|
@@ -156,7 +158,7 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
|
|
|
156
158
|
name: "database_plan_migrate_forward",
|
|
157
159
|
description: messages.databasePlanMigrate,
|
|
158
160
|
sideEffects: "none",
|
|
159
|
-
authorization: { permission:
|
|
161
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
160
162
|
inputSchema: NO_INPUT_SCHEMA,
|
|
161
163
|
},
|
|
162
164
|
{
|
|
@@ -194,7 +196,7 @@ export function getDatabaseAgentToolCatalog(_required = {}, _optional = {}) {
|
|
|
194
196
|
name: "database_get_restore_guidance",
|
|
195
197
|
description: messages.databaseRestoreGuidance,
|
|
196
198
|
sideEffects: "none",
|
|
197
|
-
authorization: { permission:
|
|
199
|
+
authorization: { permission: DATABASE_READ_PERMISSION },
|
|
198
200
|
},
|
|
199
201
|
];
|
|
200
202
|
}
|
package/dist/tools/read-tools.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { readToolLimit, ToolInputError } from "@jini-ai/core";
|
|
3
3
|
import { nowIso } from "@jini-ai/core/primitives";
|
|
4
4
|
import { defaultDbMessages } from "../core/messages.js";
|
|
5
|
-
import { getDatabaseAgentToolCatalog } from "./database-catalog.js";
|
|
5
|
+
import { DATABASE_READ_PERMISSION, getDatabaseAgentToolCatalog } from "./database-catalog.js";
|
|
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";
|
|
@@ -21,7 +21,7 @@ export function createDatabaseReadTools(ports, _optional = {}) {
|
|
|
21
21
|
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
22
22
|
throw new ToolInputError({ message: "input must be an object" });
|
|
23
23
|
const input = isRecord(ctx.input) ? ctx.input : {};
|
|
24
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission:
|
|
24
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database-ledger" });
|
|
25
25
|
return getTimeline({
|
|
26
26
|
ledger: ports.ledger,
|
|
27
27
|
filter: {
|
|
@@ -38,22 +38,22 @@ export function createDatabaseReadTools(ports, _optional = {}) {
|
|
|
38
38
|
},
|
|
39
39
|
database_list_restore_points: async (ctx) => {
|
|
40
40
|
requireNoInput(ctx.input);
|
|
41
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission:
|
|
41
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "restore-point" });
|
|
42
42
|
return listRestorePoints({ repo: ports.restorePoints });
|
|
43
43
|
},
|
|
44
44
|
database_get_health: async (ctx) => {
|
|
45
45
|
requireNoInput(ctx.input);
|
|
46
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission:
|
|
46
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database" });
|
|
47
47
|
return ports.introspection.getHealth();
|
|
48
48
|
},
|
|
49
49
|
database_get_schema_state: async (ctx) => {
|
|
50
50
|
requireNoInput(ctx.input);
|
|
51
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission:
|
|
51
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database" });
|
|
52
52
|
return ports.introspection.getSchemaState();
|
|
53
53
|
},
|
|
54
54
|
database_list_pending_migrations: async (ctx) => {
|
|
55
55
|
requireNoInput(ctx.input);
|
|
56
|
-
await ports.requirePermission({ principalId: ctx.principal.id, permission:
|
|
56
|
+
await ports.requirePermission({ principalId: ctx.principal.id, permission: DATABASE_READ_PERMISSION, entityType: "database" });
|
|
57
57
|
return ports.introspection.listPendingMigrations();
|
|
58
58
|
},
|
|
59
59
|
backup_create_restore_point: async (ctx) => {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { type DbMessages } from "../core/messages.js";
|
|
2
2
|
import type { PostgresTargetPort } from "./postgres-target.js";
|
|
3
3
|
import type { TransferSource } from "./sqlite-source.js";
|
|
4
|
-
import type { TransferTable } from "./types.js";
|
|
4
|
+
import type { TableCount, TransferTable } from "./types.js";
|
|
5
|
+
export type { TableCount } from "./types.js";
|
|
5
6
|
/**
|
|
6
7
|
* @file The COPY-mode engine (plan slice P0): which tables go, the target DDL, the psql script, and
|
|
7
8
|
* the target-state check. Vendor-blind: it knows "a Postgres database", never a provider.
|
|
@@ -34,10 +35,6 @@ import type { TransferTable } from "./types.js";
|
|
|
34
35
|
/** The schema the first site to copy into a database gets. */
|
|
35
36
|
import type { TransferNaming } from "./types.js";
|
|
36
37
|
import { type TransferPlanSource } from "./plan.js";
|
|
37
|
-
export interface TableCount {
|
|
38
|
-
readonly table: TransferTable;
|
|
39
|
-
readonly rows: number;
|
|
40
|
-
}
|
|
41
38
|
export declare class SourceSchemaMismatchError extends Error {
|
|
42
39
|
}
|
|
43
40
|
/**
|
|
@@ -3,6 +3,22 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { defaultDbMessages } from "../core/messages.js";
|
|
4
4
|
import { constraintSql, createTableSql, indexSql, qualified, quoteIdent, quoteLiteral, reseedIdentitySql } from "./internal-ddl.js";
|
|
5
5
|
import { planTransfer } from "./plan.js";
|
|
6
|
+
/** COPY text-format escapes for the characters that would otherwise end or split a field. */
|
|
7
|
+
const COPY_TEXT_ESCAPES = { "\\": "\\\\", "\n": "\\n", "\r": "\\r", "\t": "\\t" };
|
|
8
|
+
/** Drops trailing `_`; a scan rather than /_+$/, which backtracks quadratically. The transfer entry
|
|
9
|
+
* loads no other package (see loads-without-driver.test.ts), so core's trimChars is not used here. */
|
|
10
|
+
function trimTrailingUnderscores(text) {
|
|
11
|
+
let end = text.length;
|
|
12
|
+
while (end > 0 && text[end - 1] === "_")
|
|
13
|
+
end -= 1;
|
|
14
|
+
return text.slice(0, end);
|
|
15
|
+
}
|
|
16
|
+
/** A site's lowercase `_`-joined alphanumeric runs, with no leading or trailing `_`. */
|
|
17
|
+
function siteSlug(site) {
|
|
18
|
+
// Runs are collapsed first, so at most one `_` can lead.
|
|
19
|
+
const joined = site.toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
20
|
+
return trimTrailingUnderscores(joined.startsWith("_") ? joined.slice(1) : joined);
|
|
21
|
+
}
|
|
6
22
|
/** Postgres truncates identifiers past 63 bytes (NAMEDATALEN - 1). */
|
|
7
23
|
const MAX_IDENTIFIER_BYTES = 63;
|
|
8
24
|
function shortHash(text) {
|
|
@@ -18,7 +34,7 @@ function shortHash(text) {
|
|
|
18
34
|
*/
|
|
19
35
|
function siteSchemaNameInternal(site, naming) {
|
|
20
36
|
const SCHEMA_PREFIX = naming.schemaPrefix;
|
|
21
|
-
const slug = site
|
|
37
|
+
const slug = siteSlug(site);
|
|
22
38
|
const lossless = /^[A-Za-z0-9 ._-]*$/.test(site);
|
|
23
39
|
if (lossless && slug !== "" && SCHEMA_PREFIX.length + slug.length <= MAX_IDENTIFIER_BYTES)
|
|
24
40
|
return `${SCHEMA_PREFIX}${slug}`;
|
|
@@ -27,12 +43,13 @@ function siteSchemaNameInternal(site, naming) {
|
|
|
27
43
|
function withHash(site, slug, naming) {
|
|
28
44
|
const SCHEMA_PREFIX = naming.schemaPrefix;
|
|
29
45
|
const room = MAX_IDENTIFIER_BYTES - SCHEMA_PREFIX.length - 9;
|
|
30
|
-
const kept = slug.slice(0, room)
|
|
31
|
-
|
|
46
|
+
const kept = trimTrailingUnderscores(slug.slice(0, room));
|
|
47
|
+
const keptPart = kept === "" ? "" : kept + "_";
|
|
48
|
+
return `${SCHEMA_PREFIX}${keptPart}${shortHash(site)}`;
|
|
32
49
|
}
|
|
33
50
|
/** The schemas a site without a copy may take, in order. */
|
|
34
51
|
function schemaCandidates(site, naming) {
|
|
35
|
-
const slug = site
|
|
52
|
+
const slug = siteSlug(site);
|
|
36
53
|
return [...new Set([naming.defaultSchema, siteSchemaNameInternal(site, naming), withHash(site, slug, naming)])];
|
|
37
54
|
}
|
|
38
55
|
export class SourceSchemaMismatchError extends Error {
|
|
@@ -106,7 +123,7 @@ function copyField(value, table, column) {
|
|
|
106
123
|
if (typeof value === "number" || typeof value === "bigint")
|
|
107
124
|
return String(value);
|
|
108
125
|
if (typeof value === "string")
|
|
109
|
-
return value.replace(/[\\\n\r\t]/g, (ch) =>
|
|
126
|
+
return value.replace(/[\\\n\r\t]/g, (ch) => COPY_TEXT_ESCAPES[ch]);
|
|
110
127
|
if (Buffer.isBuffer(value) && column.sqlType === "bytea")
|
|
111
128
|
return `\\\\x${value.toString("hex")}`;
|
|
112
129
|
throw new SourceSchemaMismatchError(`'${table}.${column.name}' holds binary data, which its Postgres column does not accept`);
|
|
@@ -142,7 +159,7 @@ function guardSql(schema, site, TRANSFER_MARKER_TABLE, sqlTag) {
|
|
|
142
159
|
`END $${sqlTag}$;\n`);
|
|
143
160
|
}
|
|
144
161
|
function countCheckSql(schema, counts, sqlTag) {
|
|
145
|
-
const checks = counts.map(({ table, rows }) => `SELECT count(*) INTO n FROM ${qualified(schema, table.name)}; IF n <> ${rows} THEN RAISE EXCEPTION ${quoteLiteral(
|
|
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;`);
|
|
146
163
|
return `DO $${sqlTag}$ DECLARE n bigint; BEGIN ${checks.join(" ")} END $${sqlTag}$;\n`;
|
|
147
164
|
}
|
|
148
165
|
function markerSql(schema, marker, counts, naming) {
|
|
@@ -237,7 +254,7 @@ export async function runCopy(input, _optional = {}) {
|
|
|
237
254
|
const mismatch = new RegExp(`${COUNT_MISMATCH_SIGNAL} (\\S+)`).exec(result.error);
|
|
238
255
|
if (mismatch)
|
|
239
256
|
return { ok: false, code: "COUNT_MISMATCH", message: `the copy of '${mismatch[1]}' did not match, so the whole copy was thrown away. Any earlier copy is untouched.`, logDetail: result.error };
|
|
240
|
-
const where = result.copyTable ? ` while copying '${result.copyTable.replace(
|
|
257
|
+
const where = result.copyTable ? ` while copying '${result.copyTable.replace(schema + ".", "")}'` : "";
|
|
241
258
|
return { ok: false, code: "COPY_FAILED", message: `the destination refused the copy${where}, so the whole copy was thrown away. Any earlier copy is untouched.`, logDetail: result.error };
|
|
242
259
|
}
|
|
243
260
|
/** Human-readable schema naming preserves the original hash/63-byte collision rationale above. */
|
|
@@ -68,7 +68,10 @@ export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
|
|
|
68
68
|
*/
|
|
69
69
|
export function indexSql(schema, table) {
|
|
70
70
|
return table.indexes
|
|
71
|
-
.map((index) =>
|
|
71
|
+
.map((index) => {
|
|
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`;
|
|
74
|
+
})
|
|
72
75
|
.join("");
|
|
73
76
|
}
|
|
74
77
|
const REFERENTIAL_ACTIONS = new Set(["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"]);
|
|
@@ -115,7 +118,7 @@ export function constraintSql(schema, tables, unvalidatedTable, sqlTag = "transf
|
|
|
115
118
|
const pending = tables.flatMap((table) => constraintsOf(schema, table, byName));
|
|
116
119
|
const adds = pending.map(({ table, name, add }) => `ALTER TABLE ${qualified(schema, table)} ADD CONSTRAINT ${quoteIdent(name)} ${add} NOT VALID;\n`);
|
|
117
120
|
const validations = pending.map(({ table, name }) => ` BEGIN ALTER TABLE ${qualified(schema, table)} VALIDATE CONSTRAINT ${quoteIdent(name)};\n` +
|
|
118
|
-
` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral(
|
|
121
|
+
` EXCEPTION WHEN foreign_key_violation OR check_violation THEN INSERT INTO ${UNVALIDATED_TABLE} VALUES (${quoteLiteral(table + "." + name)}); END;\n`);
|
|
119
122
|
return (`CREATE TEMP TABLE ${quoteIdent(unvalidatedTable.split(".").at(-1))} (name text NOT NULL) ON COMMIT DROP;\n` +
|
|
120
123
|
adds.join("") +
|
|
121
124
|
(validations.length === 0 ? "" : `DO $${sqlTag}$ BEGIN\n${validations.join("")}END $${sqlTag}$;\n`));
|
package/dist/transfer/plan.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
/** Every physical source must account for every table before a copy can be planned. */
|
|
2
2
|
import type { TransferSource } from "./sqlite-source.js";
|
|
3
3
|
import type { SnapshotTablePlan } from "./table-catalog.js";
|
|
4
|
+
import type { TableCount } from "./types.js";
|
|
4
5
|
export interface TransferPlanSource extends SnapshotTablePlan {
|
|
5
6
|
readonly name: string;
|
|
6
7
|
readonly source: TransferSource;
|
|
7
8
|
/** Optional frozen counts from a prior plan; checked inside the destination transaction. */
|
|
8
|
-
readonly counts?: readonly
|
|
9
|
+
readonly counts?: readonly TableCount[];
|
|
9
10
|
}
|
|
10
11
|
export declare class IncompleteTransferPlanError extends Error {
|
|
11
12
|
readonly missing: readonly {
|
package/dist/transfer/plan.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export class IncompleteTransferPlanError extends Error {
|
|
2
2
|
missing;
|
|
3
3
|
constructor({ missing }, _optional = {}) {
|
|
4
|
-
super(`incomplete transfer plan: ${missing.map(entry =>
|
|
4
|
+
super(`incomplete transfer plan: ${missing.map(entry => entry.source + ": " + entry.table).join(", ")}`);
|
|
5
5
|
this.name = "IncompleteTransferPlanError";
|
|
6
6
|
this.missing = missing;
|
|
7
7
|
}
|
|
@@ -48,13 +48,20 @@ function environmentWithout(parent) {
|
|
|
48
48
|
}
|
|
49
49
|
/** Classifies copier failure codes; arbitrary psql text never reaches public errors or logs.
|
|
50
50
|
* @complexity O(n) time/space in stderr length. */
|
|
51
|
+
/** Only the transfer's own signals pass through; any other psql text stays in the log. */
|
|
52
|
+
function publicFailure({ message, countedTable }) {
|
|
53
|
+
if (message === FOREIGN_SCHEMA_SIGNAL)
|
|
54
|
+
return FOREIGN_SCHEMA_SIGNAL;
|
|
55
|
+
if (message.startsWith(`${COUNT_MISMATCH_SIGNAL} `))
|
|
56
|
+
return `${COUNT_MISMATCH_SIGNAL} ${countedTable ?? "[redacted]"}`;
|
|
57
|
+
return "psql request failed";
|
|
58
|
+
}
|
|
51
59
|
function failureFrom({ stderr }, _options = {}) {
|
|
52
60
|
const lines = stderr.split("\n").map((line) => line.trim()).filter((line) => line !== "");
|
|
53
61
|
const line = lines.find((candidate) => /\bERROR:|FATAL:|could not|timeout/i.test(candidate)) ?? lines[0] ?? "psql failed without a message";
|
|
54
62
|
const message = line.replace(/^psql:[^ ]*: /, "").replace(/^ERROR:\s*/, "");
|
|
55
63
|
const countMismatch = new RegExp(`^${COUNT_MISMATCH_SIGNAL} ([A-Za-z_][A-Za-z0-9_]{0,62})$`).exec(message);
|
|
56
|
-
const error = message
|
|
57
|
-
: message.startsWith(`${COUNT_MISMATCH_SIGNAL} `) ? `${COUNT_MISMATCH_SIGNAL} ${countMismatch?.[1] ?? "[redacted]"}` : "psql request failed";
|
|
64
|
+
const error = publicFailure({ message, countedTable: countMismatch?.[1] });
|
|
58
65
|
const copyMatch = /\bCOPY ([A-Za-z0-9_."]+), line \d+/.exec(stderr);
|
|
59
66
|
const copyTable = copyMatch ? copyMatch[1].replace(/"/g, "") : undefined;
|
|
60
67
|
return copyTable === undefined ? { ok: false, error } : { ok: false, error, copyTable };
|
|
@@ -89,20 +89,25 @@ export function planSnapshotTables({ source, policy }, _optional = {}) {
|
|
|
89
89
|
const names = source.tableNames();
|
|
90
90
|
const layouts = new Map(names.map((name) => [name, source.layout(name)]));
|
|
91
91
|
const virtualTables = names.filter((name) => layouts.get(name)?.virtual === true);
|
|
92
|
-
|
|
92
|
+
// Excluded tables are reported; core and layout-less tables are skipped silently.
|
|
93
|
+
const decide = (name) => {
|
|
93
94
|
const excluded = policy.excludedTables[name];
|
|
94
|
-
if (excluded !== undefined)
|
|
95
|
-
|
|
96
|
-
continue;
|
|
97
|
-
}
|
|
95
|
+
if (excluded !== undefined)
|
|
96
|
+
return { reason: excluded };
|
|
98
97
|
const layout = layouts.get(name);
|
|
99
98
|
if (core.has(name) || layout === null || layout === undefined)
|
|
100
|
-
|
|
99
|
+
return null;
|
|
101
100
|
const reason = reasonToLeaveOut(name, layout, derived, virtualTables, policy);
|
|
102
|
-
|
|
103
|
-
|
|
101
|
+
return reason === null ? { table: introspectedTable({ name, layout }) } : { reason };
|
|
102
|
+
};
|
|
103
|
+
for (const name of names) {
|
|
104
|
+
const decision = decide(name);
|
|
105
|
+
if (decision === null)
|
|
106
|
+
continue;
|
|
107
|
+
if ("reason" in decision)
|
|
108
|
+
leftOut.push({ table: name, reason: decision.reason });
|
|
104
109
|
else
|
|
105
|
-
|
|
110
|
+
tables.push(decision.table);
|
|
106
111
|
}
|
|
107
112
|
return { tables, leftOut };
|
|
108
113
|
}
|
package/dist/transfer/types.d.ts
CHANGED
|
@@ -40,5 +40,9 @@ export interface TransferTable {
|
|
|
40
40
|
readonly foreignKeys: readonly TransferForeignKey[];
|
|
41
41
|
readonly checks: readonly TransferCheck[];
|
|
42
42
|
}
|
|
43
|
+
export interface TableCount {
|
|
44
|
+
readonly table: TransferTable;
|
|
45
|
+
readonly rows: number;
|
|
46
|
+
}
|
|
43
47
|
export type { TransferNaming } from '../core/transfer-naming.js';
|
|
44
48
|
//# sourceMappingURL=types.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/db",
|
|
3
|
-
"version": "0.6.15
|
|
3
|
+
"version": "0.6.15",
|
|
4
4
|
"description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"./tools": "transfer"
|
|
21
21
|
},
|
|
22
22
|
"shared": [
|
|
23
|
+
"src/shared/ddl.adapter.ts",
|
|
23
24
|
"src/kernel/dialect.ts",
|
|
24
25
|
"src/kernel/index.ts",
|
|
25
26
|
"src/kernel/kernel-core.ts",
|
|
@@ -202,14 +203,14 @@
|
|
|
202
203
|
"registry": "https://registry.npmjs.org"
|
|
203
204
|
},
|
|
204
205
|
"dependencies": {
|
|
205
|
-
"@jini-ai/core": "^0.6.15
|
|
206
|
+
"@jini-ai/core": "^0.6.15"
|
|
206
207
|
},
|
|
207
208
|
"peerDependencies": {
|
|
208
209
|
"kysely": "^0.29.6",
|
|
209
210
|
"better-sqlite3": "^13.0.0",
|
|
210
211
|
"@electric-sql/pglite": "0.5.8",
|
|
211
212
|
"pg": "^8.23.0",
|
|
212
|
-
"@jini-ai/platform": "^0.6.
|
|
213
|
+
"@jini-ai/platform": "^0.6.10"
|
|
213
214
|
},
|
|
214
215
|
"peerDependenciesMeta": {
|
|
215
216
|
"better-sqlite3": {
|
|
@@ -236,8 +237,8 @@
|
|
|
236
237
|
"better-sqlite3": "13.0.3",
|
|
237
238
|
"kysely": "0.29.6",
|
|
238
239
|
"pg": "8.23.0",
|
|
239
|
-
"@jini-ai/
|
|
240
|
-
"@jini-ai/
|
|
240
|
+
"@jini-ai/core": "0.6.15",
|
|
241
|
+
"@jini-ai/platform": "0.6.15"
|
|
241
242
|
},
|
|
242
243
|
"scripts": {
|
|
243
244
|
"build": "tsc -p tsconfig.build.json",
|