@jini-ai/db 0.7.3-next.2 → 0.7.4
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 +7 -0
- package/README.md +66 -2
- package/dist/core/ports.d.ts +2 -2
- package/dist/core/ports.js +2 -2
- package/dist/data-modules/data-module.d.ts +2 -46
- package/dist/data-modules/plugin-identity.d.ts +2 -11
- package/dist/data-modules/snapshot.d.ts +5 -3
- package/dist/data-modules/snapshot.js +5 -3
- package/dist/events/change-set-repo.sql.d.ts +18 -5
- package/dist/events/change-set-repo.sql.js +25 -8
- package/dist/events/index.d.ts +1 -1
- package/dist/events/outbox-repo.sql.d.ts +26 -1
- package/dist/events/outbox-repo.sql.js +36 -2
- package/dist/events/repo.rows.d.ts +22 -4
- package/dist/events/repo.rows.js +32 -4
- package/dist/kernel/idle-turn.d.ts +62 -0
- package/dist/kernel/idle-turn.js +32 -0
- package/dist/kernel/index.d.ts +1 -0
- package/dist/kernel/index.js +1 -0
- package/dist/kernel/kernel-core.js +28 -0
- package/dist/kernel/schema-scope.js +2 -0
- package/dist/kernel/sqlite/driver.js +2 -0
- package/dist/kernel/sqlite/index.d.ts +1 -1
- package/dist/kernel/sqlite/index.js +1 -1
- package/dist/kernel/sqlite/ops.d.ts +61 -0
- package/dist/kernel/sqlite/ops.js +82 -0
- package/dist/kernel/turn-lock.d.ts +2 -0
- package/dist/kernel/turn-lock.js +7 -0
- package/dist/migrate/runner.d.ts +3 -3
- package/dist/migrate/runner.js +4 -1
- package/dist/owner-store/index.js +1 -1
- package/dist/pglite/copy-source.d.ts +45 -0
- package/dist/pglite/copy-source.js +36 -0
- package/dist/pglite/index.d.ts +1 -0
- package/dist/pglite/index.js +1 -0
- package/dist/react/recovery/Recovery.d.ts +205 -0
- package/dist/react/recovery/Recovery.js +141 -0
- package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
- package/dist/react/recovery/Recovery.restore-steps.js +71 -0
- package/dist/recovery/agent-tools.d.ts +33 -0
- package/dist/recovery/agent-tools.js +166 -0
- package/dist/recovery/drift.d.ts +47 -0
- package/dist/recovery/drift.js +51 -0
- package/dist/recovery/journal-kernel.d.ts +80 -0
- package/dist/recovery/journal-kernel.js +40 -0
- package/dist/recovery/journal-repo.sql.d.ts +154 -0
- package/dist/recovery/journal-repo.sql.js +303 -0
- package/dist/recovery/journal-schema.d.ts +37 -0
- package/dist/recovery/journal-schema.js +110 -0
- package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
- package/dist/recovery/migrate-forward-hooks.js +3 -3
- package/dist/recovery/operation-lock.d.ts +2 -17
- package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
- package/dist/recovery/reconcile-interrupted-migration.js +0 -30
- package/dist/recovery/restore-hooks.d.ts +4 -0
- package/dist/recovery/restore-hooks.js +1 -1
- package/dist/recovery/tool-registrations.d.ts +175 -0
- package/dist/recovery/tool-registrations.js +295 -0
- package/dist/site/repo.memory.d.ts +149 -0
- package/dist/site/repo.memory.js +162 -0
- package/dist/site/tool-registrations.d.ts +130 -0
- package/dist/site/tool-registrations.js +184 -0
- package/dist/sqlite/backup-policy.d.ts +14 -0
- package/dist/sqlite/backup-policy.js +47 -3
- package/dist/sqlite/compaction-steps.d.ts +43 -0
- package/dist/sqlite/compaction-steps.js +74 -0
- package/dist/sqlite/compaction.d.ts +63 -0
- package/dist/sqlite/compaction.js +263 -0
- package/dist/sqlite/db-ops.js +10 -11
- package/dist/sqlite/index.d.ts +2 -1
- package/dist/sqlite/index.js +2 -1
- package/dist/sqlite/open.d.ts +2 -1
- package/dist/sqlite/open.js +14 -4
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +2 -0
- package/dist/tools/plan-store.d.ts +1 -1
- package/dist/tools/plan-store.js +10 -6
- package/dist/tools/read-tools.d.ts +1 -1
- package/dist/tools/site-db-messages.d.ts +10 -0
- package/dist/tools/site-db-messages.js +23 -0
- package/dist/tools/site-transfer-messages.d.ts +9 -0
- package/dist/tools/site-transfer-messages.js +20 -0
- package/dist/transfer/confirmation-ui.d.ts +19 -0
- package/dist/transfer/confirmation-ui.js +39 -0
- package/dist/transfer/copy-engine.js +11 -11
- package/dist/transfer/copy-order.js +1 -3
- package/dist/transfer/destination-store.d.ts +83 -0
- package/dist/transfer/destination-store.js +82 -0
- package/dist/transfer/index.d.ts +2 -0
- package/dist/transfer/index.js +2 -0
- package/dist/transfer/internal-ddl.d.ts +6 -2
- package/dist/transfer/internal-ddl.js +15 -15
- package/dist/transfer/postgres-ddl.js +2 -2
- package/dist/transfer/schema-catalog.d.ts +148 -0
- package/dist/transfer/schema-catalog.js +141 -0
- package/dist/transfer/sqlite-backup.d.ts +27 -0
- package/dist/transfer/sqlite-backup.js +31 -0
- package/dist/transfer/table-catalog.js +1 -0
- package/dist/watermark/kernel.d.ts +64 -0
- package/dist/watermark/kernel.js +45 -0
- package/package.json +107 -9
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file `withIdleTurn`: an exclusive, NON-queuing turn on a one-connection kernel (better-sqlite3,
|
|
3
|
+
* PGlite), taken only while the kernel is idle.
|
|
4
|
+
*
|
|
5
|
+
* Why: every caller of such a kernel shares ONE connection, and a kernel transaction is just a
|
|
6
|
+
* `BEGIN` on it. Maintenance that must not land inside someone else's transaction (a bounded
|
|
7
|
+
* `PRAGMA incremental_vacuum`, for instance) needs the file's turn lock to itself — but serving
|
|
8
|
+
* traffic must never queue behind maintenance, so admission refuses instead of waiting.
|
|
9
|
+
*
|
|
10
|
+
* Invariants: the body runs only while this process holds the file's turn lock exclusively (I1);
|
|
11
|
+
* admission never waits and never overtakes a queued caller (I2); it refuses inside a kernel scope,
|
|
12
|
+
* with a foreign transaction open, or on a kernel without a turn lock (I3); kernel calls on the same
|
|
13
|
+
* file inside the body throw (I4); the lock is released even when the body throws, and the body's
|
|
14
|
+
* error is never caught (I5). Never call it from a migration: the runner's transaction scope makes
|
|
15
|
+
* it refuse with "in-scope" (I6).
|
|
16
|
+
*/
|
|
17
|
+
import type { KyselyKernel } from "./port.js";
|
|
18
|
+
/**
|
|
19
|
+
* Why a turn was not taken. "busy": kernel work holds or waits for the lock — it clears by itself.
|
|
20
|
+
* "in-scope": the caller is inside a kernel run/transaction (or holds the lock through another
|
|
21
|
+
* kernel). "transaction-open": the shared connection is in a transaction the kernel does not own.
|
|
22
|
+
* "unsupported": a multi-connection kernel, or one not built by `buildKernel`.
|
|
23
|
+
*/
|
|
24
|
+
export type IdleTurnRefusal = "busy" | "in-scope" | "transaction-open" | "unsupported";
|
|
25
|
+
export type IdleTurnResult<T> = {
|
|
26
|
+
readonly ran: true;
|
|
27
|
+
readonly value: T;
|
|
28
|
+
} | {
|
|
29
|
+
readonly ran: false;
|
|
30
|
+
readonly reason: IdleTurnRefusal;
|
|
31
|
+
};
|
|
32
|
+
/** Private per-kernel control, registered by `buildKernel` (the same pattern as `registerOwnedTransaction`). */
|
|
33
|
+
export interface IdleTurnControl {
|
|
34
|
+
/** Synchronous admission plus exclusive take: the release function, or the refusal. */
|
|
35
|
+
tryTake(): {
|
|
36
|
+
readonly release: () => void;
|
|
37
|
+
} | {
|
|
38
|
+
readonly refusal: IdleTurnRefusal;
|
|
39
|
+
};
|
|
40
|
+
/** Runs `body` with the lock marked held for this async chain, so nested kernel calls throw (I4). */
|
|
41
|
+
runHeld<T>(body: () => Promise<T>): Promise<T>;
|
|
42
|
+
}
|
|
43
|
+
/** Records the control of a kernel built by `buildKernel`. Not exported from the package. */
|
|
44
|
+
export declare function registerIdleTurn({ kernel, control }: {
|
|
45
|
+
kernel: KyselyKernel<unknown>;
|
|
46
|
+
control: IdleTurnControl;
|
|
47
|
+
}, _optional?: Record<string, never>): void;
|
|
48
|
+
/** A wrapper kernel (schema-scoped, owned connection) shares its source's lock and control. */
|
|
49
|
+
export declare function inheritIdleTurn({ from, to }: {
|
|
50
|
+
from: KyselyKernel<unknown>;
|
|
51
|
+
to: KyselyKernel<unknown>;
|
|
52
|
+
}, _optional?: Record<string, never>): void;
|
|
53
|
+
/**
|
|
54
|
+
* Run `body` in an exclusive turn on a one-connection kernel, only if the kernel is idle right now.
|
|
55
|
+
* Never queues (I2), never joins a transaction (I3), always releases (I5).
|
|
56
|
+
* @complexity O(1) admission plus the body.
|
|
57
|
+
*/
|
|
58
|
+
export declare function withIdleTurn<T, DB = unknown>({ kernel, body }: {
|
|
59
|
+
kernel: KyselyKernel<DB>;
|
|
60
|
+
body: () => Promise<T>;
|
|
61
|
+
}, _optional?: Record<string, never>): Promise<IdleTurnResult<T>>;
|
|
62
|
+
//# sourceMappingURL=idle-turn.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const controls = new WeakMap();
|
|
2
|
+
/** Records the control of a kernel built by `buildKernel`. Not exported from the package. */
|
|
3
|
+
export function registerIdleTurn({ kernel, control }, _optional = {}) {
|
|
4
|
+
controls.set(kernel, control);
|
|
5
|
+
}
|
|
6
|
+
/** A wrapper kernel (schema-scoped, owned connection) shares its source's lock and control. */
|
|
7
|
+
export function inheritIdleTurn({ from, to }, _optional = {}) {
|
|
8
|
+
const control = controls.get(from);
|
|
9
|
+
if (control !== undefined)
|
|
10
|
+
controls.set(to, control);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Run `body` in an exclusive turn on a one-connection kernel, only if the kernel is idle right now.
|
|
14
|
+
* Never queues (I2), never joins a transaction (I3), always releases (I5).
|
|
15
|
+
* @complexity O(1) admission plus the body.
|
|
16
|
+
*/
|
|
17
|
+
export async function withIdleTurn({ kernel, body }, _optional = {}) {
|
|
18
|
+
const control = controls.get(kernel);
|
|
19
|
+
if (control === undefined)
|
|
20
|
+
return { ran: false, reason: "unsupported" };
|
|
21
|
+
await kernel.ready;
|
|
22
|
+
const taken = control.tryTake();
|
|
23
|
+
if ("refusal" in taken)
|
|
24
|
+
return { ran: false, reason: taken.refusal };
|
|
25
|
+
try {
|
|
26
|
+
return { ran: true, value: await control.runHeld(body) };
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
taken.release();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=idle-turn.js.map
|
package/dist/kernel/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
export type { DbTransport, KyselyKernel } from "./port.js";
|
|
7
7
|
export { buildKernel, type KernelDriver } from "./kernel-core.js";
|
|
8
8
|
export { TurnLock } from "./turn-lock.js";
|
|
9
|
+
export { withIdleTurn, type IdleTurnRefusal, type IdleTurnResult } from "./idle-turn.js";
|
|
9
10
|
export { autoIdColumnSql, checkpointWal, type ColumnAffinity, columnTypeSql, type IndexInfo, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, } from "./dialect.js";
|
|
10
11
|
export { scopeToSchema } from "./schema-scope.js";
|
|
11
12
|
export { databaseFile, readSchemaShape, type SchemaShape, type TableShape } from "./schema-shape.js";
|
package/dist/kernel/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { buildKernel } from "./kernel-core.js";
|
|
2
2
|
export { TurnLock } from "./turn-lock.js";
|
|
3
|
+
export { withIdleTurn } from "./idle-turn.js";
|
|
3
4
|
export { autoIdColumnSql, checkpointWal, columnTypeSql, jsonScalarEquals, jsonSet, jsonSortKey, jsonText, listColumns, listIndexes, listTables, nowIso, tableExists, } from "./dialect.js";
|
|
4
5
|
export { scopeToSchema } from "./schema-scope.js";
|
|
5
6
|
export { databaseFile, readSchemaShape } from "./schema-shape.js";
|
|
@@ -4,6 +4,7 @@ import {} from "./port.js";
|
|
|
4
4
|
import { UnsupportedCapabilityError, } from "@jini-ai/core/contracts/storage";
|
|
5
5
|
import { TurnLock } from "./turn-lock.js";
|
|
6
6
|
import { registerOwnedTransaction } from "./owned-transaction.js";
|
|
7
|
+
import { registerIdleTurn } from "./idle-turn.js";
|
|
7
8
|
/** The turn locks the caller's async context holds, across every kernel in the process. */
|
|
8
9
|
const heldLocks = new AsyncLocalStorage();
|
|
9
10
|
/**
|
|
@@ -121,7 +122,34 @@ export function buildKernel({ driver }, _optional = {}) {
|
|
|
121
122
|
assertAvailable: () => assertOwnedAvailable({ rt }),
|
|
122
123
|
transaction: (work, optional = {}) => transaction(work, optional),
|
|
123
124
|
} });
|
|
125
|
+
registerIdleTurn({ kernel: kernel, control: idleTurnControl({ rt }) });
|
|
124
126
|
registerKernelSessionDatabase({ kernel: kernel, database: driver.base, ...(driver.poolMax === undefined ? {} : { poolMax: driver.poolMax }) });
|
|
125
127
|
return kernel;
|
|
126
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Admission for `withIdleTurn`. The turn lock is checked BEFORE the transaction state: an owned
|
|
131
|
+
* transaction holds the lock, so it is ordinary kernel work that clears by itself and answers
|
|
132
|
+
* "busy" (invariant I2). "transaction-open" is left for a transaction the kernel does not own —
|
|
133
|
+
* a raw `BEGIN` on the shared handle — which only the connection itself can reveal. A refusal
|
|
134
|
+
* after the lock was taken releases it before returning.
|
|
135
|
+
*/
|
|
136
|
+
function idleTurnControl({ rt }) {
|
|
137
|
+
return {
|
|
138
|
+
tryTake() {
|
|
139
|
+
const { lock, scope } = rt;
|
|
140
|
+
if (lock === undefined)
|
|
141
|
+
return { refusal: "unsupported" };
|
|
142
|
+
if (scope.getStore() !== undefined || heldLocks.getStore()?.has(lock) === true)
|
|
143
|
+
return { refusal: "in-scope" };
|
|
144
|
+
if (!lock.tryAcquire("exclusive"))
|
|
145
|
+
return { refusal: "busy" };
|
|
146
|
+
if (rt.own.transactions > 0 || rt.driver.foreignTransactionOpen?.() === true) {
|
|
147
|
+
lock.release("exclusive");
|
|
148
|
+
return { refusal: "transaction-open" };
|
|
149
|
+
}
|
|
150
|
+
return { release: () => lock.release("exclusive") };
|
|
151
|
+
},
|
|
152
|
+
runHeld: (body) => heldLocks.run(new Set([...(heldLocks.getStore() ?? []), ...(rt.lock ? [rt.lock] : [])]), body),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
127
155
|
//# sourceMappingURL=kernel-core.js.map
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { inheritKernelSessionDatabase } from "./session-lock.js";
|
|
2
2
|
import { inheritOwnedTransaction } from "./owned-transaction.js";
|
|
3
|
+
import { inheritIdleTurn } from "./idle-turn.js";
|
|
3
4
|
/**
|
|
4
5
|
* @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
|
|
5
6
|
* `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
|
|
@@ -19,6 +20,7 @@ export function scopeToSchema({ kernel, schema }, _optional = {}) {
|
|
|
19
20
|
run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
|
|
20
21
|
};
|
|
21
22
|
inheritOwnedTransaction({ from: kernel, to: scoped });
|
|
23
|
+
inheritIdleTurn({ from: kernel, to: scoped });
|
|
22
24
|
inheritKernelSessionDatabase({ from: kernel, to: scoped });
|
|
23
25
|
return scoped;
|
|
24
26
|
}
|
|
@@ -4,6 +4,7 @@ import { Kysely, SqliteDialect } from "kysely";
|
|
|
4
4
|
import { buildKernel, TurnLock } from "../index.js";
|
|
5
5
|
import { checkedClients, checkedStates, connectionsByKernel, rawKernelClients } from "../../sqlite/checked-state.js";
|
|
6
6
|
import { inheritOwnedTransaction } from "../owned-transaction.js";
|
|
7
|
+
import { inheritIdleTurn } from "../idle-turn.js";
|
|
7
8
|
const kernels = new WeakMap();
|
|
8
9
|
/** One turn lock per database FILE, shared by every connection to it in this process. */
|
|
9
10
|
const fileTurnLocks = new Map();
|
|
@@ -135,6 +136,7 @@ export function openSqliteFileKernel(required, optional = {}) {
|
|
|
135
136
|
};
|
|
136
137
|
connectionsByKernel.set(owned, client);
|
|
137
138
|
inheritOwnedTransaction({ from: kernel, to: owned });
|
|
139
|
+
inheritIdleTurn({ from: kernel, to: owned });
|
|
138
140
|
return owned;
|
|
139
141
|
}
|
|
140
142
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Kysely's SQLite binding and kernel storage operations. */
|
|
2
2
|
export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf, type SqliteConnectionSource, type SqliteKernel } from "./driver.js";
|
|
3
|
-
export { sqliteOps, copySqliteInto } from "./ops.js";
|
|
3
|
+
export { sqliteOps, copySqliteInto, readSqliteMigrationLedger, sqliteHasColumn, readSqliteTextColumn, quickCheckSqlite, type SqliteReadClient, type SqliteReadonlyOpener, type SqliteMigrationLedgerEntry, type SqliteQuickCheckSource } from "./ops.js";
|
|
4
4
|
export { sqliteForeignKeyCheckedTransaction, sqliteSchemaObjects, sqliteTableExtendedInfo, sqliteTableInfo, type SqliteExtendedTableColumn, type SqliteForeignKeyViolation, type SqliteSchemaObject, type SqliteTableColumn } from "./sqlite-only.js";
|
|
5
5
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Kysely's SQLite binding and kernel storage operations. */
|
|
2
2
|
export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf } from "./driver.js";
|
|
3
|
-
export { sqliteOps, copySqliteInto } from "./ops.js";
|
|
3
|
+
export { sqliteOps, copySqliteInto, readSqliteMigrationLedger, sqliteHasColumn, readSqliteTextColumn, quickCheckSqlite } from "./ops.js";
|
|
4
4
|
export { sqliteForeignKeyCheckedTransaction, sqliteSchemaObjects, sqliteTableExtendedInfo, sqliteTableInfo } from "./sqlite-only.js";
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,65 @@
|
|
|
1
1
|
import { type KyselyKernel, type StorageOps } from "../index.js";
|
|
2
|
+
/** Minimal borrowed synchronous read handle; the caller keeps ownership. */
|
|
3
|
+
export interface SqliteReadClient {
|
|
4
|
+
prepare(source: string): {
|
|
5
|
+
all(...parameters: unknown[]): unknown[];
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
/** Host-owned driver acquisition; these operations never create a missing database. */
|
|
9
|
+
export type SqliteReadonlyOpener = (path: string, options: {
|
|
10
|
+
readonly: true;
|
|
11
|
+
fileMustExist: true;
|
|
12
|
+
}) => SqliteReadClient & {
|
|
13
|
+
close(): unknown;
|
|
14
|
+
};
|
|
15
|
+
export interface SqliteMigrationLedgerEntry {
|
|
16
|
+
id: string;
|
|
17
|
+
checksum: string;
|
|
18
|
+
}
|
|
19
|
+
/** Read a stopped file's ledger in applied_at, id order; validate every id/checksum and close.
|
|
20
|
+
* The host decides whether the returned steps belong to its migration history.
|
|
21
|
+
* @throws A redacted error on open/read/close failure or a malformed ledger row.
|
|
22
|
+
* @complexity O(n log n) database ordering and O(n) result storage.
|
|
23
|
+
*/
|
|
24
|
+
export declare function readSqliteMigrationLedger({ open, path, table }: {
|
|
25
|
+
open: SqliteReadonlyOpener;
|
|
26
|
+
path: string;
|
|
27
|
+
table: string;
|
|
28
|
+
}, _optional?: {}): SqliteMigrationLedgerEntry[];
|
|
29
|
+
/** Synchronous column-presence probe on a borrowed handle; names are bound as values.
|
|
30
|
+
* @throws A redacted error on read failure. A missing table/column returns false.
|
|
31
|
+
* @complexity O(columns) catalog scan; no writes or connection lifecycle changes.
|
|
32
|
+
*/
|
|
33
|
+
export declare function sqliteHasColumn({ client, table, column }: {
|
|
34
|
+
client: SqliteReadClient;
|
|
35
|
+
table: string;
|
|
36
|
+
column: string;
|
|
37
|
+
}, _optional?: {}): boolean;
|
|
38
|
+
/** Project a text column on a borrowed handle, preserving duplicates and empty strings.
|
|
39
|
+
* Each name is quoted as one identifier, never a SQL fragment. Hosts filter empty references.
|
|
40
|
+
* @throws A redacted error on missing tables/columns, non-text values or read failure.
|
|
41
|
+
* @complexity O(rows) time and result storage. No ordering is promised.
|
|
42
|
+
*/
|
|
43
|
+
export declare function readSqliteTextColumn({ client, table, column }: {
|
|
44
|
+
client: SqliteReadClient;
|
|
45
|
+
table: string;
|
|
46
|
+
column: string;
|
|
47
|
+
}, _optional?: {}): string[];
|
|
48
|
+
/** A borrowed handle, or an owned read-only file opened and closed for this check. */
|
|
49
|
+
export type SqliteQuickCheckSource = {
|
|
50
|
+
client: SqliteReadClient;
|
|
51
|
+
} | {
|
|
52
|
+
open: SqliteReadonlyOpener;
|
|
53
|
+
path: string;
|
|
54
|
+
};
|
|
55
|
+
/** True only for SQLite's single exact 'ok' result. The optional limit bounds reported errors.
|
|
56
|
+
* Borrowed handles stay open; file sources use readonly + fileMustExist and always close.
|
|
57
|
+
* @throws A redacted error on open/read/close failure or an invalid limit. Hosts map refusals.
|
|
58
|
+
* @complexity O(database pages) SQLite work, O(reported errors) result storage.
|
|
59
|
+
*/
|
|
60
|
+
export declare function quickCheckSqlite(source: SqliteQuickCheckSource, { maxErrors }?: {
|
|
61
|
+
maxErrors?: number;
|
|
62
|
+
}): boolean;
|
|
2
63
|
/** Synchronous WAL-safe snapshot for admission code that must commit under a synchronous lock.
|
|
3
64
|
* Accepts either the host's SQLite client or Node's built-in DatabaseSync; the caller owns it.
|
|
4
65
|
* @throws SQLite errors, including an existing destination or an active transaction.
|
|
@@ -1,5 +1,87 @@
|
|
|
1
1
|
import { outsideTransactionOf, StorageOpError } from "../index.js";
|
|
2
2
|
import { sqliteConnectionOf } from "./driver.js";
|
|
3
|
+
function sqliteIdentifier({ name }, _optional = {}) {
|
|
4
|
+
if (name.length === 0 || name.includes("\0"))
|
|
5
|
+
throw new Error("A SQLite identifier must be non-empty and contain no null characters.");
|
|
6
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
7
|
+
}
|
|
8
|
+
function sqliteRow({ value }, _optional = {}) {
|
|
9
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
10
|
+
}
|
|
11
|
+
function readRows({ client, statement }, { parameters = [] } = {}) {
|
|
12
|
+
try {
|
|
13
|
+
return client.prepare(statement).all(...parameters);
|
|
14
|
+
}
|
|
15
|
+
// Driver diagnostics may contain file paths or row contents. Hosts supply their own refusal.
|
|
16
|
+
catch {
|
|
17
|
+
throw new Error("The SQLite database could not be read.");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function readOwnedRows({ open, path, statement }, _optional = {}) {
|
|
21
|
+
try {
|
|
22
|
+
const client = open(path, { readonly: true, fileMustExist: true });
|
|
23
|
+
try {
|
|
24
|
+
return readRows({ client, statement });
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
client.close();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error("The SQLite database could not be read.");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Read a stopped file's ledger in applied_at, id order; validate every id/checksum and close.
|
|
35
|
+
* The host decides whether the returned steps belong to its migration history.
|
|
36
|
+
* @throws A redacted error on open/read/close failure or a malformed ledger row.
|
|
37
|
+
* @complexity O(n log n) database ordering and O(n) result storage.
|
|
38
|
+
*/
|
|
39
|
+
export function readSqliteMigrationLedger({ open, path, table }, _optional = {}) {
|
|
40
|
+
const statement = `SELECT id, checksum FROM ${sqliteIdentifier({ name: table })} ORDER BY applied_at, id`;
|
|
41
|
+
return readOwnedRows({ open, path, statement }).map(row => {
|
|
42
|
+
const value = sqliteRow({ value: row });
|
|
43
|
+
if (typeof value?.id !== "string" || typeof value.checksum !== "string") {
|
|
44
|
+
throw new Error("The SQLite migration ledger contains an invalid row.");
|
|
45
|
+
}
|
|
46
|
+
return { id: value.id, checksum: value.checksum };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** Synchronous column-presence probe on a borrowed handle; names are bound as values.
|
|
50
|
+
* @throws A redacted error on read failure. A missing table/column returns false.
|
|
51
|
+
* @complexity O(columns) catalog scan; no writes or connection lifecycle changes.
|
|
52
|
+
*/
|
|
53
|
+
export function sqliteHasColumn({ client, table, column }, _optional = {}) {
|
|
54
|
+
const statement = "SELECT 1 FROM pragma_table_info(?) WHERE name = ?";
|
|
55
|
+
return readRows({ client, statement }, { parameters: [table, column] }).length > 0;
|
|
56
|
+
}
|
|
57
|
+
/** Project a text column on a borrowed handle, preserving duplicates and empty strings.
|
|
58
|
+
* Each name is quoted as one identifier, never a SQL fragment. Hosts filter empty references.
|
|
59
|
+
* @throws A redacted error on missing tables/columns, non-text values or read failure.
|
|
60
|
+
* @complexity O(rows) time and result storage. No ordering is promised.
|
|
61
|
+
*/
|
|
62
|
+
export function readSqliteTextColumn({ client, table, column }, _optional = {}) {
|
|
63
|
+
// Qualifying the column prevents SQLite's legacy double-quoted-string fallback for a typo.
|
|
64
|
+
const statement = `SELECT source.${sqliteIdentifier({ name: column })} AS value FROM ${sqliteIdentifier({ name: table })} AS source`;
|
|
65
|
+
return readRows({ client, statement }).map(row => {
|
|
66
|
+
const value = sqliteRow({ value: row });
|
|
67
|
+
if (typeof value?.value !== "string")
|
|
68
|
+
throw new Error("The SQLite text column contains an invalid value.");
|
|
69
|
+
return value.value;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** True only for SQLite's single exact 'ok' result. The optional limit bounds reported errors.
|
|
73
|
+
* Borrowed handles stay open; file sources use readonly + fileMustExist and always close.
|
|
74
|
+
* @throws A redacted error on open/read/close failure or an invalid limit. Hosts map refusals.
|
|
75
|
+
* @complexity O(database pages) SQLite work, O(reported errors) result storage.
|
|
76
|
+
*/
|
|
77
|
+
export function quickCheckSqlite(source, { maxErrors } = {}) {
|
|
78
|
+
if (maxErrors !== undefined && (!Number.isInteger(maxErrors) || maxErrors < 1 || maxErrors > 2_147_483_647)) {
|
|
79
|
+
throw new Error("The SQLite quick-check error limit must be a positive 32-bit integer.");
|
|
80
|
+
}
|
|
81
|
+
const statement = maxErrors === undefined ? "PRAGMA quick_check" : `PRAGMA quick_check(${maxErrors})`;
|
|
82
|
+
const rows = "client" in source ? readRows({ client: source.client, statement }) : readOwnedRows({ ...source, statement });
|
|
83
|
+
return rows.length === 1 && sqliteRow({ value: rows[0] })?.quick_check === "ok";
|
|
84
|
+
}
|
|
3
85
|
/** Synchronous WAL-safe snapshot for admission code that must commit under a synchronous lock.
|
|
4
86
|
* Accepts either the host's SQLite client or Node's built-in DatabaseSync; the caller owns it.
|
|
5
87
|
* @throws SQLite errors, including an existing destination or an active transaction.
|
|
@@ -13,6 +13,8 @@ export declare class TurnLock {
|
|
|
13
13
|
private exclusive;
|
|
14
14
|
private readonly waiting;
|
|
15
15
|
acquire(kind: Kind): Promise<void>;
|
|
16
|
+
/** Take the lock only if it is free AND nobody is queued; never waits, so queued callers are never overtaken. O(1). */
|
|
17
|
+
tryAcquire(kind: Kind): boolean;
|
|
16
18
|
release(kind: Kind): void;
|
|
17
19
|
private fits;
|
|
18
20
|
private take;
|
package/dist/kernel/turn-lock.js
CHANGED
|
@@ -18,6 +18,13 @@ export class TurnLock {
|
|
|
18
18
|
}
|
|
19
19
|
return new Promise((grant) => this.waiting.push({ kind, grant }));
|
|
20
20
|
}
|
|
21
|
+
/** Take the lock only if it is free AND nobody is queued; never waits, so queued callers are never overtaken. O(1). */
|
|
22
|
+
tryAcquire(kind) {
|
|
23
|
+
if (this.waiting.length > 0 || !this.fits(kind))
|
|
24
|
+
return false;
|
|
25
|
+
this.take(kind);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
21
28
|
release(kind) {
|
|
22
29
|
if (kind === "exclusive")
|
|
23
30
|
this.exclusive = false;
|
package/dist/migrate/runner.d.ts
CHANGED
|
@@ -39,8 +39,8 @@ export declare function assertValidSteps({ steps }: {
|
|
|
39
39
|
steps: readonly MigrationStep<KyselyKernel<unknown>>[];
|
|
40
40
|
}, _optional?: Record<string, never>): void;
|
|
41
41
|
/** Object-input facade over the existing runner; all extensions remain opt-in. */
|
|
42
|
-
export declare function migrate(required: {
|
|
43
|
-
kernel: KyselyKernel<
|
|
42
|
+
export declare function migrate<DB>(required: {
|
|
43
|
+
kernel: KyselyKernel<DB>;
|
|
44
44
|
steps: readonly MigrationStep<KyselyKernel<unknown>>[];
|
|
45
45
|
ledgerTable: string;
|
|
46
46
|
}, optional?: Omit<MigrationOptions, "ledgerTable">): Promise<MigrationReport>;
|
|
@@ -52,7 +52,7 @@ export declare function migrate(required: {
|
|
|
52
52
|
* @throws UnknownAppliedMigrationError / MigrationChecksumError before applying anything; whatever a
|
|
53
53
|
* step throws (its transaction is rolled back, later steps are not attempted).
|
|
54
54
|
*/
|
|
55
|
-
export declare function runMigrations(
|
|
55
|
+
export declare function runMigrations<DB>(typedKernel: KyselyKernel<DB>, steps: readonly MigrationStep<KyselyKernel<unknown>>[], options: MigrationOptions): Promise<MigrationReport>;
|
|
56
56
|
/** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
|
|
57
57
|
export declare function hasLedger({ kernel, ledgerTable }: {
|
|
58
58
|
kernel: KyselyKernel<unknown>;
|
package/dist/migrate/runner.js
CHANGED
|
@@ -140,7 +140,10 @@ export function migrate(required, optional = {}) {
|
|
|
140
140
|
* @throws UnknownAppliedMigrationError / MigrationChecksumError before applying anything; whatever a
|
|
141
141
|
* step throws (its transaction is rolled back, later steps are not attempted).
|
|
142
142
|
*/
|
|
143
|
-
export async function runMigrations(
|
|
143
|
+
export async function runMigrations(typedKernel, steps, options) {
|
|
144
|
+
// Histories use schema-independent steps; erase only the table view and retain kernel identity
|
|
145
|
+
// so transaction ownership and the runner's private ledger view keep using the same connection.
|
|
146
|
+
const kernel = typedKernel;
|
|
144
147
|
assertValidSteps({ steps });
|
|
145
148
|
kernel.require("interactiveTransactions");
|
|
146
149
|
validateExtensions({ options, steps });
|
|
@@ -8,7 +8,7 @@ export { ownerStoreDdl, ownerStoreMigration } from "./migrations/0000_owner_stor
|
|
|
8
8
|
* @example const { entries, grants } = await countOwnerStoreRows({ kernel });
|
|
9
9
|
*/
|
|
10
10
|
export async function countOwnerStoreRows({ kernel }, _options = {}) {
|
|
11
|
-
const count = (table) => kernel.run(async (db) => Number((await db.selectFrom(table).select(eb => eb.fn.countAll().as("n")).
|
|
11
|
+
const count = (table) => kernel.run(async (db) => Number((await db.selectFrom(table).select(eb => eb.fn.countAll().as("n")).executeTakeFirstOrThrow()).n));
|
|
12
12
|
return { entries: await count("secrets_vault"), grants: await count("owner_grants") };
|
|
13
13
|
}
|
|
14
14
|
/** The sealed entries of one workspace, in id order. The caller passes the legacy owner workspace.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The served-versus-stopped copy lifecycle of a PGlite data dir.
|
|
3
|
+
*
|
|
4
|
+
* Reaching the source: when THIS process serves it (copying the store you are running), through its owner's
|
|
5
|
+
* exclusive window; otherwise the source must be stopped — the copy takes the data dir's owner lock for the
|
|
6
|
+
* duration, so nothing writes to it meanwhile. A source served by another live process is refused by the
|
|
7
|
+
* lock port (its owner is the only one who may open it); the host maps that refusal to its own error.
|
|
8
|
+
*/
|
|
9
|
+
/** What the host supplies: the concrete PGlite owner/kernel/storage operations and the lock-refusal mapping. */
|
|
10
|
+
export interface PgliteSourceCopyPorts<Owner, Source extends {
|
|
11
|
+
close(): Promise<void>;
|
|
12
|
+
}> {
|
|
13
|
+
runningOwner(required: {
|
|
14
|
+
dataDir: string;
|
|
15
|
+
}): Owner | undefined;
|
|
16
|
+
copyServed(required: {
|
|
17
|
+
owner: Owner;
|
|
18
|
+
targetPath: string;
|
|
19
|
+
}): Promise<void>;
|
|
20
|
+
/** Takes the data dir's owner lock and returns its release; throws the host's error when another process holds it. */
|
|
21
|
+
acquireOwnerLock(required: {
|
|
22
|
+
dataDir: string;
|
|
23
|
+
}): () => void;
|
|
24
|
+
/** May throw synchronously. */
|
|
25
|
+
openStopped(required: {
|
|
26
|
+
dataDir: string;
|
|
27
|
+
}): Source;
|
|
28
|
+
copyStopped(required: {
|
|
29
|
+
source: Source;
|
|
30
|
+
targetPath: string;
|
|
31
|
+
}): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Copies the source data dir to `targetDataDir` through the right door (see this file's header).
|
|
35
|
+
* @throws Whatever a port throws (the lock refusal, an open or copy failure); the owner lock is always released.
|
|
36
|
+
* @complexity One dump + restore of the whole data dir, bounded by the site's size.
|
|
37
|
+
*/
|
|
38
|
+
export declare function copyPgliteSourceTo<Owner, Source extends {
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
}>({ sourceDataDir, targetDataDir, ports }: {
|
|
41
|
+
sourceDataDir: string;
|
|
42
|
+
targetDataDir: string;
|
|
43
|
+
ports: PgliteSourceCopyPorts<Owner, Source>;
|
|
44
|
+
}, _optional?: {}): Promise<void>;
|
|
45
|
+
//# sourceMappingURL=copy-source.d.ts.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The served-versus-stopped copy lifecycle of a PGlite data dir.
|
|
3
|
+
*
|
|
4
|
+
* Reaching the source: when THIS process serves it (copying the store you are running), through its owner's
|
|
5
|
+
* exclusive window; otherwise the source must be stopped — the copy takes the data dir's owner lock for the
|
|
6
|
+
* duration, so nothing writes to it meanwhile. A source served by another live process is refused by the
|
|
7
|
+
* lock port (its owner is the only one who may open it); the host maps that refusal to its own error.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Copies the source data dir to `targetDataDir` through the right door (see this file's header).
|
|
11
|
+
* @throws Whatever a port throws (the lock refusal, an open or copy failure); the owner lock is always released.
|
|
12
|
+
* @complexity One dump + restore of the whole data dir, bounded by the site's size.
|
|
13
|
+
*/
|
|
14
|
+
export async function copyPgliteSourceTo({ sourceDataDir, targetDataDir, ports }, _optional = {}) {
|
|
15
|
+
const owner = ports.runningOwner({ dataDir: sourceDataDir });
|
|
16
|
+
if (owner !== undefined) {
|
|
17
|
+
await ports.copyServed({ owner, targetPath: targetDataDir });
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const release = ports.acquireOwnerLock({ dataDir: sourceDataDir });
|
|
21
|
+
// Nested so the lock is released however the open, the copy or the close fails: the open can
|
|
22
|
+
// throw synchronously, and a rejected close must not skip `release()` for the process's life.
|
|
23
|
+
try {
|
|
24
|
+
const source = ports.openStopped({ dataDir: sourceDataDir });
|
|
25
|
+
try {
|
|
26
|
+
await ports.copyStopped({ source, targetPath: targetDataDir });
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
await source.close();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
release();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=copy-source.js.map
|
package/dist/pglite/index.d.ts
CHANGED
|
@@ -2,4 +2,5 @@
|
|
|
2
2
|
export { startPgliteOwner, runningPgliteOwner, acquireOwnerLock, defaultPgliteSocketDir, assertSocketPathFits, ensurePrivateDir, PgliteOwnerLockedError, PGLITE_LOW_MEMORY_SETTINGS, pgliteLowMemoryStartParams, type PgliteOwner } from "./owner.js";
|
|
3
3
|
export { PgliteSocketServer, errorResponseFrame, type PgliteSocketServerOptions } from "./socket-server.js";
|
|
4
4
|
export type { PgliteClass } from "./types.js";
|
|
5
|
+
export { copyPgliteSourceTo, type PgliteSourceCopyPorts } from "./copy-source.js";
|
|
5
6
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/pglite/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** PGlite ownership and socket serving. The consumer supplies its PGlite class. */
|
|
2
2
|
export { startPgliteOwner, runningPgliteOwner, acquireOwnerLock, defaultPgliteSocketDir, assertSocketPathFits, ensurePrivateDir, PgliteOwnerLockedError, PGLITE_LOW_MEMORY_SETTINGS, pgliteLowMemoryStartParams } from "./owner.js";
|
|
3
3
|
export { PgliteSocketServer, errorResponseFrame } from "./socket-server.js";
|
|
4
|
+
export { copyPgliteSourceTo } from "./copy-source.js";
|
|
4
5
|
//# sourceMappingURL=index.js.map
|