@jini-ai/db 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -10
- package/dist/kernel/dialect.d.ts +2 -1
- package/dist/kernel/dialect.js +5 -2
- package/dist/tools/read-tools.js +7 -4
- package/dist/tools/restore-points.d.ts +3 -0
- package/dist/tools/restore-points.js +2 -2
- package/dist/tools/surface-port.d.ts +7 -1
- package/dist/tools/timeline.d.ts +4 -0
- package/dist/tools/timeline.js +8 -2
- package/dist/tools/transfer-tools.js +1 -1
- package/package.json +3 -3
- package/dist/kernel/pg-types.d.ts +0 -22
- package/dist/kernel/pg-types.js +0 -26
- package/dist/kernel/socket.d.ts +0 -8
- package/dist/kernel/socket.js +0 -8
- package/dist/pglite/dialect.d.ts +0 -11
- package/dist/pglite/dialect.js +0 -88
- package/dist/pglite/driver.d.ts +0 -30
- package/dist/pglite/driver.js +0 -46
- package/dist/pglite/ops.d.ts +0 -39
- package/dist/pglite/ops.js +0 -78
- package/dist/postgres/driver.d.ts +0 -23
- package/dist/postgres/driver.js +0 -41
- package/dist/postgres/ops.d.ts +0 -12
- package/dist/postgres/ops.js +0 -46
- package/dist/postgres/pglite-socket.d.ts +0 -23
- package/dist/postgres/pglite-socket.js +0 -51
- package/dist/sqlite/driver.d.ts +0 -71
- package/dist/sqlite/driver.js +0 -132
- package/dist/sqlite/ops.d.ts +0 -12
- package/dist/sqlite/ops.js +0 -40
package/CHANGELOG.md
CHANGED
|
@@ -1,19 +1,16 @@
|
|
|
1
|
-
##
|
|
1
|
+
## 0.3.0 — 2026-10-05
|
|
2
2
|
|
|
3
3
|
### BREAKING
|
|
4
4
|
|
|
5
|
-
- `
|
|
5
|
+
- `createRestorePoint` takes a required `kind` (the host passes `getCapabilities().restorePoint.kind`, the same source as `costClass`) and returns it as-is. It always returned `"file-snapshot"` before, so a Postgres host's logical dump was returned and persisted as a file snapshot. `backup_create_restore_point` passes it.
|
|
6
|
+
- `getTimeline` refuses a non-integer or non-positive `limit` instead of passing it to the query.
|
|
6
7
|
|
|
7
8
|
### Fixed
|
|
8
9
|
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
-
|
|
12
|
-
|
|
13
|
-
- Align transfer handlers with core's second-argument `ToolExecutionOptions.emitSurface` and canonical `SurfaceEmitter`; preserve fail-closed confirmation behavior. Forward resolved catalog messages and adapt native SQLite snapshot fixtures with explicit raw-row result types.
|
|
14
|
-
- Move the canonical `defaultDbMessages` definition to a driver-free core module and export `DbMessages` through the existing tools entry. Extend optional host copy to the 16 remaining consumer-facing prose sites, including read-tool registration and copy preflight.
|
|
15
|
-
- Neutral runtime defaults now refer to the source; hosts can supply their exact prior wording. Tool IDs, permissions, refusal/cost gates, persisted naming, SQL bytes and schema vectors are unchanged.
|
|
16
|
-
|
|
10
|
+
- `database_query_timeline` reads `limit` through core's `readToolLimit` (default 50, cap 200): `0` or a non-integer is a model-facing input error and an over-cap value is capped, instead of a redacted plain `Error`. Needs `@jini-ai/core` ^0.4.1.
|
|
11
|
+
- `database_transfer_run` hands the exchange's deadline to `TransferSurfacePorts.confirmation` (new optional third argument `{ expiresAtMs }`) when the exchange reports one through the new optional `SurfaceExchange.expiresAtMs()`, so a host's confirmation card can count down and close on time.
|
|
12
|
+
- SQLite JSON equality (`jsonScalarEquals`) checks `json_type` first, so `true`/`false` never equal `1`/`0`.
|
|
13
|
+
- Internal `@jini-ai/core` dependency is a caret range (`workspace:^`) instead of an exact pin.
|
|
17
14
|
|
|
18
15
|
## 0.2.0 — 2026-10-02
|
|
19
16
|
|
|
@@ -25,6 +22,21 @@
|
|
|
25
22
|
- BREAKING: Import AgentToolDefinition, AgentToolSideEffect and AgentToolActorClassRule from core; db no longer declares or exports duplicate catalog types.
|
|
26
23
|
- Transfer descriptions derive from host naming and replaceable `defaultDbMessages`; the display catalog defaults to neutral `app` / `app_` names. Persisted naming is unchanged.
|
|
27
24
|
|
|
25
|
+
### Also shipped in 0.2.0 (published 2026-10-03; was listed under Unreleased)
|
|
26
|
+
|
|
27
|
+
#### BREAKING
|
|
28
|
+
|
|
29
|
+
- `DatabaseReadToolPorts.clock` now takes core `Clock.nowMs()`; restore-point timestamps use `nowIso({ clock })` at the existing sampling point.
|
|
30
|
+
|
|
31
|
+
#### Fixed
|
|
32
|
+
|
|
33
|
+
- Add a `default` condition to every JavaScript subpath, pointing to its existing ESM entry, so tsx CommonJS bootstraps can resolve the package without `ERR_PACKAGE_PATH_NOT_EXPORTED`.
|
|
34
|
+
|
|
35
|
+
- `databaseFile<DB>` accepts `StorageKernel<DB>` so hosts can pass typed kernels without casting or erasing their schema. Query and null behavior are unchanged.
|
|
36
|
+
|
|
37
|
+
- Align transfer handlers with core's second-argument `ToolExecutionOptions.emitSurface` and canonical `SurfaceEmitter`; preserve fail-closed confirmation behavior. Forward resolved catalog messages and adapt native SQLite snapshot fixtures with explicit raw-row result types.
|
|
38
|
+
- Move the canonical `defaultDbMessages` definition to a driver-free core module and export `DbMessages` through the existing tools entry. Extend optional host copy to the 16 remaining consumer-facing prose sites, including read-tool registration and copy preflight.
|
|
39
|
+
- Neutral runtime defaults now refer to the source; hosts can supply their exact prior wording. Tool IDs, permissions, refusal/cost gates, persisted naming, SQL bytes and schema vectors are unchanged.
|
|
28
40
|
|
|
29
41
|
## Unreleased — C2 generic additions
|
|
30
42
|
|
package/dist/kernel/dialect.d.ts
CHANGED
|
@@ -12,7 +12,8 @@ export declare function jsonText(dialect: StorageDialect, column: Expression<unk
|
|
|
12
12
|
/**
|
|
13
13
|
* `column` at `path` equals the JSON scalar `value` (string, number or boolean), as a boolean
|
|
14
14
|
* expression. SQLite has no JSON boolean type — `json_extract` reads `true`/`false` as `1`/`0` — so
|
|
15
|
-
*
|
|
15
|
+
* check `json_type` before comparing the bound `1`/`0`, so booleans never match numbers.
|
|
16
|
+
* Postgres compares the two `jsonb` values, so `10` matches
|
|
16
17
|
* `10.0` and a string never matches a number.
|
|
17
18
|
*/
|
|
18
19
|
export declare function jsonScalarEquals(dialect: StorageDialect, column: Expression<unknown>, path: readonly string[], value: string | number | boolean): RawBuilder<boolean>;
|
package/dist/kernel/dialect.js
CHANGED
|
@@ -40,14 +40,17 @@ export function jsonText(dialect, column, path) {
|
|
|
40
40
|
/**
|
|
41
41
|
* `column` at `path` equals the JSON scalar `value` (string, number or boolean), as a boolean
|
|
42
42
|
* expression. SQLite has no JSON boolean type — `json_extract` reads `true`/`false` as `1`/`0` — so
|
|
43
|
-
*
|
|
43
|
+
* check `json_type` before comparing the bound `1`/`0`, so booleans never match numbers.
|
|
44
|
+
* Postgres compares the two `jsonb` values, so `10` matches
|
|
44
45
|
* `10.0` and a string never matches a number.
|
|
45
46
|
*/
|
|
46
47
|
export function jsonScalarEquals(dialect, column, path, value) {
|
|
47
48
|
if (dialect === "postgres")
|
|
48
49
|
return sql `((${column}::jsonb #> ${pgPath(path)}) = ${JSON.stringify(value)}::jsonb)`;
|
|
49
50
|
const bound = typeof value === "boolean" ? (value ? 1 : 0) : value;
|
|
50
|
-
|
|
51
|
+
const types = typeof value === "number" ? ["integer", "real"] : typeof value === "boolean" ? ["true", "false"] : ["text"];
|
|
52
|
+
const at = sqlitePath(path);
|
|
53
|
+
return sql `(json_type(${column}, ${at}) IN (${sql.join(types)}) AND json_extract(${column}, ${at}) = ${bound})`;
|
|
51
54
|
}
|
|
52
55
|
/**
|
|
53
56
|
* A sort key for the value at `path`: SQLite's typed `json_extract`, Postgres' `jsonb` value, so
|
package/dist/tools/read-tools.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** Portable DB read/restore-point handlers; migration gateways stay host-owned. See docs/decisions/DR-001-bounded-operational-timeline.md. */
|
|
2
|
-
import { ToolInputError } from "@jini-ai/core";
|
|
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
5
|
import { getDatabaseAgentToolCatalog } from "./database-catalog.js";
|
|
6
|
-
import { getTimeline } from "./timeline.js";
|
|
6
|
+
import { DEFAULT_TIMELINE_PAGE_SIZE, getTimeline, MAX_TIMELINE_PAGE_SIZE } from "./timeline.js";
|
|
7
7
|
import { createRestorePoint as createDatabaseRestorePoint, listRestorePoints } from "./restore-points.js";
|
|
8
8
|
import { registrations } from "./registration.js";
|
|
9
9
|
/**
|
|
@@ -15,7 +15,7 @@ import { registrations } from "./registration.js";
|
|
|
15
15
|
*/
|
|
16
16
|
export function createDatabaseReadTools(ports, _optional = {}) {
|
|
17
17
|
const messages = _optional.messages ?? defaultDbMessages;
|
|
18
|
-
const { noInput: requireNoInput, isRecord, optionalString,
|
|
18
|
+
const { noInput: requireNoInput, isRecord, optionalString, optionalBoolean } = ports.readers;
|
|
19
19
|
const handlers = {
|
|
20
20
|
database_query_timeline: async (ctx) => {
|
|
21
21
|
if (ctx.input !== undefined && !isRecord(ctx.input))
|
|
@@ -30,7 +30,9 @@ export function createDatabaseReadTools(ports, _optional = {}) {
|
|
|
30
30
|
fromDate: optionalString(input, "fromDate"),
|
|
31
31
|
toDate: optionalString(input, "toDate"),
|
|
32
32
|
cursor: optionalString(input, "cursor"),
|
|
33
|
-
|
|
33
|
+
// The catalog promises "server-capped at 200, defaults to 50": cap here, and refuse 0/-1/2.5
|
|
34
|
+
// as a ToolInputError the model can read instead of getTimeline's redacted plain Error.
|
|
35
|
+
limit: readToolLimit({ input, max: MAX_TIMELINE_PAGE_SIZE, fallback: DEFAULT_TIMELINE_PAGE_SIZE }),
|
|
34
36
|
},
|
|
35
37
|
});
|
|
36
38
|
},
|
|
@@ -67,6 +69,7 @@ export function createDatabaseReadTools(ports, _optional = {}) {
|
|
|
67
69
|
let captured;
|
|
68
70
|
const summary = await createDatabaseRestorePoint({
|
|
69
71
|
costClass: capabilities.restorePoint.costClass,
|
|
72
|
+
kind: capabilities.restorePoint.kind,
|
|
70
73
|
costAck: costAck ?? false,
|
|
71
74
|
capture: async () => {
|
|
72
75
|
captured = await ports.dbOps.captureRestorePoint({ scopeId: ports.workspaceId });
|
|
@@ -42,6 +42,9 @@ export interface RestorePointSummary {
|
|
|
42
42
|
*/
|
|
43
43
|
export declare function createRestorePoint(required: {
|
|
44
44
|
costClass: RestorePointCostClass;
|
|
45
|
+
/** The host capability's restore kind (`getCapabilities().restorePoint.kind`), returned as-is.
|
|
46
|
+
* Required, not defaulted: a hardcoded `file-snapshot` mislabeled every Postgres logical dump. */
|
|
47
|
+
kind: string;
|
|
45
48
|
costAck?: boolean;
|
|
46
49
|
capture: () => Promise<{
|
|
47
50
|
artifactRef: string;
|
|
@@ -23,7 +23,7 @@ export class RestorePointUnavailableError extends Error {
|
|
|
23
23
|
* @overallScore 100
|
|
24
24
|
*/
|
|
25
25
|
export async function createRestorePoint(required, _optional = {}) {
|
|
26
|
-
const { costClass, costAck = false, capture } = required;
|
|
26
|
+
const { costClass, kind, costAck = false, capture } = required;
|
|
27
27
|
const messages = _optional.messages ?? defaultDbMessages;
|
|
28
28
|
if (costClass === "unavailable") {
|
|
29
29
|
throw new RestorePointUnavailableError(
|
|
@@ -36,7 +36,7 @@ export async function createRestorePoint(required, _optional = {}) {
|
|
|
36
36
|
"an 'expensive' restore point requires an explicit costAck; the confirmer must acknowledge the cost/disk estimate first");
|
|
37
37
|
}
|
|
38
38
|
await capture();
|
|
39
|
-
return { id: randomUUID(), costClass, kind
|
|
39
|
+
return { id: randomUUID(), costClass, kind };
|
|
40
40
|
}
|
|
41
41
|
/**
|
|
42
42
|
* Lists every restore point recorded for this site, newest-first (the port's own contract —
|
|
@@ -12,6 +12,9 @@ export interface SurfaceExchange {
|
|
|
12
12
|
send(emission: SurfaceEmission): Promise<void>;
|
|
13
13
|
receive(): Promise<SurfaceMessage>;
|
|
14
14
|
close(): void;
|
|
15
|
+
/** When the exchange stops waiting, in epoch ms, if the host tracks one. Read right before the
|
|
16
|
+
* confirmation is built and handed to it, so the host's card can count down and close on time. */
|
|
17
|
+
expiresAtMs?(): number;
|
|
15
18
|
}
|
|
16
19
|
export interface TransferSurfacePorts {
|
|
17
20
|
open(binding: {
|
|
@@ -30,7 +33,10 @@ export interface TransferSurfacePorts {
|
|
|
30
33
|
result: T;
|
|
31
34
|
outcome?: SurfaceEmission;
|
|
32
35
|
}>): Promise<T>;
|
|
33
|
-
|
|
36
|
+
/** `optional.expiresAtMs` is the exchange's deadline when it reports one (see `SurfaceExchange.expiresAtMs`). */
|
|
37
|
+
confirmation(plan: DatabaseTransferPlan, exchangeId: string, optional?: {
|
|
38
|
+
readonly expiresAtMs?: number;
|
|
39
|
+
}): SurfaceEmission;
|
|
34
40
|
destinationForm(exchangeId: string): SurfaceEmission;
|
|
35
41
|
destinationOutcome(input: {
|
|
36
42
|
exchangeId: string;
|
package/dist/tools/timeline.d.ts
CHANGED
|
@@ -39,6 +39,10 @@ export interface LedgerReadPort {
|
|
|
39
39
|
nextCursor: string | null;
|
|
40
40
|
}>;
|
|
41
41
|
}
|
|
42
|
+
/** The server-side row cap — no raw/unbounded query surface is ever offered. See docs/decisions/DR-001-bounded-operational-timeline.md. */
|
|
43
|
+
export declare const MAX_TIMELINE_PAGE_SIZE = 200;
|
|
44
|
+
/** Page size when a caller names none. */
|
|
45
|
+
export declare const DEFAULT_TIMELINE_PAGE_SIZE = 50;
|
|
42
46
|
/**
|
|
43
47
|
* Returns a filtered, cursor-paginated page of the Timeline ledger.
|
|
44
48
|
*
|
package/dist/tools/timeline.js
CHANGED
|
@@ -18,8 +18,9 @@
|
|
|
18
18
|
* See docs/decisions/DR-001-bounded-operational-timeline.md.
|
|
19
19
|
*/
|
|
20
20
|
/** The server-side row cap — no raw/unbounded query surface is ever offered. See docs/decisions/DR-001-bounded-operational-timeline.md. */
|
|
21
|
-
const MAX_TIMELINE_PAGE_SIZE = 200;
|
|
22
|
-
|
|
21
|
+
export const MAX_TIMELINE_PAGE_SIZE = 200;
|
|
22
|
+
/** Page size when a caller names none. */
|
|
23
|
+
export const DEFAULT_TIMELINE_PAGE_SIZE = 50;
|
|
23
24
|
/** Thrown when a caller requests a page size above the server's bound. */
|
|
24
25
|
class TimelineValidationError extends Error {
|
|
25
26
|
constructor(message) {
|
|
@@ -37,6 +38,11 @@ class TimelineValidationError extends Error {
|
|
|
37
38
|
export async function getTimeline(required, _optional = {}) {
|
|
38
39
|
const { ledger, filter = {} } = required;
|
|
39
40
|
const limit = filter.limit ?? DEFAULT_TIMELINE_PAGE_SIZE;
|
|
41
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
42
|
+
// A 0 or fractional limit reached the ledger as an empty page or a fractional SQL LIMIT; an HTTP
|
|
43
|
+
// caller's `Number("abc")` arrived as NaN.
|
|
44
|
+
throw new TimelineValidationError(`'limit' must be an integer between 1 and ${MAX_TIMELINE_PAGE_SIZE}`);
|
|
45
|
+
}
|
|
40
46
|
if (limit > MAX_TIMELINE_PAGE_SIZE) {
|
|
41
47
|
// See docs/decisions/DR-001-bounded-operational-timeline.md for the invariant behind this refusal; keep external identifiers out of caller-facing messages.
|
|
42
48
|
throw new TimelineValidationError(`requested limit ${limit} exceeds the server cap of ${MAX_TIMELINE_PAGE_SIZE}`);
|
|
@@ -183,7 +183,7 @@ async function handlePlan(deps, ctx) {
|
|
|
183
183
|
}
|
|
184
184
|
async function askToConfirm(ctx, surfaces, plan, emitSurface) {
|
|
185
185
|
const exchange = surfaces.open({ toolId: DATABASE_TRANSFER_RUN_TOOL_ID, principalId: ctx.principal.id }, emitSurface);
|
|
186
|
-
const emission = surfaces.confirmation(plan, exchange.id);
|
|
186
|
+
const emission = surfaces.confirmation(plan, exchange.id, exchange.expiresAtMs ? { expiresAtMs: exchange.expiresAtMs() } : {});
|
|
187
187
|
const closeOnAbort = () => exchange.close();
|
|
188
188
|
ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
|
|
189
189
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/db",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
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": {
|
|
@@ -169,10 +169,10 @@
|
|
|
169
169
|
"better-sqlite3": "13.0.3",
|
|
170
170
|
"kysely": "0.29.6",
|
|
171
171
|
"pg": "8.23.0",
|
|
172
|
-
"@jini-ai/core": "0.4.
|
|
172
|
+
"@jini-ai/core": "0.4.1"
|
|
173
173
|
},
|
|
174
174
|
"dependencies": {
|
|
175
|
-
"@jini-ai/core": "0.4.
|
|
175
|
+
"@jini-ai/core": "^0.4.1"
|
|
176
176
|
},
|
|
177
177
|
"scripts": {
|
|
178
178
|
"build": "tsc -p tsconfig.build.json",
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file How every Postgres transport turns column text into JS values where the defaults differ
|
|
3
|
-
* from what the repos (and SQLite) expect. One table, used by the PGlite and node-postgres drivers,
|
|
4
|
-
* so a row reads the same on both.
|
|
5
|
-
*
|
|
6
|
-
* - `json`/`jsonb` stay JSON TEXT: the repos store and parse JSON themselves (SQLite has no JSON
|
|
7
|
-
* type), so a `string` column type holds on every dialect. The text is re-serialised compactly
|
|
8
|
-
* (`{"a":1}`, as `JSON.stringify` writes it) instead of Postgres's own spelling (`{"a": 1}`), so a
|
|
9
|
-
* value written compactly reads back byte-identical.
|
|
10
|
-
* Key order is jsonb's (it does not keep insertion order); compare parsed values, not text.
|
|
11
|
-
* - `int8` (`bigint`) is a `number` when it fits in a double exactly, else a `bigint` — PGlite's own
|
|
12
|
-
* rule, which node-postgres (default: string) is aligned to.
|
|
13
|
-
*/
|
|
14
|
-
export declare const PG_OID: {
|
|
15
|
-
readonly int8: 20;
|
|
16
|
-
readonly json: 114;
|
|
17
|
-
readonly jsonb: 3802;
|
|
18
|
-
};
|
|
19
|
-
export declare function parseInt8(text: string): number | bigint;
|
|
20
|
-
/** Parser overrides by type oid. */
|
|
21
|
-
export declare const PG_PARSERS: Readonly<Record<number, (text: string) => unknown>>;
|
|
22
|
-
//# sourceMappingURL=pg-types.d.ts.map
|
package/dist/kernel/pg-types.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file How every Postgres transport turns column text into JS values where the defaults differ
|
|
3
|
-
* from what the repos (and SQLite) expect. One table, used by the PGlite and node-postgres drivers,
|
|
4
|
-
* so a row reads the same on both.
|
|
5
|
-
*
|
|
6
|
-
* - `json`/`jsonb` stay JSON TEXT: the repos store and parse JSON themselves (SQLite has no JSON
|
|
7
|
-
* type), so a `string` column type holds on every dialect. The text is re-serialised compactly
|
|
8
|
-
* (`{"a":1}`, as `JSON.stringify` writes it) instead of Postgres's own spelling (`{"a": 1}`), so a
|
|
9
|
-
* value written compactly reads back byte-identical.
|
|
10
|
-
* Key order is jsonb's (it does not keep insertion order); compare parsed values, not text.
|
|
11
|
-
* - `int8` (`bigint`) is a `number` when it fits in a double exactly, else a `bigint` — PGlite's own
|
|
12
|
-
* rule, which node-postgres (default: string) is aligned to.
|
|
13
|
-
*/
|
|
14
|
-
export const PG_OID = { int8: 20, json: 114, jsonb: 3802 };
|
|
15
|
-
export function parseInt8(text) {
|
|
16
|
-
const value = BigInt(text);
|
|
17
|
-
return value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER) ? value : Number(value);
|
|
18
|
-
}
|
|
19
|
-
const compactJson = (text) => JSON.stringify(JSON.parse(text));
|
|
20
|
-
/** Parser overrides by type oid. */
|
|
21
|
-
export const PG_PARSERS = {
|
|
22
|
-
[PG_OID.int8]: parseInt8,
|
|
23
|
-
[PG_OID.json]: compactJson,
|
|
24
|
-
[PG_OID.jsonb]: compactJson,
|
|
25
|
-
};
|
|
26
|
-
//# sourceMappingURL=pg-types.js.map
|
package/dist/kernel/socket.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file Where a PGlite owner's Unix socket lives inside its socket directory. Shared by the owner
|
|
3
|
-
* (`@jini-ai/db/pglite`) and the socket client (`@jini-ai/db/postgres`), which must agree on it and
|
|
4
|
-
* must not import each other.
|
|
5
|
-
*/
|
|
6
|
-
/** The Postgres client convention: a client given `host=<dir>, port=5432` connects to this file. */
|
|
7
|
-
export declare const PGLITE_SOCKET_FILE = ".s.PGSQL.5432";
|
|
8
|
-
//# sourceMappingURL=socket.d.ts.map
|
package/dist/kernel/socket.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file Where a PGlite owner's Unix socket lives inside its socket directory. Shared by the owner
|
|
3
|
-
* (`@jini-ai/db/pglite`) and the socket client (`@jini-ai/db/postgres`), which must agree on it and
|
|
4
|
-
* must not import each other.
|
|
5
|
-
*/
|
|
6
|
-
/** The Postgres client convention: a client given `host=<dir>, port=5432` connects to this file. */
|
|
7
|
-
export const PGLITE_SOCKET_FILE = ".s.PGSQL.5432";
|
|
8
|
-
//# sourceMappingURL=socket.js.map
|
package/dist/pglite/dialect.d.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import type { PGlite } from "@electric-sql/pglite";
|
|
2
|
-
import { type Dialect, type Driver, type Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler } from "kysely";
|
|
3
|
-
export declare class PgliteDialect implements Dialect {
|
|
4
|
-
private readonly client;
|
|
5
|
-
constructor(client: PGlite);
|
|
6
|
-
createAdapter(): PostgresAdapter;
|
|
7
|
-
createDriver(): Driver;
|
|
8
|
-
createQueryCompiler(): PostgresQueryCompiler;
|
|
9
|
-
createIntrospector(db: Kysely<unknown>): PostgresIntrospector;
|
|
10
|
-
}
|
|
11
|
-
//# sourceMappingURL=dialect.d.ts.map
|
package/dist/pglite/dialect.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { CompiledQuery, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, } from "kysely";
|
|
2
|
-
/**
|
|
3
|
-
* @file A Kysely dialect over one PGlite instance: Kysely's own Postgres adapter, compiler and
|
|
4
|
-
* introspector, plus a driver that runs compiled queries through `PGlite#query`.
|
|
5
|
-
*
|
|
6
|
-
* Written here rather than taken from npm (2026-09-28): `kysely-pglite-dialect` 1.3.1 declares
|
|
7
|
-
* `@electric-sql/pglite` peer `^0.2 || ^0.3 || ^0.4` (this package pins 0.5.8), is one maintainer, and is
|
|
8
|
-
* ~11 KB of the same few lines; `kysely-pglite` was last published 2024. This file is that driver,
|
|
9
|
-
* sized to what the kernel needs and nothing else.
|
|
10
|
-
*
|
|
11
|
-
* PGlite is ONE connection. The driver hands it out one holder at a time (a transaction holds it
|
|
12
|
-
* from `BEGIN` to `COMMIT`), so a statement from outside can never land inside someone else's
|
|
13
|
-
* transaction. The kernel's turn lock already orders callers; this keeps the dialect correct on its
|
|
14
|
-
* own too.
|
|
15
|
-
*/
|
|
16
|
-
class PgliteConnection {
|
|
17
|
-
client;
|
|
18
|
-
constructor(client) {
|
|
19
|
-
this.client = client;
|
|
20
|
-
}
|
|
21
|
-
async executeQuery(compiled) {
|
|
22
|
-
const result = await this.client.query(compiled.sql, [...compiled.parameters]);
|
|
23
|
-
return {
|
|
24
|
-
rows: result.rows,
|
|
25
|
-
...(result.affectedRows !== undefined ? { numAffectedRows: BigInt(result.affectedRows) } : {}),
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
// eslint-disable-next-line require-yield -- the interface requires a generator; PGlite has no cursor API here
|
|
29
|
-
async *streamQuery() {
|
|
30
|
-
throw new Error("streaming queries are not supported on PGlite");
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
class PgliteDriver {
|
|
34
|
-
client;
|
|
35
|
-
connection;
|
|
36
|
-
holder = Promise.resolve();
|
|
37
|
-
releaseHolder;
|
|
38
|
-
constructor(client) {
|
|
39
|
-
this.client = client;
|
|
40
|
-
this.connection = new PgliteConnection(client);
|
|
41
|
-
}
|
|
42
|
-
async init() {
|
|
43
|
-
await this.client.waitReady;
|
|
44
|
-
}
|
|
45
|
-
async acquireConnection() {
|
|
46
|
-
const previous = this.holder;
|
|
47
|
-
let release;
|
|
48
|
-
this.holder = new Promise((resolve) => (release = resolve));
|
|
49
|
-
await previous;
|
|
50
|
-
this.releaseHolder = release;
|
|
51
|
-
return this.connection;
|
|
52
|
-
}
|
|
53
|
-
async releaseConnection() {
|
|
54
|
-
const release = this.releaseHolder;
|
|
55
|
-
this.releaseHolder = undefined;
|
|
56
|
-
release?.();
|
|
57
|
-
}
|
|
58
|
-
async beginTransaction(connection) {
|
|
59
|
-
await connection.executeQuery(CompiledQuery.raw("BEGIN"));
|
|
60
|
-
}
|
|
61
|
-
async commitTransaction(connection) {
|
|
62
|
-
await connection.executeQuery(CompiledQuery.raw("COMMIT"));
|
|
63
|
-
}
|
|
64
|
-
async rollbackTransaction(connection) {
|
|
65
|
-
await connection.executeQuery(CompiledQuery.raw("ROLLBACK"));
|
|
66
|
-
}
|
|
67
|
-
/** The PGlite instance belongs to whoever opened it (the kernel closes it). */
|
|
68
|
-
async destroy() { }
|
|
69
|
-
}
|
|
70
|
-
export class PgliteDialect {
|
|
71
|
-
client;
|
|
72
|
-
constructor(client) {
|
|
73
|
-
this.client = client;
|
|
74
|
-
}
|
|
75
|
-
createAdapter() {
|
|
76
|
-
return new PostgresAdapter();
|
|
77
|
-
}
|
|
78
|
-
createDriver() {
|
|
79
|
-
return new PgliteDriver(this.client);
|
|
80
|
-
}
|
|
81
|
-
createQueryCompiler() {
|
|
82
|
-
return new PostgresQueryCompiler();
|
|
83
|
-
}
|
|
84
|
-
createIntrospector(db) {
|
|
85
|
-
return new PostgresIntrospector(db);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
//# sourceMappingURL=dialect.js.map
|
package/dist/pglite/driver.d.ts
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import type { PGlite } from "@electric-sql/pglite";
|
|
2
|
-
import { type StorageKernel } from "../kernel/index.js";
|
|
3
|
-
import type { PgliteClass } from "./types.js";
|
|
4
|
-
/**
|
|
5
|
-
* @file The PGlite driver: one in-process Postgres (WASM) per data directory, behind the same
|
|
6
|
-
* Kysely query bodies as every other driver.
|
|
7
|
-
*
|
|
8
|
-
* PGlite holds one connection: a repo that kept using the base handle inside a transaction would
|
|
9
|
-
* wait on itself forever. The kernel's transaction scope hands the open transaction to every
|
|
10
|
-
* `run()` inside it, which is what makes that safe.
|
|
11
|
-
*
|
|
12
|
-
* Only ONE process may open a data dir; to share one, run an owner (`startPgliteOwner`) and connect
|
|
13
|
-
* through its socket.
|
|
14
|
-
*/
|
|
15
|
-
export type PgKernel<DB> = StorageKernel<DB>;
|
|
16
|
-
/**
|
|
17
|
-
* Opens (and on first use creates) a PGlite database. Synchronous so it fits the synchronous
|
|
18
|
-
* composition root; the async setup runs behind `ready`, which every kernel call awaits.
|
|
19
|
-
*
|
|
20
|
-
* @param required.PGlite the consumer's `PGlite` class (this package never imports it).
|
|
21
|
-
* @param optional.dataDir absent = in-memory (tests).
|
|
22
|
-
* @param optional.prepare runs once after open, before any call (e.g. schema creation).
|
|
23
|
-
*/
|
|
24
|
-
export declare function openPgliteKernel<DB>(required: {
|
|
25
|
-
PGlite: PgliteClass;
|
|
26
|
-
}, optional?: {
|
|
27
|
-
dataDir?: string;
|
|
28
|
-
prepare?: (client: PGlite) => Promise<void>;
|
|
29
|
-
}): PgKernel<DB>;
|
|
30
|
-
//# sourceMappingURL=driver.d.ts.map
|
package/dist/pglite/driver.js
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { mkdirSync } from "node:fs";
|
|
2
|
-
import { writeFile } from "node:fs/promises";
|
|
3
|
-
import { Kysely } from "kysely";
|
|
4
|
-
import { buildKernel, PG_PARSERS, postgresLockKey } from "../kernel/index.js";
|
|
5
|
-
import { PgliteDialect } from "./dialect.js";
|
|
6
|
-
/**
|
|
7
|
-
* Opens (and on first use creates) a PGlite database. Synchronous so it fits the synchronous
|
|
8
|
-
* composition root; the async setup runs behind `ready`, which every kernel call awaits.
|
|
9
|
-
*
|
|
10
|
-
* @param required.PGlite the consumer's `PGlite` class (this package never imports it).
|
|
11
|
-
* @param optional.dataDir absent = in-memory (tests).
|
|
12
|
-
* @param optional.prepare runs once after open, before any call (e.g. schema creation).
|
|
13
|
-
*/
|
|
14
|
-
export function openPgliteKernel(required, optional = {}) {
|
|
15
|
-
if (optional.dataDir !== undefined)
|
|
16
|
-
mkdirSync(optional.dataDir, { recursive: true });
|
|
17
|
-
// One options object: PGlite drops the second argument when the first (dataDir) is undefined.
|
|
18
|
-
const client = new required.PGlite({ ...(optional.dataDir === undefined ? {} : { dataDir: optional.dataDir }), parsers: PG_PARSERS });
|
|
19
|
-
const base = new Kysely({ dialect: new PgliteDialect(client) });
|
|
20
|
-
const ready = (async () => {
|
|
21
|
-
await client.waitReady;
|
|
22
|
-
await optional.prepare?.(client);
|
|
23
|
-
})();
|
|
24
|
-
// Surfaced by every call that awaits `ready`; this only stops an unhandled-rejection crash when
|
|
25
|
-
// nothing has called in yet.
|
|
26
|
-
ready.catch(() => { });
|
|
27
|
-
return buildKernel({
|
|
28
|
-
dialect: "postgres",
|
|
29
|
-
transport: "pglite",
|
|
30
|
-
capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: true },
|
|
31
|
-
ready,
|
|
32
|
-
base,
|
|
33
|
-
oneConnection: true,
|
|
34
|
-
begin: (body) => base.transaction().execute((tx) => body(tx)),
|
|
35
|
-
lockKey: postgresLockKey,
|
|
36
|
-
async backup(destPath) {
|
|
37
|
-
const dump = await client.dumpDataDir("none");
|
|
38
|
-
await writeFile(destPath, Buffer.from(await dump.arrayBuffer()));
|
|
39
|
-
},
|
|
40
|
-
async close() {
|
|
41
|
-
await ready.catch(() => { });
|
|
42
|
-
await client.close();
|
|
43
|
-
},
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
//# sourceMappingURL=driver.js.map
|
package/dist/pglite/ops.d.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import type { PGlite } from "@electric-sql/pglite";
|
|
2
|
-
import { type StorageKernel, type StorageOps } from "../kernel/index.js";
|
|
3
|
-
import type { PgliteClass } from "./types.js";
|
|
4
|
-
/**
|
|
5
|
-
* @file The storage ops for PGlite: an in-process kernel (`openPgliteKernel`), or a socket client
|
|
6
|
-
* whose owner runs in this process. The copy is a data-dir dump restored into a new data dir;
|
|
7
|
-
* compacting is `VACUUM` + `CHECKPOINT`, then a read-back of the consumer's migration ledger. A
|
|
8
|
-
* socket client reaches the dump only through its owner's exclusive window ({@link PgliteExclusive});
|
|
9
|
-
* without one, use `@jini-ai/db/postgres`'s `postgresOps`, which refuses the copy.
|
|
10
|
-
*/
|
|
11
|
-
/** A PGlite owner's exclusive window (`PgliteOwner.runExclusive`): the one way to dump a served data dir. */
|
|
12
|
-
export interface PgliteExclusive {
|
|
13
|
-
runExclusive<T>(fn: (db: PGlite) => Promise<T>): Promise<T>;
|
|
14
|
-
}
|
|
15
|
-
/** What restoring a dump needs: the consumer's `PGlite` class and the owner lock file to drop from the copy. */
|
|
16
|
-
export interface PgliteRestore {
|
|
17
|
-
readonly PGlite: PgliteClass;
|
|
18
|
-
/** The owner's pid lock file name; the dump carries the source owner's lock, the copy has no owner yet. */
|
|
19
|
-
readonly ownerLockFileName?: string;
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* The ops for a PGlite kernel. Must be used outside a transaction (Postgres cannot `VACUUM` inside one).
|
|
23
|
-
*
|
|
24
|
-
* @param required.ledgerTable the migration ledger the compaction reads back (no default).
|
|
25
|
-
* @param optional.pgliteOwner the owner serving the data dir `kernel` is a socket client of.
|
|
26
|
-
* @throws {Error} a kernel that is neither in-process PGlite nor a socket client given its owner.
|
|
27
|
-
* @complexity each op is one full pass over the data dir, O(size).
|
|
28
|
-
*/
|
|
29
|
-
export declare function pgliteOps<DB>(kernel: StorageKernel<DB>, required: PgliteRestore & {
|
|
30
|
-
ledgerTable: string;
|
|
31
|
-
}, optional?: {
|
|
32
|
-
pgliteOwner?: PgliteExclusive;
|
|
33
|
-
}): StorageOps;
|
|
34
|
-
/**
|
|
35
|
-
* `copyTo` for a PGlite data dir served by `owner` (in this process): the dump is taken inside the
|
|
36
|
-
* owner's exclusive window, then restored into `targetPath` (which must not exist).
|
|
37
|
-
*/
|
|
38
|
-
export declare function copyServedPgliteTo(owner: PgliteExclusive, targetPath: string, required: PgliteRestore): Promise<void>;
|
|
39
|
-
//# sourceMappingURL=ops.d.ts.map
|
package/dist/pglite/ops.js
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { existsSync, rmSync } from "node:fs";
|
|
3
|
-
import { readFile } from "node:fs/promises";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { sql } from "kysely";
|
|
6
|
-
import { outsideTransactionOf, verifyLedgerReadBack, } from "../kernel/index.js";
|
|
7
|
-
/**
|
|
8
|
-
* The ops for a PGlite kernel. Must be used outside a transaction (Postgres cannot `VACUUM` inside one).
|
|
9
|
-
*
|
|
10
|
-
* @param required.ledgerTable the migration ledger the compaction reads back (no default).
|
|
11
|
-
* @param optional.pgliteOwner the owner serving the data dir `kernel` is a socket client of.
|
|
12
|
-
* @throws {Error} a kernel that is neither in-process PGlite nor a socket client given its owner.
|
|
13
|
-
* @complexity each op is one full pass over the data dir, O(size).
|
|
14
|
-
*/
|
|
15
|
-
export function pgliteOps(kernel, required, optional = {}) {
|
|
16
|
-
const owner = optional.pgliteOwner;
|
|
17
|
-
const ownedSocket = kernel.transport === "pglite-socket" && owner !== undefined;
|
|
18
|
-
if (kernel.transport !== "pglite" && !ownedSocket) {
|
|
19
|
-
throw new Error(`pgliteOps: a ${kernel.transport} kernel is not PGlite in this process (a socket client needs pgliteOwner)`);
|
|
20
|
-
}
|
|
21
|
-
const outsideTransaction = outsideTransactionOf(kernel);
|
|
22
|
-
return {
|
|
23
|
-
async copyTo(targetPath) {
|
|
24
|
-
outsideTransaction("copyTo");
|
|
25
|
-
if (owner !== undefined)
|
|
26
|
-
return copyServedPgliteTo(owner, targetPath, required);
|
|
27
|
-
await restoreDataDir(targetPath, required, async () => {
|
|
28
|
-
const tarball = `${targetPath}.${randomUUID()}.tar`;
|
|
29
|
-
try {
|
|
30
|
-
await kernel.backupTo(tarball);
|
|
31
|
-
return new Blob([await readFile(tarball)]);
|
|
32
|
-
}
|
|
33
|
-
finally {
|
|
34
|
-
rmSync(tarball, { force: true });
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
},
|
|
38
|
-
async compactAndVerify() {
|
|
39
|
-
outsideTransaction("compactAndVerify");
|
|
40
|
-
if (owner !== undefined) {
|
|
41
|
-
// Two calls: a multi-statement string runs as one implicit transaction, which VACUUM refuses.
|
|
42
|
-
await owner.runExclusive(async (db) => {
|
|
43
|
-
await db.exec("VACUUM");
|
|
44
|
-
await db.exec("CHECKPOINT");
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
else {
|
|
48
|
-
await kernel.execute(sql `VACUUM`);
|
|
49
|
-
await kernel.execute(sql `CHECKPOINT`);
|
|
50
|
-
}
|
|
51
|
-
await verifyLedgerReadBack(kernel, required.ledgerTable);
|
|
52
|
-
},
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* `copyTo` for a PGlite data dir served by `owner` (in this process): the dump is taken inside the
|
|
57
|
-
* owner's exclusive window, then restored into `targetPath` (which must not exist).
|
|
58
|
-
*/
|
|
59
|
-
export async function copyServedPgliteTo(owner, targetPath, required) {
|
|
60
|
-
await restoreDataDir(targetPath, required, () => owner.runExclusive((db) => db.dumpDataDir("none")));
|
|
61
|
-
}
|
|
62
|
-
/** Restores `dump()` into a new PGlite data dir at `targetPath`; removes a partial dir on failure. */
|
|
63
|
-
async function restoreDataDir(targetPath, required, dump) {
|
|
64
|
-
if (existsSync(targetPath))
|
|
65
|
-
throw new Error(`storage op copyTo: ${targetPath} already exists`);
|
|
66
|
-
const data = await dump();
|
|
67
|
-
try {
|
|
68
|
-
const restored = await required.PGlite.create({ dataDir: targetPath, loadDataDir: data });
|
|
69
|
-
await restored.close();
|
|
70
|
-
if (required.ownerLockFileName !== undefined)
|
|
71
|
-
rmSync(join(targetPath, required.ownerLockFileName), { force: true });
|
|
72
|
-
}
|
|
73
|
-
catch (err) {
|
|
74
|
-
rmSync(targetPath, { recursive: true, force: true });
|
|
75
|
-
throw err;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
//# sourceMappingURL=ops.js.map
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { type StorageKernel } from "../kernel/index.js";
|
|
2
|
-
import { type PgModule } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
* @file The node-postgres driver: a connection POOL to any Postgres server (local, Supabase, Neon).
|
|
5
|
-
* Kysely's own Postgres dialect; each transaction checks out its own connection, so unrelated
|
|
6
|
-
* requests run concurrently (no turn lock) and `lockKey` is what serializes the sequences that
|
|
7
|
-
* must not interleave.
|
|
8
|
-
*
|
|
9
|
-
* This package never imports `pg`: the consumer passes its own module (`import pg from "pg"`).
|
|
10
|
-
*/
|
|
11
|
-
/**
|
|
12
|
-
* Opens a pooled kernel on the server at `connectionString`.
|
|
13
|
-
*
|
|
14
|
-
* @param required.pg the consumer's node-postgres module.
|
|
15
|
-
* @param optional.max pool size, default 10.
|
|
16
|
-
*/
|
|
17
|
-
export declare function openPostgresKernel<DB>(required: {
|
|
18
|
-
pg: PgModule;
|
|
19
|
-
connectionString: string;
|
|
20
|
-
}, optional?: {
|
|
21
|
-
max?: number;
|
|
22
|
-
}): StorageKernel<DB>;
|
|
23
|
-
//# sourceMappingURL=driver.d.ts.map
|
package/dist/postgres/driver.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { Kysely, PostgresDialect } from "kysely";
|
|
2
|
-
import { buildKernel, PG_PARSERS, postgresLockKey } from "../kernel/index.js";
|
|
3
|
-
import { pgTypesFor } from "./types.js";
|
|
4
|
-
/**
|
|
5
|
-
* @file The node-postgres driver: a connection POOL to any Postgres server (local, Supabase, Neon).
|
|
6
|
-
* Kysely's own Postgres dialect; each transaction checks out its own connection, so unrelated
|
|
7
|
-
* requests run concurrently (no turn lock) and `lockKey` is what serializes the sequences that
|
|
8
|
-
* must not interleave.
|
|
9
|
-
*
|
|
10
|
-
* This package never imports `pg`: the consumer passes its own module (`import pg from "pg"`).
|
|
11
|
-
*/
|
|
12
|
-
/**
|
|
13
|
-
* Opens a pooled kernel on the server at `connectionString`.
|
|
14
|
-
*
|
|
15
|
-
* @param required.pg the consumer's node-postgres module.
|
|
16
|
-
* @param optional.max pool size, default 10.
|
|
17
|
-
*/
|
|
18
|
-
export function openPostgresKernel(required, optional = {}) {
|
|
19
|
-
const pool = new required.pg.Pool({
|
|
20
|
-
connectionString: required.connectionString,
|
|
21
|
-
max: optional.max ?? 10,
|
|
22
|
-
types: pgTypesFor(required.pg, PG_PARSERS),
|
|
23
|
-
});
|
|
24
|
-
// An idle connection dropped by the server (restart, failover, pg_terminate_backend, a pooler's
|
|
25
|
-
// idle cut) is evicted by the pool and reopened on next use; without a listener it would crash the
|
|
26
|
-
// process.
|
|
27
|
-
pool.on("error", (err) => console.warn(`[postgres] idle pool connection dropped: ${err.message}`));
|
|
28
|
-
const base = new Kysely({ dialect: new PostgresDialect({ pool }) });
|
|
29
|
-
return buildKernel({
|
|
30
|
-
dialect: "postgres",
|
|
31
|
-
transport: "node-postgres",
|
|
32
|
-
capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: false },
|
|
33
|
-
ready: Promise.resolve(),
|
|
34
|
-
base,
|
|
35
|
-
oneConnection: false,
|
|
36
|
-
begin: (body) => base.transaction().execute((tx) => body(tx)),
|
|
37
|
-
lockKey: postgresLockKey,
|
|
38
|
-
close: () => base.destroy(),
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
//# sourceMappingURL=driver.js.map
|
package/dist/postgres/ops.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { type StorageKernel, type StorageOps } from "../kernel/index.js";
|
|
2
|
-
/**
|
|
3
|
-
* The ops for a node-postgres kernel. Must be used outside a transaction.
|
|
4
|
-
*
|
|
5
|
-
* @param required.ledgerTable the migration ledger the compaction reads back (no default).
|
|
6
|
-
* @throws {Error} a kernel of another transport.
|
|
7
|
-
* @complexity `compactAndVerify` is one full `VACUUM` pass, O(size).
|
|
8
|
-
*/
|
|
9
|
-
export declare function postgresOps<DB>(kernel: StorageKernel<DB>, required: {
|
|
10
|
-
ledgerTable: string;
|
|
11
|
-
}): StorageOps;
|
|
12
|
-
//# sourceMappingURL=ops.d.ts.map
|
package/dist/postgres/ops.js
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { sql } from "kysely";
|
|
2
|
-
import { outsideTransactionOf, StorageOpNotSupportedError, verifyLedgerReadBack, } from "../kernel/index.js";
|
|
3
|
-
/**
|
|
4
|
-
* @file The storage ops for a node-postgres kernel: a Postgres server (`openPostgresKernel`) or a
|
|
5
|
-
* PGlite socket client (`openPgliteSocketKernel`) with no owner in this process. Neither can copy
|
|
6
|
-
* the database as a file; compacting is `VACUUM` (plus `CHECKPOINT` on PGlite) and a read-back of the
|
|
7
|
-
* consumer's migration ledger. A socket client whose owner runs in this process uses
|
|
8
|
-
* `@jini-ai/db/pglite`'s `pgliteOps` instead, which can copy through the owner.
|
|
9
|
-
*/
|
|
10
|
-
/** Why a Postgres server's database is never file-copied. */
|
|
11
|
-
const POSTGRES_COPY_REASON = "a Postgres database is backed up by its provider; use a transfer tool to copy it";
|
|
12
|
-
/** Why a PGlite socket client cannot copy on its own. */
|
|
13
|
-
const SOCKET_COPY_REASON = "a PGlite socket client copies through its owner's exclusive window (use pgliteOps with pgliteOwner)";
|
|
14
|
-
/**
|
|
15
|
-
* The ops for a node-postgres kernel. Must be used outside a transaction.
|
|
16
|
-
*
|
|
17
|
-
* @param required.ledgerTable the migration ledger the compaction reads back (no default).
|
|
18
|
-
* @throws {Error} a kernel of another transport.
|
|
19
|
-
* @complexity `compactAndVerify` is one full `VACUUM` pass, O(size).
|
|
20
|
-
*/
|
|
21
|
-
export function postgresOps(kernel, required) {
|
|
22
|
-
if (kernel.transport !== "node-postgres" && kernel.transport !== "pglite-socket") {
|
|
23
|
-
throw new Error(`postgresOps: a ${kernel.transport} kernel is not a node-postgres connection`);
|
|
24
|
-
}
|
|
25
|
-
const outsideTransaction = outsideTransactionOf(kernel);
|
|
26
|
-
return {
|
|
27
|
-
async copyTo() {
|
|
28
|
-
outsideTransaction("copyTo");
|
|
29
|
-
const reason = kernel.transport === "pglite-socket" ? SOCKET_COPY_REASON : POSTGRES_COPY_REASON;
|
|
30
|
-
throw new StorageOpNotSupportedError("copyTo", kernel.transport, reason);
|
|
31
|
-
},
|
|
32
|
-
async compactAndVerify() {
|
|
33
|
-
outsideTransaction("compactAndVerify");
|
|
34
|
-
if (kernel.transport === "pglite-socket") {
|
|
35
|
-
await kernel.execute(sql `VACUUM`);
|
|
36
|
-
await kernel.execute(sql `CHECKPOINT`);
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
// A hosted server rarely lets an app's role CHECKPOINT; a commit is durable anyway.
|
|
40
|
-
await kernel.execute(sql `VACUUM (ANALYZE)`);
|
|
41
|
-
}
|
|
42
|
-
await verifyLedgerReadBack(kernel, required.ledgerTable);
|
|
43
|
-
},
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
//# sourceMappingURL=ops.js.map
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import { type StorageKernel } from "../kernel/index.js";
|
|
2
|
-
import { type PgModule } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
* @file A storage kernel that reaches a PGlite data dir through its owner's Unix socket
|
|
5
|
-
* (`@jini-ai/db/pglite`'s `startPgliteOwner`): node-postgres with ONE connection and the kernel's turn lock, because PGlite
|
|
6
|
-
* is one backend session — a second connection gives no parallelism, and every client's transaction
|
|
7
|
-
* blocks every other client anyway. Every process sharing the data dir uses this.
|
|
8
|
-
*
|
|
9
|
-
* Kernel rules this transport makes hard: no `SET` (only `SET LOCAL`), no temp tables, no named
|
|
10
|
-
* prepared statements, no session advisory locks — all clients share one session, so any of those
|
|
11
|
-
* leaks into the other process. Backup is not offered here; it goes through the owner.
|
|
12
|
-
*/
|
|
13
|
-
/**
|
|
14
|
-
* Opens a one-connection kernel on the PGlite owner socket at `socketPath`.
|
|
15
|
-
*
|
|
16
|
-
* @param required.pg the consumer's node-postgres module (`import pg from "pg"`).
|
|
17
|
-
* @throws {Error} a path that does not end in the Postgres socket file name.
|
|
18
|
-
*/
|
|
19
|
-
export declare function openPgliteSocketKernel<DB>(required: {
|
|
20
|
-
pg: PgModule;
|
|
21
|
-
socketPath: string;
|
|
22
|
-
}): StorageKernel<DB>;
|
|
23
|
-
//# sourceMappingURL=pglite-socket.d.ts.map
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { dirname } from "node:path";
|
|
2
|
-
import { Kysely, PostgresDialect } from "kysely";
|
|
3
|
-
import { buildKernel, PG_PARSERS, PGLITE_SOCKET_FILE, postgresLockKey } from "../kernel/index.js";
|
|
4
|
-
import { pgTypesFor } from "./types.js";
|
|
5
|
-
/**
|
|
6
|
-
* @file A storage kernel that reaches a PGlite data dir through its owner's Unix socket
|
|
7
|
-
* (`@jini-ai/db/pglite`'s `startPgliteOwner`): node-postgres with ONE connection and the kernel's turn lock, because PGlite
|
|
8
|
-
* is one backend session — a second connection gives no parallelism, and every client's transaction
|
|
9
|
-
* blocks every other client anyway. Every process sharing the data dir uses this.
|
|
10
|
-
*
|
|
11
|
-
* Kernel rules this transport makes hard: no `SET` (only `SET LOCAL`), no temp tables, no named
|
|
12
|
-
* prepared statements, no session advisory locks — all clients share one session, so any of those
|
|
13
|
-
* leaks into the other process. Backup is not offered here; it goes through the owner.
|
|
14
|
-
*/
|
|
15
|
-
/**
|
|
16
|
-
* Opens a one-connection kernel on the PGlite owner socket at `socketPath`.
|
|
17
|
-
*
|
|
18
|
-
* @param required.pg the consumer's node-postgres module (`import pg from "pg"`).
|
|
19
|
-
* @throws {Error} a path that does not end in the Postgres socket file name.
|
|
20
|
-
*/
|
|
21
|
-
export function openPgliteSocketKernel(required) {
|
|
22
|
-
if (!required.socketPath.endsWith(`/${PGLITE_SOCKET_FILE}`)) {
|
|
23
|
-
throw new Error(`a PGlite socket path ends in /${PGLITE_SOCKET_FILE}: ${required.socketPath}`);
|
|
24
|
-
}
|
|
25
|
-
const pool = new required.pg.Pool({
|
|
26
|
-
host: dirname(required.socketPath),
|
|
27
|
-
port: 5432,
|
|
28
|
-
user: "postgres",
|
|
29
|
-
database: "postgres",
|
|
30
|
-
max: 1,
|
|
31
|
-
// Keep the one connection: every new one's startup waits behind any open transaction.
|
|
32
|
-
idleTimeoutMillis: 0,
|
|
33
|
-
types: pgTypesFor(required.pg, PG_PARSERS),
|
|
34
|
-
});
|
|
35
|
-
// An idle connection dropped by the owner (restart, idle-in-transaction timeout) is evicted by the
|
|
36
|
-
// pool and reopened on next use; without a listener it would crash the process.
|
|
37
|
-
pool.on("error", () => { });
|
|
38
|
-
const base = new Kysely({ dialect: new PostgresDialect({ pool }) });
|
|
39
|
-
return buildKernel({
|
|
40
|
-
dialect: "postgres",
|
|
41
|
-
transport: "pglite-socket",
|
|
42
|
-
capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: false },
|
|
43
|
-
ready: Promise.resolve(),
|
|
44
|
-
base,
|
|
45
|
-
oneConnection: true,
|
|
46
|
-
begin: (body) => base.transaction().execute((tx) => body(tx)),
|
|
47
|
-
lockKey: postgresLockKey,
|
|
48
|
-
close: () => base.destroy(),
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
//# sourceMappingURL=pglite-socket.js.map
|
package/dist/sqlite/driver.d.ts
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { type StorageKernel } from "../kernel/index.js";
|
|
2
|
-
import type { SqliteClient, SqliteOpener } from "./types.js";
|
|
3
|
-
/**
|
|
4
|
-
* @file The better-sqlite3 driver: a kernel over an ALREADY OPEN SQLite connection the consumer
|
|
5
|
-
* opened (and migrated) itself. Wrapping instead of opening keeps an existing database exactly as it
|
|
6
|
-
* was: same file, same pragmas, same migrations.
|
|
7
|
-
*
|
|
8
|
-
* This package never imports better-sqlite3: the consumer passes its own client (or, for
|
|
9
|
-
* {@link openSqliteFileKernel}, its own opener). Two copies of the SQLite library in one process
|
|
10
|
-
* would share POSIX locks, a documented way to corrupt a database. Accepts an ORM handle that
|
|
11
|
-
* carries its client as `$client` (Drizzle's shape) and reads the client; the handle itself is not
|
|
12
|
-
* used. ONE kernel per connection ({@link sqliteKernel} memoizes on the
|
|
13
|
-
* client): the transaction scope only protects callers that share it. The turn lock is per FILE:
|
|
14
|
-
* every connection to one database file in this process takes turns on the same lock (see
|
|
15
|
-
* `KernelDriver.turnLock`).
|
|
16
|
-
*
|
|
17
|
-
* Queries go through Kysely's own SQLite dialect over a thin binding shim: SQLite cannot bind a
|
|
18
|
-
* boolean, so `true`/`false` are written as `1`/`0` (the usual SQLite boolean encoding). Reads
|
|
19
|
-
* of those columns come back as `0`/`1` — the generated types say `SqlBool` so a repo converts.
|
|
20
|
-
*
|
|
21
|
-
* Transactions are `BEGIN IMMEDIATE` on the connection, not Kysely's `transaction()` (which issues a
|
|
22
|
-
* deferred `BEGIN`): IMMEDIATE takes the write lock up front, which is what makes `lockKey` a no-op
|
|
23
|
-
* here and keeps read-then-write sequences from failing with SQLITE_BUSY halfway through.
|
|
24
|
-
*
|
|
25
|
-
* The connection's opener closes it; `close()` here does nothing.
|
|
26
|
-
*/
|
|
27
|
-
export type SqliteKernel<DB> = StorageKernel<DB>;
|
|
28
|
-
/** An ORM handle that carries its better-sqlite3 client as `$client`, or the client itself. */
|
|
29
|
-
export type SqliteConnectionSource = SqliteClient | {
|
|
30
|
-
readonly $client: SqliteClient;
|
|
31
|
-
};
|
|
32
|
-
/** The better-sqlite3 client under `source` (a handle's `$client`, or the client itself). */
|
|
33
|
-
export declare function sqliteClientOf(source: SqliteConnectionSource): SqliteClient;
|
|
34
|
-
export declare function sqliteKernel<DB>(source: SqliteConnectionSource): SqliteKernel<DB>;
|
|
35
|
-
/**
|
|
36
|
-
* A kernel over a new private in-memory SQLite database (foreign keys on). `close()` closes the
|
|
37
|
-
* connection. For scratch work, e.g. building a reference schema.
|
|
38
|
-
*
|
|
39
|
-
* @param required.open the consumer's better-sqlite3 opener, e.g. `(p, o) => new Database(p, o)`.
|
|
40
|
-
*/
|
|
41
|
-
export declare function openMemorySqliteKernel<DB>(required: {
|
|
42
|
-
open: SqliteOpener;
|
|
43
|
-
}): SqliteKernel<DB>;
|
|
44
|
-
/**
|
|
45
|
-
* A kernel over its OWN connection to the SQLite file at `filePath`, opened as-is: no migration, no
|
|
46
|
-
* WAL switch, foreign keys on, a 5 s busy timeout. `close()` closes the connection.
|
|
47
|
-
*
|
|
48
|
-
* For ops on a database file that is not the running app's (a duplicate being prepared, a directory
|
|
49
|
-
* being inspected). `readOnly` opens with better-sqlite3's own `readonly` mode, so SQLite itself
|
|
50
|
-
* rejects any write, and requires the file to exist.
|
|
51
|
-
*
|
|
52
|
-
* @param required.open the consumer's better-sqlite3 opener, e.g. `(p, o) => new Database(p, o)`,
|
|
53
|
-
* so the connection comes from the consumer's own copy of the library.
|
|
54
|
-
* @throws whatever the opener throws opening the file (missing file when `readOnly`, not a
|
|
55
|
-
* database, locked).
|
|
56
|
-
*/
|
|
57
|
-
export declare function openSqliteFileKernel<DB>(required: {
|
|
58
|
-
filePath: string;
|
|
59
|
-
open: SqliteOpener;
|
|
60
|
-
}, optional?: {
|
|
61
|
-
readOnly?: boolean;
|
|
62
|
-
}): SqliteKernel<DB>;
|
|
63
|
-
/**
|
|
64
|
-
* Closes the better-sqlite3 connection under `source` (a handle carrying `$client`, or the client)
|
|
65
|
-
* and forgets its kernel. For callers that opened a database themselves and must
|
|
66
|
-
* release it; the kernel's own `close()` never closes a connection it did not open.
|
|
67
|
-
*/
|
|
68
|
-
export declare function closeSqliteConnection(source: SqliteConnectionSource): void;
|
|
69
|
-
/** The connection under a kernel this driver built, for the SQLite `StorageOps` (`./ops.ts`). */
|
|
70
|
-
export declare function sqliteConnectionOf<DB>(kernel: StorageKernel<DB>): SqliteClient | undefined;
|
|
71
|
-
//# sourceMappingURL=driver.d.ts.map
|
package/dist/sqlite/driver.js
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
|
-
import { Kysely, SqliteDialect } from "kysely";
|
|
3
|
-
import { buildKernel, TurnLock } from "../kernel/index.js";
|
|
4
|
-
const kernels = new WeakMap();
|
|
5
|
-
/** The reverse of `kernels`, plus the owning kernels {@link openSqliteFileKernel} hands out. */
|
|
6
|
-
const connectionsByKernel = new WeakMap();
|
|
7
|
-
/** One turn lock per database FILE, shared by every connection to it in this process. */
|
|
8
|
-
const fileTurnLocks = new Map();
|
|
9
|
-
function turnLockFor(client) {
|
|
10
|
-
if (client.memory)
|
|
11
|
-
return undefined;
|
|
12
|
-
const file = path.resolve(client.name);
|
|
13
|
-
let lock = fileTurnLocks.get(file);
|
|
14
|
-
if (lock === undefined) {
|
|
15
|
-
lock = new TurnLock();
|
|
16
|
-
fileTurnLocks.set(file, lock);
|
|
17
|
-
}
|
|
18
|
-
return lock;
|
|
19
|
-
}
|
|
20
|
-
/** The better-sqlite3 client under `source` (a handle's `$client`, or the client itself). */
|
|
21
|
-
export function sqliteClientOf(source) {
|
|
22
|
-
return "$client" in source ? source.$client : source;
|
|
23
|
-
}
|
|
24
|
-
const bindable = (value) => (typeof value === "boolean" ? (value ? 1 : 0) : value);
|
|
25
|
-
/** better-sqlite3 as Kysely's `SqliteDatabase`, with booleans bound as integers. */
|
|
26
|
-
function bindingShim(client) {
|
|
27
|
-
return {
|
|
28
|
-
close: () => { },
|
|
29
|
-
prepare(sqlText) {
|
|
30
|
-
const statement = client.prepare(sqlText);
|
|
31
|
-
const bind = (parameters) => parameters.map(bindable);
|
|
32
|
-
return {
|
|
33
|
-
reader: statement.reader,
|
|
34
|
-
all: (parameters) => statement.all(bind(parameters)),
|
|
35
|
-
run: (parameters) => statement.run(bind(parameters)),
|
|
36
|
-
iterate: (parameters) => statement.iterate(bind(parameters)),
|
|
37
|
-
};
|
|
38
|
-
},
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
export function sqliteKernel(source) {
|
|
42
|
-
const client = sqliteClientOf(source);
|
|
43
|
-
const known = kernels.get(client);
|
|
44
|
-
if (known !== undefined)
|
|
45
|
-
return known;
|
|
46
|
-
const base = new Kysely({ dialect: new SqliteDialect({ database: bindingShim(client) }) });
|
|
47
|
-
const kernel = buildKernel({
|
|
48
|
-
dialect: "sqlite",
|
|
49
|
-
transport: "better-sqlite3",
|
|
50
|
-
capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: true },
|
|
51
|
-
ready: Promise.resolve(),
|
|
52
|
-
base,
|
|
53
|
-
oneConnection: true,
|
|
54
|
-
turnLock: turnLockFor(client),
|
|
55
|
-
async begin(body) {
|
|
56
|
-
client.exec("BEGIN IMMEDIATE");
|
|
57
|
-
try {
|
|
58
|
-
const result = await body(base);
|
|
59
|
-
client.exec("COMMIT");
|
|
60
|
-
return result;
|
|
61
|
-
}
|
|
62
|
-
catch (error) {
|
|
63
|
-
if (client.inTransaction)
|
|
64
|
-
client.exec("ROLLBACK");
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
},
|
|
68
|
-
// BEGIN IMMEDIATE already holds the database write lock for the whole transaction.
|
|
69
|
-
lockKey: async () => { },
|
|
70
|
-
foreignTransactionOpen: () => client.inTransaction,
|
|
71
|
-
backup: async (destPath) => {
|
|
72
|
-
await client.backup(destPath);
|
|
73
|
-
},
|
|
74
|
-
close: async () => { },
|
|
75
|
-
});
|
|
76
|
-
kernels.set(client, kernel);
|
|
77
|
-
connectionsByKernel.set(kernel, client);
|
|
78
|
-
return kernel;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* A kernel over a new private in-memory SQLite database (foreign keys on). `close()` closes the
|
|
82
|
-
* connection. For scratch work, e.g. building a reference schema.
|
|
83
|
-
*
|
|
84
|
-
* @param required.open the consumer's better-sqlite3 opener, e.g. `(p, o) => new Database(p, o)`.
|
|
85
|
-
*/
|
|
86
|
-
export function openMemorySqliteKernel(required) {
|
|
87
|
-
return openSqliteFileKernel({ filePath: ":memory:", open: required.open });
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* A kernel over its OWN connection to the SQLite file at `filePath`, opened as-is: no migration, no
|
|
91
|
-
* WAL switch, foreign keys on, a 5 s busy timeout. `close()` closes the connection.
|
|
92
|
-
*
|
|
93
|
-
* For ops on a database file that is not the running app's (a duplicate being prepared, a directory
|
|
94
|
-
* being inspected). `readOnly` opens with better-sqlite3's own `readonly` mode, so SQLite itself
|
|
95
|
-
* rejects any write, and requires the file to exist.
|
|
96
|
-
*
|
|
97
|
-
* @param required.open the consumer's better-sqlite3 opener, e.g. `(p, o) => new Database(p, o)`,
|
|
98
|
-
* so the connection comes from the consumer's own copy of the library.
|
|
99
|
-
* @throws whatever the opener throws opening the file (missing file when `readOnly`, not a
|
|
100
|
-
* database, locked).
|
|
101
|
-
*/
|
|
102
|
-
export function openSqliteFileKernel(required, optional = {}) {
|
|
103
|
-
const readOnly = optional.readOnly === true;
|
|
104
|
-
const client = required.open(required.filePath, readOnly ? { readonly: true, fileMustExist: true } : {});
|
|
105
|
-
// A second connection to a file another may be writing: wait out a transient lock rather than
|
|
106
|
-
// throwing SQLITE_BUSY at once.
|
|
107
|
-
client.pragma("busy_timeout = 5000");
|
|
108
|
-
if (!readOnly)
|
|
109
|
-
client.pragma("foreign_keys = ON");
|
|
110
|
-
const kernel = sqliteKernel(client);
|
|
111
|
-
const owned = {
|
|
112
|
-
...kernel,
|
|
113
|
-
close: async () => closeSqliteConnection(client),
|
|
114
|
-
};
|
|
115
|
-
connectionsByKernel.set(owned, client);
|
|
116
|
-
return owned;
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Closes the better-sqlite3 connection under `source` (a handle carrying `$client`, or the client)
|
|
120
|
-
* and forgets its kernel. For callers that opened a database themselves and must
|
|
121
|
-
* release it; the kernel's own `close()` never closes a connection it did not open.
|
|
122
|
-
*/
|
|
123
|
-
export function closeSqliteConnection(source) {
|
|
124
|
-
const client = sqliteClientOf(source);
|
|
125
|
-
kernels.delete(client);
|
|
126
|
-
client.close();
|
|
127
|
-
}
|
|
128
|
-
/** The connection under a kernel this driver built, for the SQLite `StorageOps` (`./ops.ts`). */
|
|
129
|
-
export function sqliteConnectionOf(kernel) {
|
|
130
|
-
return connectionsByKernel.get(kernel);
|
|
131
|
-
}
|
|
132
|
-
//# sourceMappingURL=driver.js.map
|
package/dist/sqlite/ops.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { type StorageKernel, type StorageOps } from "../kernel/index.js";
|
|
2
|
-
/**
|
|
3
|
-
* The storage ops (`@jini-ai/db/kernel`'s `StorageOps`) for a kernel the sqlite driver built:
|
|
4
|
-
* `VACUUM INTO` for the copy; `VACUUM` + WAL checkpoint + `integrity_check` for compacting. Must be
|
|
5
|
-
* used outside a transaction.
|
|
6
|
-
*
|
|
7
|
-
* @throws {Error} a kernel this driver did not build (no connection to act on); an op called inside
|
|
8
|
-
* a transaction.
|
|
9
|
-
* @complexity each op is one full pass over the database file, O(size).
|
|
10
|
-
*/
|
|
11
|
-
export declare function sqliteOps<DB>(kernel: StorageKernel<DB>): StorageOps;
|
|
12
|
-
//# sourceMappingURL=ops.d.ts.map
|
package/dist/sqlite/ops.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import { outsideTransactionOf, StorageOpError } from "../kernel/index.js";
|
|
2
|
-
import { sqliteConnectionOf } from "./driver.js";
|
|
3
|
-
/**
|
|
4
|
-
* The storage ops (`@jini-ai/db/kernel`'s `StorageOps`) for a kernel the sqlite driver built:
|
|
5
|
-
* `VACUUM INTO` for the copy; `VACUUM` + WAL checkpoint + `integrity_check` for compacting. Must be
|
|
6
|
-
* used outside a transaction.
|
|
7
|
-
*
|
|
8
|
-
* @throws {Error} a kernel this driver did not build (no connection to act on); an op called inside
|
|
9
|
-
* a transaction.
|
|
10
|
-
* @complexity each op is one full pass over the database file, O(size).
|
|
11
|
-
*/
|
|
12
|
-
export function sqliteOps(kernel) {
|
|
13
|
-
const client = sqliteConnectionOf(kernel);
|
|
14
|
-
if (client === undefined)
|
|
15
|
-
throw new Error("sqliteOps: this SQLite kernel was not built by the sqlite driver");
|
|
16
|
-
const outsideTransaction = outsideTransactionOf(kernel);
|
|
17
|
-
return {
|
|
18
|
-
async copyTo(targetPath) {
|
|
19
|
-
outsideTransaction("copyTo");
|
|
20
|
-
// Bound parameter: VACUUM INTO takes an expression, so the path is never spliced into SQL.
|
|
21
|
-
client.prepare("VACUUM INTO ?").run(targetPath);
|
|
22
|
-
},
|
|
23
|
-
async compactAndVerify() {
|
|
24
|
-
outsideTransaction("compactAndVerify");
|
|
25
|
-
client.exec("VACUUM");
|
|
26
|
-
// WAL switch and checkpoint BEFORE integrity_check: running the check first on a just-VACUUMed
|
|
27
|
-
// connection reproducibly left a lock that failed the checkpoint with SQLITE_LOCKED.
|
|
28
|
-
client.pragma("journal_mode = WAL");
|
|
29
|
-
const [checkpoint] = client.pragma("wal_checkpoint(TRUNCATE)");
|
|
30
|
-
if (checkpoint === undefined || checkpoint.busy !== 0) {
|
|
31
|
-
throw new StorageOpError(`final WAL checkpoint on ${client.name} reported busy=${checkpoint?.busy}`);
|
|
32
|
-
}
|
|
33
|
-
const [integrity] = client.pragma("integrity_check");
|
|
34
|
-
if (integrity?.integrity_check !== "ok") {
|
|
35
|
-
throw new StorageOpError(`${client.name} failed integrity_check: ${JSON.stringify(integrity)}`);
|
|
36
|
-
}
|
|
37
|
-
},
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
//# sourceMappingURL=ops.js.map
|