@jini-ai/db 0.2.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.
Files changed (157) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE.pglite-socket +176 -0
  3. package/NOTICE.md +27 -0
  4. package/README.md +210 -0
  5. package/dist/core/artifact-naming.d.ts +34 -0
  6. package/dist/core/artifact-naming.js +34 -0
  7. package/dist/core/index.d.ts +8 -0
  8. package/dist/core/index.js +10 -0
  9. package/dist/core/messages.d.ts +43 -0
  10. package/dist/core/messages.js +26 -0
  11. package/dist/core/pg-types.d.ts +22 -0
  12. package/dist/core/pg-types.js +26 -0
  13. package/dist/core/ports.d.ts +70 -0
  14. package/dist/core/ports.js +22 -0
  15. package/dist/core/row-values.d.ts +32 -0
  16. package/dist/core/row-values.js +42 -0
  17. package/dist/core/socket.d.ts +8 -0
  18. package/dist/core/socket.js +8 -0
  19. package/dist/kernel/dialect.d.ts +83 -0
  20. package/dist/kernel/dialect.js +191 -0
  21. package/dist/kernel/index.d.ts +15 -0
  22. package/dist/kernel/index.js +15 -0
  23. package/dist/kernel/kernel-core.d.ts +43 -0
  24. package/dist/kernel/kernel-core.js +98 -0
  25. package/dist/kernel/ops.d.ts +48 -0
  26. package/dist/kernel/ops.js +49 -0
  27. package/dist/kernel/pg-types.d.ts +22 -0
  28. package/dist/kernel/pg-types.js +26 -0
  29. package/dist/kernel/pglite/dialect.d.ts +11 -0
  30. package/dist/kernel/pglite/dialect.js +88 -0
  31. package/dist/kernel/pglite/driver.d.ts +30 -0
  32. package/dist/kernel/pglite/driver.js +47 -0
  33. package/dist/kernel/pglite/index.d.ts +5 -0
  34. package/dist/kernel/pglite/index.js +5 -0
  35. package/dist/kernel/pglite/ops.d.ts +39 -0
  36. package/dist/kernel/pglite/ops.js +78 -0
  37. package/dist/kernel/port.d.ts +82 -0
  38. package/dist/kernel/port.js +11 -0
  39. package/dist/kernel/postgres/driver.d.ts +23 -0
  40. package/dist/kernel/postgres/driver.js +42 -0
  41. package/dist/kernel/postgres/index.d.ts +5 -0
  42. package/dist/kernel/postgres/index.js +5 -0
  43. package/dist/kernel/postgres/ops.d.ts +12 -0
  44. package/dist/kernel/postgres/ops.js +46 -0
  45. package/dist/kernel/postgres/pglite-socket.d.ts +23 -0
  46. package/dist/kernel/postgres/pglite-socket.js +52 -0
  47. package/dist/kernel/postgres-lock.d.ts +8 -0
  48. package/dist/kernel/postgres-lock.js +10 -0
  49. package/dist/kernel/schema-scope.d.ts +14 -0
  50. package/dist/kernel/schema-scope.js +20 -0
  51. package/dist/kernel/schema-shape.d.ts +26 -0
  52. package/dist/kernel/schema-shape.js +83 -0
  53. package/dist/kernel/socket.d.ts +8 -0
  54. package/dist/kernel/socket.js +8 -0
  55. package/dist/kernel/sqlite/driver.d.ts +71 -0
  56. package/dist/kernel/sqlite/driver.js +132 -0
  57. package/dist/kernel/sqlite/index.d.ts +4 -0
  58. package/dist/kernel/sqlite/index.js +4 -0
  59. package/dist/kernel/sqlite/ops.d.ts +12 -0
  60. package/dist/kernel/sqlite/ops.js +40 -0
  61. package/dist/kernel/store-copy.d.ts +82 -0
  62. package/dist/kernel/store-copy.js +240 -0
  63. package/dist/kernel/turn-lock.d.ts +21 -0
  64. package/dist/kernel/turn-lock.js +42 -0
  65. package/dist/kernel/typegen.d.ts +13 -0
  66. package/dist/kernel/typegen.js +76 -0
  67. package/dist/migrate/checksum.d.ts +11 -0
  68. package/dist/migrate/checksum.js +14 -0
  69. package/dist/migrate/index.d.ts +8 -0
  70. package/dist/migrate/index.js +8 -0
  71. package/dist/migrate/runner.d.ts +33 -0
  72. package/dist/migrate/runner.js +126 -0
  73. package/dist/migrate/step.d.ts +37 -0
  74. package/dist/migrate/step.js +31 -0
  75. package/dist/pglite/dialect.d.ts +11 -0
  76. package/dist/pglite/dialect.js +88 -0
  77. package/dist/pglite/driver.d.ts +30 -0
  78. package/dist/pglite/driver.js +46 -0
  79. package/dist/pglite/index.d.ts +5 -0
  80. package/dist/pglite/index.js +4 -0
  81. package/dist/pglite/ops.d.ts +39 -0
  82. package/dist/pglite/ops.js +78 -0
  83. package/dist/pglite/owner.d.ts +107 -0
  84. package/dist/pglite/owner.js +359 -0
  85. package/dist/pglite/socket-server.d.ts +38 -0
  86. package/dist/pglite/socket-server.js +375 -0
  87. package/dist/pglite/types.d.ts +9 -0
  88. package/dist/pglite/types.js +2 -0
  89. package/dist/postgres/driver.d.ts +23 -0
  90. package/dist/postgres/driver.js +41 -0
  91. package/dist/postgres/index.d.ts +3 -0
  92. package/dist/postgres/index.js +3 -0
  93. package/dist/postgres/ops.d.ts +12 -0
  94. package/dist/postgres/ops.js +46 -0
  95. package/dist/postgres/pglite-socket.d.ts +23 -0
  96. package/dist/postgres/pglite-socket.js +51 -0
  97. package/dist/postgres/types.d.ts +53 -0
  98. package/dist/postgres/types.js +14 -0
  99. package/dist/sqlite/db-ops.d.ts +59 -0
  100. package/dist/sqlite/db-ops.js +82 -0
  101. package/dist/sqlite/driver.d.ts +71 -0
  102. package/dist/sqlite/driver.js +132 -0
  103. package/dist/sqlite/index.d.ts +9 -0
  104. package/dist/sqlite/index.js +4 -0
  105. package/dist/sqlite/inspect.d.ts +60 -0
  106. package/dist/sqlite/inspect.js +153 -0
  107. package/dist/sqlite/open.d.ts +58 -0
  108. package/dist/sqlite/open.js +43 -0
  109. package/dist/sqlite/ops.d.ts +12 -0
  110. package/dist/sqlite/ops.js +40 -0
  111. package/dist/sqlite/restore-types.d.ts +42 -0
  112. package/dist/sqlite/restore-types.js +2 -0
  113. package/dist/sqlite/sync-types.d.ts +34 -0
  114. package/dist/sqlite/sync-types.js +2 -0
  115. package/dist/sqlite/types.d.ts +37 -0
  116. package/dist/sqlite/types.js +8 -0
  117. package/dist/tools/database-catalog.d.ts +61 -0
  118. package/dist/tools/database-catalog.js +201 -0
  119. package/dist/tools/destination-port.d.ts +27 -0
  120. package/dist/tools/destination-port.js +2 -0
  121. package/dist/tools/index.d.ts +13 -0
  122. package/dist/tools/index.js +11 -0
  123. package/dist/tools/plan-store.d.ts +61 -0
  124. package/dist/tools/plan-store.js +39 -0
  125. package/dist/tools/read-tools.d.ts +53 -0
  126. package/dist/tools/read-tools.js +97 -0
  127. package/dist/tools/registration.d.ts +18 -0
  128. package/dist/tools/registration.js +10 -0
  129. package/dist/tools/restore-points.d.ts +125 -0
  130. package/dist/tools/restore-points.js +54 -0
  131. package/dist/tools/surface-port.d.ts +43 -0
  132. package/dist/tools/surface-port.js +2 -0
  133. package/dist/tools/timeline.d.ts +63 -0
  134. package/dist/tools/timeline.js +46 -0
  135. package/dist/tools/transfer-catalog.d.ts +25 -0
  136. package/dist/tools/transfer-catalog.js +59 -0
  137. package/dist/tools/transfer-tools.d.ts +82 -0
  138. package/dist/tools/transfer-tools.js +346 -0
  139. package/dist/transfer/copy-engine.d.ts +129 -0
  140. package/dist/transfer/copy-engine.js +233 -0
  141. package/dist/transfer/index.d.ts +9 -0
  142. package/dist/transfer/index.js +9 -0
  143. package/dist/transfer/internal-ddl.d.ts +23 -0
  144. package/dist/transfer/internal-ddl.js +119 -0
  145. package/dist/transfer/plan.d.ts +28 -0
  146. package/dist/transfer/plan.js +19 -0
  147. package/dist/transfer/postgres-ddl.d.ts +36 -0
  148. package/dist/transfer/postgres-ddl.js +16 -0
  149. package/dist/transfer/postgres-target.d.ts +65 -0
  150. package/dist/transfer/postgres-target.js +95 -0
  151. package/dist/transfer/sqlite-source.d.ts +78 -0
  152. package/dist/transfer/sqlite-source.js +79 -0
  153. package/dist/transfer/table-catalog.d.ts +44 -0
  154. package/dist/transfer/table-catalog.js +109 -0
  155. package/dist/transfer/types.d.ts +47 -0
  156. package/dist/transfer/types.js +2 -0
  157. package/package.json +184 -0
@@ -0,0 +1,98 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { UnsupportedCapabilityError, } from "./port.js";
3
+ import { TurnLock } from "./turn-lock.js";
4
+ /** The turn locks the caller's async context holds, across every kernel in the process. */
5
+ const heldLocks = new AsyncLocalStorage();
6
+ /**
7
+ * Takes `lock` for `body`, unless this call chain already holds it through ANOTHER kernel (a second
8
+ * connection to the same database): that would wait on its own turn forever, so it throws.
9
+ */
10
+ async function takingTurn(lock, kind, body) {
11
+ if (lock === undefined)
12
+ return body();
13
+ const held = heldLocks.getStore();
14
+ if (held?.has(lock)) {
15
+ throw new Error("this call chain already holds another connection to the same database file; use one connection (one kernel) for the whole unit of work");
16
+ }
17
+ await lock.acquire(kind);
18
+ try {
19
+ return await heldLocks.run(new Set([...(held ?? []), lock]), body);
20
+ }
21
+ finally {
22
+ lock.release(kind);
23
+ }
24
+ }
25
+ export function buildKernel(driver) {
26
+ const scope = new AsyncLocalStorage();
27
+ const lock = driver.oneConnection ? (driver.turnLock ?? new TurnLock()) : undefined;
28
+ let ownTransactions = 0;
29
+ const joinsForeign = () => ownTransactions === 0 && driver.foreignTransactionOpen?.() === true;
30
+ function require(capability) {
31
+ if (!driver.capabilities[capability])
32
+ throw new UnsupportedCapabilityError(capability, driver.transport);
33
+ }
34
+ async function run(fn) {
35
+ await driver.ready;
36
+ const current = scope.getStore();
37
+ if (current !== undefined)
38
+ return fn(current.db);
39
+ if (joinsForeign())
40
+ return fn(driver.base);
41
+ return takingTurn(lock, "shared", async () => scope.run({ kind: "run", db: driver.base }, () => fn(driver.base)));
42
+ }
43
+ async function transaction(fn) {
44
+ require("interactiveTransactions");
45
+ await driver.ready;
46
+ const current = scope.getStore();
47
+ if (current?.kind === "transaction")
48
+ return fn();
49
+ if (current?.kind === "run") {
50
+ throw new Error("transaction() was called inside a run() body; start the transaction first and call run() inside it");
51
+ }
52
+ if (joinsForeign())
53
+ return fn();
54
+ return takingTurn(lock, "exclusive", async () => {
55
+ ownTransactions += 1;
56
+ try {
57
+ return await driver.begin((tx) => scope.run({ kind: "transaction", db: tx }, fn));
58
+ }
59
+ finally {
60
+ ownTransactions -= 1;
61
+ }
62
+ });
63
+ }
64
+ async function lockKey(key) {
65
+ const current = scope.getStore();
66
+ // A joined legacy transaction counts: it is the same `BEGIN IMMEDIATE` on SQLite.
67
+ if (current?.kind !== "transaction" && !joinsForeign()) {
68
+ throw new Error("lockKey() must be called inside transaction()");
69
+ }
70
+ await driver.lockKey(current?.db ?? driver.base, key);
71
+ }
72
+ return {
73
+ dialect: driver.dialect,
74
+ transport: driver.transport,
75
+ capabilities: driver.capabilities,
76
+ ready: driver.ready,
77
+ run,
78
+ transaction,
79
+ lockKey,
80
+ query: async (statement) => (await run((db) => statement.execute(db))).rows,
81
+ execute: async (statement) => {
82
+ await run((db) => statement.execute(db));
83
+ },
84
+ inTransaction: () => scope.getStore()?.kind === "transaction",
85
+ require,
86
+ async backupTo(destPath) {
87
+ require("backup");
88
+ if (driver.backup === undefined)
89
+ throw new UnsupportedCapabilityError("backup", driver.transport);
90
+ if (scope.getStore()?.kind === "transaction")
91
+ throw new Error("backupTo() must be called outside a transaction");
92
+ await driver.ready;
93
+ await driver.backup(destPath);
94
+ },
95
+ close: () => driver.close(),
96
+ };
97
+ }
98
+ //# sourceMappingURL=kernel-core.js.map
@@ -0,0 +1,48 @@
1
+ import type { StorageKernel, StorageTransport } from "./port.js";
2
+ /**
3
+ * @file The storage ops port: whole-database FILE operations, which every dialect spells
4
+ * differently and which are not queries (copying a database, compacting and sealing it). Queries go
5
+ * through `StorageKernel.run`; a whole-database backup is `StorageKernel.backupTo`.
6
+ *
7
+ * Each driver subpath implements it (`sqliteOps`, `pgliteOps`, `postgresOps`); this file holds only
8
+ * the contract and the pieces they share, so it reaches no driver.
9
+ */
10
+ export interface StorageOps {
11
+ /**
12
+ * Writes a physically consistent copy of the whole database to `targetPath` (which must not
13
+ * exist), read through this connection — so anything still parked in a write-ahead log is
14
+ * included — without writing the source (works on a read-only open).
15
+ * @throws the driver's own error (target exists, directory not writable, source locked).
16
+ */
17
+ copyTo(targetPath: string): Promise<void>;
18
+ /**
19
+ * Reclaims free pages, leaves the database with no pending journal (a sealed file with no
20
+ * sidecars, in WAL mode on SQLite), then verifies its integrity.
21
+ * @throws {StorageOpError} a busy final checkpoint or a failed integrity check.
22
+ */
23
+ compactAndVerify(): Promise<void>;
24
+ }
25
+ /** An op this driver has no implementation of. `reason` says what to do instead, when there is something. */
26
+ export declare class StorageOpNotSupportedError extends Error {
27
+ readonly op: keyof StorageOps;
28
+ readonly transport: StorageTransport;
29
+ constructor(op: keyof StorageOps, transport: StorageTransport, reason?: string);
30
+ }
31
+ /** An op that ran but found the database in a state it must not hand back. */
32
+ export declare class StorageOpError extends Error {
33
+ constructor(message: string);
34
+ }
35
+ /**
36
+ * A guard each op calls first: neither SQLite nor Postgres can `VACUUM` inside a transaction.
37
+ * @throws {Error} when `kernel` is inside a transaction.
38
+ */
39
+ export declare function outsideTransactionOf(kernel: StorageKernel<unknown>): (op: keyof StorageOps) => void;
40
+ /**
41
+ * The read-back that ends a Postgres-family compaction: the migration ledger the consumer names must
42
+ * still be readable and non-empty. The ledger name is the consumer's (no default), because this
43
+ * package ships no tables.
44
+ *
45
+ * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
46
+ */
47
+ export declare function verifyLedgerReadBack(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<void>;
48
+ //# sourceMappingURL=ops.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { sql } from "kysely";
2
+ /** An op this driver has no implementation of. `reason` says what to do instead, when there is something. */
3
+ export class StorageOpNotSupportedError extends Error {
4
+ op;
5
+ transport;
6
+ constructor(op, transport, reason) {
7
+ super(reason === undefined ? `storage op ${op} is not supported on the ${transport} driver` : `storage op ${op} is not supported on the ${transport} driver: ${reason}`);
8
+ this.op = op;
9
+ this.transport = transport;
10
+ this.name = "StorageOpNotSupportedError";
11
+ }
12
+ }
13
+ /** An op that ran but found the database in a state it must not hand back. */
14
+ export class StorageOpError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "StorageOpError";
18
+ }
19
+ }
20
+ /**
21
+ * A guard each op calls first: neither SQLite nor Postgres can `VACUUM` inside a transaction.
22
+ * @throws {Error} when `kernel` is inside a transaction.
23
+ */
24
+ export function outsideTransactionOf(kernel) {
25
+ return (op) => {
26
+ if (kernel.inTransaction())
27
+ throw new Error(`storage op ${op} must be called outside a transaction`);
28
+ };
29
+ }
30
+ /**
31
+ * The read-back that ends a Postgres-family compaction: the migration ledger the consumer names must
32
+ * still be readable and non-empty. The ledger name is the consumer's (no default), because this
33
+ * package ships no tables.
34
+ *
35
+ * @throws {StorageOpError} the ledger cannot be read, or holds no rows.
36
+ */
37
+ export async function verifyLedgerReadBack(kernel, ledgerTable) {
38
+ let steps;
39
+ try {
40
+ const [row] = await kernel.query(sql `SELECT count(*)::int AS n FROM ${sql.table(ledgerTable)}`);
41
+ steps = row?.n ?? 0;
42
+ }
43
+ catch (err) {
44
+ throw new StorageOpError(`the migration ledger ${ledgerTable} cannot be read back: ${err.message}`);
45
+ }
46
+ if (steps === 0)
47
+ throw new StorageOpError(`the migration ledger ${ledgerTable} is empty after compacting`);
48
+ }
49
+ //# sourceMappingURL=ops.js.map
@@ -0,0 +1,22 @@
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
@@ -0,0 +1,26 @@
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
@@ -0,0 +1,11 @@
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
@@ -0,0 +1,88 @@
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
@@ -0,0 +1,30 @@
1
+ import type { PGlite } from "@electric-sql/pglite";
2
+ import { type StorageKernel } from "../index.js";
3
+ import type { PgliteClass } from "../../pglite/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
@@ -0,0 +1,47 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { writeFile } from "node:fs/promises";
3
+ import { Kysely } from "kysely";
4
+ import { PG_PARSERS } from "../../core/index.js";
5
+ import { buildKernel, postgresLockKey } from "../index.js";
6
+ import { PgliteDialect } from "./dialect.js";
7
+ /**
8
+ * Opens (and on first use creates) a PGlite database. Synchronous so it fits the synchronous
9
+ * composition root; the async setup runs behind `ready`, which every kernel call awaits.
10
+ *
11
+ * @param required.PGlite the consumer's `PGlite` class (this package never imports it).
12
+ * @param optional.dataDir absent = in-memory (tests).
13
+ * @param optional.prepare runs once after open, before any call (e.g. schema creation).
14
+ */
15
+ export function openPgliteKernel(required, optional = {}) {
16
+ if (optional.dataDir !== undefined)
17
+ mkdirSync(optional.dataDir, { recursive: true });
18
+ // One options object: PGlite drops the second argument when the first (dataDir) is undefined.
19
+ const client = new required.PGlite({ ...(optional.dataDir === undefined ? {} : { dataDir: optional.dataDir }), parsers: PG_PARSERS });
20
+ const base = new Kysely({ dialect: new PgliteDialect(client) });
21
+ const ready = (async () => {
22
+ await client.waitReady;
23
+ await optional.prepare?.(client);
24
+ })();
25
+ // Surfaced by every call that awaits `ready`; this only stops an unhandled-rejection crash when
26
+ // nothing has called in yet.
27
+ ready.catch(() => { });
28
+ return buildKernel({
29
+ dialect: "postgres",
30
+ transport: "pglite",
31
+ capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: true },
32
+ ready,
33
+ base,
34
+ oneConnection: true,
35
+ begin: (body) => base.transaction().execute((tx) => body(tx)),
36
+ lockKey: postgresLockKey,
37
+ async backup(destPath) {
38
+ const dump = await client.dumpDataDir("none");
39
+ await writeFile(destPath, Buffer.from(await dump.arrayBuffer()));
40
+ },
41
+ async close() {
42
+ await ready.catch(() => { });
43
+ await client.close();
44
+ },
45
+ });
46
+ }
47
+ //# sourceMappingURL=driver.js.map
@@ -0,0 +1,5 @@
1
+ /** Kysely's PGlite binding and kernel storage operations. */
2
+ export { openPgliteKernel, type PgKernel } from "./driver.js";
3
+ export { PgliteDialect } from "./dialect.js";
4
+ export { pgliteOps, copyServedPgliteTo, type PgliteExclusive, type PgliteRestore } from "./ops.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Kysely's PGlite binding and kernel storage operations. */
2
+ export { openPgliteKernel } from "./driver.js";
3
+ export { PgliteDialect } from "./dialect.js";
4
+ export { pgliteOps, copyServedPgliteTo } from "./ops.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,39 @@
1
+ import type { PGlite } from "@electric-sql/pglite";
2
+ import { type StorageKernel, type StorageOps } from "../index.js";
3
+ import type { PgliteClass } from "../../pglite/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/kernel/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
@@ -0,0 +1,78 @@
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 "../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
@@ -0,0 +1,82 @@
1
+ import type { Kysely, RawBuilder } from "kysely";
2
+ /**
3
+ * @file The storage kernel port: the ONE async way a repo reaches its database, on every driver.
4
+ * Package: `@jini-ai/db/kernel` (no driver is imported here; each driver lives in its own subpath).
5
+ *
6
+ * A repo is ONE Kysely query body for every dialect. It never holds a raw handle, never runs
7
+ * `BEGIN`, never calls a driver API. It asks the kernel:
8
+ *
9
+ * - {@link StorageKernel.run} — run statements on the right executor: the open transaction when the
10
+ * caller is inside {@link StorageKernel.transaction}, else the base handle.
11
+ * - {@link StorageKernel.transaction} — one unit of work. A NESTED call joins the outer one (no
12
+ * savepoint), so a service composing two repos that each wrap themselves still commits or rolls
13
+ * back as one. Calling it from inside a `run()` body throws: that body holds the handle a
14
+ * transaction would wait for.
15
+ * - {@link StorageKernel.lockKey} — the explicit concurrency strategy for "nothing else may
16
+ * interleave here" (read-then-write sequences such as a ledger append). A transaction alone does
17
+ * not give that on Postgres (READ COMMITTED); this does, on every dialect.
18
+ * - {@link StorageKernel.query} — a portable Kysely `sql` statement returning rows. For dialect
19
+ * helpers, migrations and introspection (`dialect.ts`), not for repos.
20
+ *
21
+ * Three separate things describe a kernel (never inferred from each other, never cached per process):
22
+ * the SQL {@link StorageDialect}, the connection {@link StorageTransport}, and its
23
+ * {@link StorageCapabilities}. Asking for a capability the kernel lacks throws
24
+ * {@link UnsupportedCapabilityError}; nothing silently downgrades (e.g. a transaction never becomes
25
+ * "run the statements one by one").
26
+ *
27
+ * Drivers live in the `sqlite`, `pglite` and `postgres` subpaths. None of them imports a driver
28
+ * package: the consumer passes its own client, pool or class in.
29
+ */
30
+ /** SQL family: decides which dialect helper fragment applies. */
31
+ export type StorageDialect = "sqlite" | "postgres";
32
+ /** The connection underneath: an embedded engine, a network pool, or a PGlite owner's Unix socket. */
33
+ export type StorageTransport = "better-sqlite3" | "pglite" | "node-postgres" | "pglite-socket";
34
+ /** What this kernel instance can do. Checked per call; a missing one is an explicit error. */
35
+ export interface StorageCapabilities {
36
+ /** `transaction(fn)` with awaits (reads, logic) between statements. D1 and HTTP drivers: no. */
37
+ readonly interactiveTransactions: boolean;
38
+ /** Several statements applied all-or-nothing without an interactive transaction. */
39
+ readonly atomicBatch: boolean;
40
+ /** DDL inside a transaction rolls back with it. */
41
+ readonly transactionalDdl: boolean;
42
+ /** A consistent copy of the whole database can be taken through the driver (restore points). */
43
+ readonly backup: boolean;
44
+ }
45
+ export type StorageCapability = keyof StorageCapabilities;
46
+ export declare class UnsupportedCapabilityError extends Error {
47
+ readonly capability: StorageCapability;
48
+ readonly transport: StorageTransport;
49
+ constructor(capability: StorageCapability, transport: StorageTransport);
50
+ }
51
+ export interface StorageKernel<DB> {
52
+ readonly dialect: StorageDialect;
53
+ readonly transport: StorageTransport;
54
+ readonly capabilities: StorageCapabilities;
55
+ /** Resolves once the driver is open and its schema is in place. Every call below awaits it. */
56
+ readonly ready: Promise<void>;
57
+ run<T>(fn: (db: Kysely<DB>) => T | Promise<T>): Promise<T>;
58
+ /** Throws {@link UnsupportedCapabilityError} without `interactiveTransactions`. */
59
+ transaction<T>(fn: () => Promise<T>): Promise<T>;
60
+ /**
61
+ * Inside a transaction: blocks every other transaction that locks the same `key` until this one
62
+ * ends. Postgres: a transaction-scoped advisory lock. SQLite: nothing to do — the kernel's
63
+ * transactions take the database write lock at `BEGIN IMMEDIATE`, which already serializes them.
64
+ * Throws outside a transaction (a lock with no transaction to end it would never be released).
65
+ */
66
+ lockKey(key: string): Promise<void>;
67
+ query<Row>(statement: RawBuilder<Row>): Promise<Row[]>;
68
+ /** {@link query} for a statement that returns no rows (DDL, a write without `RETURNING`). */
69
+ execute(statement: RawBuilder<unknown>): Promise<void>;
70
+ /** True inside this kernel's own transaction (the caller's async context). */
71
+ inTransaction(): boolean;
72
+ /** Throws {@link UnsupportedCapabilityError} when this kernel lacks `capability`. */
73
+ require(capability: StorageCapability): void;
74
+ /**
75
+ * A consistent copy of the whole database written to `destPath` (SQLite: the online backup API,
76
+ * a normal SQLite file; PGlite: a data-dir tarball). Throws {@link UnsupportedCapabilityError}
77
+ * without `backup`. Call it outside a transaction.
78
+ */
79
+ backupTo(destPath: string): Promise<void>;
80
+ close(): Promise<void>;
81
+ }
82
+ //# sourceMappingURL=port.d.ts.map
@@ -0,0 +1,11 @@
1
+ export class UnsupportedCapabilityError extends Error {
2
+ capability;
3
+ transport;
4
+ constructor(capability, transport) {
5
+ super(`the ${transport} storage driver does not support ${capability}`);
6
+ this.capability = capability;
7
+ this.transport = transport;
8
+ this.name = "UnsupportedCapabilityError";
9
+ }
10
+ }
11
+ //# sourceMappingURL=port.js.map