@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,23 @@
1
+ import { type StorageKernel } from "../index.js";
2
+ import { type PgModule } from "../../postgres/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
@@ -0,0 +1,42 @@
1
+ import { Kysely, PostgresDialect } from "kysely";
2
+ import { PG_PARSERS } from "../../core/index.js";
3
+ import { buildKernel, postgresLockKey } from "../index.js";
4
+ import { pgTypesFor } from "../../postgres/types.js";
5
+ /**
6
+ * @file The node-postgres driver: a connection POOL to any Postgres server (local, Supabase, Neon).
7
+ * Kysely's own Postgres dialect; each transaction checks out its own connection, so unrelated
8
+ * requests run concurrently (no turn lock) and `lockKey` is what serializes the sequences that
9
+ * must not interleave.
10
+ *
11
+ * This package never imports `pg`: the consumer passes its own module (`import pg from "pg"`).
12
+ */
13
+ /**
14
+ * Opens a pooled kernel on the server at `connectionString`.
15
+ *
16
+ * @param required.pg the consumer's node-postgres module.
17
+ * @param optional.max pool size, default 10.
18
+ */
19
+ export function openPostgresKernel(required, optional = {}) {
20
+ const pool = new required.pg.Pool({
21
+ connectionString: required.connectionString,
22
+ max: optional.max ?? 10,
23
+ types: pgTypesFor(required.pg, PG_PARSERS),
24
+ });
25
+ // An idle connection dropped by the server (restart, failover, pg_terminate_backend, a pooler's
26
+ // idle cut) is evicted by the pool and reopened on next use; without a listener it would crash the
27
+ // process.
28
+ pool.on("error", (err) => console.warn(`[postgres] idle pool connection dropped: ${err.message}`));
29
+ const base = new Kysely({ dialect: new PostgresDialect({ pool }) });
30
+ return buildKernel({
31
+ dialect: "postgres",
32
+ transport: "node-postgres",
33
+ capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: false },
34
+ ready: Promise.resolve(),
35
+ base,
36
+ oneConnection: false,
37
+ begin: (body) => base.transaction().execute((tx) => body(tx)),
38
+ lockKey: postgresLockKey,
39
+ close: () => base.destroy(),
40
+ });
41
+ }
42
+ //# sourceMappingURL=driver.js.map
@@ -0,0 +1,5 @@
1
+ /** Kysely's pooled Postgres and single-connection PGlite socket bindings. */
2
+ export { openPostgresKernel } from "./driver.js";
3
+ export { openPgliteSocketKernel } from "./pglite-socket.js";
4
+ export { postgresOps } from "./ops.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Kysely's pooled Postgres and single-connection PGlite socket bindings. */
2
+ export { openPostgresKernel } from "./driver.js";
3
+ export { openPgliteSocketKernel } from "./pglite-socket.js";
4
+ export { postgresOps } from "./ops.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import { type StorageKernel, type StorageOps } from "../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
@@ -0,0 +1,46 @@
1
+ import { sql } from "kysely";
2
+ import { outsideTransactionOf, StorageOpNotSupportedError, verifyLedgerReadBack, } from "../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/kernel/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
@@ -0,0 +1,23 @@
1
+ import { type StorageKernel } from "../index.js";
2
+ import { type PgModule } from "../../postgres/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
@@ -0,0 +1,52 @@
1
+ import { dirname } from "node:path";
2
+ import { Kysely, PostgresDialect } from "kysely";
3
+ import { PG_PARSERS, PGLITE_SOCKET_FILE } from "../../core/index.js";
4
+ import { buildKernel, postgresLockKey } from "../index.js";
5
+ import { pgTypesFor } from "../../postgres/types.js";
6
+ /**
7
+ * @file A storage kernel that reaches a PGlite data dir through its owner's Unix socket
8
+ * (`@jini-ai/db/pglite`'s `startPgliteOwner`): node-postgres with ONE connection and the kernel's turn lock, because PGlite
9
+ * is one backend session — a second connection gives no parallelism, and every client's transaction
10
+ * blocks every other client anyway. Every process sharing the data dir uses this.
11
+ *
12
+ * Kernel rules this transport makes hard: no `SET` (only `SET LOCAL`), no temp tables, no named
13
+ * prepared statements, no session advisory locks — all clients share one session, so any of those
14
+ * leaks into the other process. Backup is not offered here; it goes through the owner.
15
+ */
16
+ /**
17
+ * Opens a one-connection kernel on the PGlite owner socket at `socketPath`.
18
+ *
19
+ * @param required.pg the consumer's node-postgres module (`import pg from "pg"`).
20
+ * @throws {Error} a path that does not end in the Postgres socket file name.
21
+ */
22
+ export function openPgliteSocketKernel(required) {
23
+ if (!required.socketPath.endsWith(`/${PGLITE_SOCKET_FILE}`)) {
24
+ throw new Error(`a PGlite socket path ends in /${PGLITE_SOCKET_FILE}: ${required.socketPath}`);
25
+ }
26
+ const pool = new required.pg.Pool({
27
+ host: dirname(required.socketPath),
28
+ port: 5432,
29
+ user: "postgres",
30
+ database: "postgres",
31
+ max: 1,
32
+ // Keep the one connection: every new one's startup waits behind any open transaction.
33
+ idleTimeoutMillis: 0,
34
+ types: pgTypesFor(required.pg, PG_PARSERS),
35
+ });
36
+ // An idle connection dropped by the owner (restart, idle-in-transaction timeout) is evicted by the
37
+ // pool and reopened on next use; without a listener it would crash the process.
38
+ pool.on("error", () => { });
39
+ const base = new Kysely({ dialect: new PostgresDialect({ pool }) });
40
+ return buildKernel({
41
+ dialect: "postgres",
42
+ transport: "pglite-socket",
43
+ capabilities: { interactiveTransactions: true, atomicBatch: true, transactionalDdl: true, backup: false },
44
+ ready: Promise.resolve(),
45
+ base,
46
+ oneConnection: true,
47
+ begin: (body) => base.transaction().execute((tx) => body(tx)),
48
+ lockKey: postgresLockKey,
49
+ close: () => base.destroy(),
50
+ });
51
+ }
52
+ //# sourceMappingURL=pglite-socket.js.map
@@ -0,0 +1,8 @@
1
+ import { type Kysely } from "kysely";
2
+ /**
3
+ * `StorageKernel.lockKey` on Postgres: a transaction-scoped advisory lock on a 64-bit hash of the
4
+ * key, released by COMMIT/ROLLBACK. A hash collision only makes two unrelated keys wait for each
5
+ * other, never lets two holders of one key through.
6
+ */
7
+ export declare function postgresLockKey<DB>(tx: Kysely<DB>, key: string): Promise<void>;
8
+ //# sourceMappingURL=postgres-lock.d.ts.map
@@ -0,0 +1,10 @@
1
+ import { sql } from "kysely";
2
+ /**
3
+ * `StorageKernel.lockKey` on Postgres: a transaction-scoped advisory lock on a 64-bit hash of the
4
+ * key, released by COMMIT/ROLLBACK. A hash collision only makes two unrelated keys wait for each
5
+ * other, never lets two holders of one key through.
6
+ */
7
+ export async function postgresLockKey(tx, key) {
8
+ await sql `SELECT pg_advisory_xact_lock(hashtextextended(${key}, 0))`.execute(tx);
9
+ }
10
+ //# sourceMappingURL=postgres-lock.js.map
@@ -0,0 +1,14 @@
1
+ import type { StorageKernel } from "./port.js";
2
+ /**
3
+ * @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
4
+ * `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
5
+ * database holds several histories, each in its own schema.
6
+ *
7
+ * Not `SET search_path`: that is session state, which a shared PGlite connection (and a pooled
8
+ * node-postgres one) must never carry. `query`/`execute` take raw SQL, which no plugin rewrites:
9
+ * raw statements through a scoped kernel name their schema themselves.
10
+ *
11
+ * Transactions, locks and `close` are the underlying kernel's: one database, one connection pool.
12
+ */
13
+ export declare function scopeToSchema<DB>(kernel: StorageKernel<DB>, schema: string): StorageKernel<DB>;
14
+ //# sourceMappingURL=schema-scope.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
3
+ * `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
4
+ * database holds several histories, each in its own schema.
5
+ *
6
+ * Not `SET search_path`: that is session state, which a shared PGlite connection (and a pooled
7
+ * node-postgres one) must never carry. `query`/`execute` take raw SQL, which no plugin rewrites:
8
+ * raw statements through a scoped kernel name their schema themselves.
9
+ *
10
+ * Transactions, locks and `close` are the underlying kernel's: one database, one connection pool.
11
+ */
12
+ export function scopeToSchema(kernel, schema) {
13
+ if (kernel.dialect !== "postgres")
14
+ throw new Error(`schema '${schema}' needs a Postgres kernel, not ${kernel.dialect}`);
15
+ return {
16
+ ...kernel,
17
+ run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
18
+ };
19
+ }
20
+ //# sourceMappingURL=schema-scope.js.map
@@ -0,0 +1,26 @@
1
+ import type { StorageKernel } from "./port.js";
2
+ /**
3
+ * @file The physical schema of a database as comparable text, per table: columns (type, NOT NULL,
4
+ * default, key position), indexes (uniqueness, columns, partial predicate), foreign keys and — on
5
+ * SQLite — the table's own `CREATE` text (the only place SQLite keeps CHECK constraints). Used by the
6
+ * migration runner to verify an adopted database against a freshly built one, and by tests that
7
+ * hold a migration history to a declared schema. Two shapes are equal when the databases
8
+ * would accept and reject the same writes; object names SQLite generates itself are left out.
9
+ */
10
+ export interface TableShape {
11
+ columns: string[];
12
+ indexes: string[];
13
+ constraints: string[];
14
+ }
15
+ export interface SchemaShape {
16
+ tables: Record<string, TableShape>;
17
+ /** Views and triggers: `kind name: definition`. */
18
+ others: string[];
19
+ }
20
+ /** Every user table's shape (internal and `sqlite_`/`pg_` tables excluded), keyed by table name. */
21
+ export declare function readSchemaShape(kernel: StorageKernel<unknown>, optional?: {
22
+ exclude?: readonly string[];
23
+ }): Promise<SchemaShape>;
24
+ /** The main database file of a SQLite kernel; null for an in-memory database or a Postgres kernel. */
25
+ export declare function databaseFile<DB>(kernel: StorageKernel<DB>): Promise<string | null>;
26
+ //# sourceMappingURL=schema-shape.d.ts.map
@@ -0,0 +1,83 @@
1
+ import { sql } from "kysely";
2
+ const squash = (text) => (text ?? "").replace(/\s+/g, " ").trim();
3
+ /** Every user table's shape (internal and `sqlite_`/`pg_` tables excluded), keyed by table name. */
4
+ export async function readSchemaShape(kernel, optional = {}) {
5
+ const exclude = new Set(optional.exclude ?? []);
6
+ const shape = kernel.dialect === "sqlite" ? await sqliteShape(kernel) : await postgresShape(kernel);
7
+ for (const name of exclude)
8
+ delete shape.tables[name];
9
+ return shape;
10
+ }
11
+ async function sqliteShape(kernel) {
12
+ const objects = await kernel.query(sql `SELECT type, name, tbl_name, sql FROM sqlite_schema WHERE substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name`);
13
+ const tables = {};
14
+ const others = [];
15
+ for (const object of objects) {
16
+ if (object.type === "view" || object.type === "trigger")
17
+ others.push(`${object.type} ${object.name}: ${squash(object.sql)}`);
18
+ if (object.type !== "table")
19
+ continue;
20
+ const columns = await kernel.query(sql `SELECT name, type, "notnull", dflt_value, pk FROM pragma_table_info(${object.name}) ORDER BY cid`);
21
+ const indexes = await kernel.query(sql `SELECT name, "unique", origin, partial FROM pragma_index_list(${object.name}) ORDER BY name`);
22
+ const indexTexts = [];
23
+ for (const index of indexes) {
24
+ const cols = await kernel.query(sql `SELECT name FROM pragma_index_info(${index.name}) ORDER BY seqno`);
25
+ const definition = objects.find((o) => o.type === "index" && o.name === index.name)?.sql;
26
+ const where = index.partial ? ` WHERE ${squash(definition).replace(/^.*? WHERE /i, "")}` : "";
27
+ // Auto-named indexes (UNIQUE/PRIMARY KEY in the table text) are identified by what they cover.
28
+ const label = index.origin === "c" ? index.name : `(${index.origin})`;
29
+ indexTexts.push(`${label} ${index.unique ? "UNIQUE " : ""}(${cols.map((c) => c.name).join(", ")})${where}`);
30
+ }
31
+ const fks = await kernel.query(sql `SELECT id, "table", "from", "to", on_update, on_delete FROM pragma_foreign_key_list(${object.name}) ORDER BY id, seq`);
32
+ const byId = new Map();
33
+ for (const fk of fks)
34
+ byId.set(fk.id, [...(byId.get(fk.id) ?? []), fk]);
35
+ const constraints = [...byId.values()].map((parts) => {
36
+ // Every group has at least one part: it was created by pushing one.
37
+ const first = parts[0];
38
+ return `FOREIGN KEY (${parts.map((p) => p.from).join(", ")}) REFERENCES ${first.table} (${parts.map((p) => p.to ?? "").join(", ")}) ON DELETE ${first.on_delete} ON UPDATE ${first.on_update}`;
39
+ });
40
+ constraints.push(`DEFINITION ${squash(object.sql)}`);
41
+ tables[object.name] = {
42
+ columns: columns.map((c) => `${c.name} ${c.type.toLowerCase()}${c.notnull ? " NOT NULL" : ""}${c.dflt_value === null ? "" : ` DEFAULT ${c.dflt_value}`}${c.pk ? ` PK${c.pk}` : ""}`),
43
+ indexes: indexTexts.sort(),
44
+ constraints: constraints.sort(),
45
+ };
46
+ }
47
+ return { tables, others: others.sort() };
48
+ }
49
+ async function postgresShape(kernel) {
50
+ const columns = await kernel.query(sql `SELECT c.table_name, c.column_name, c.data_type, c.is_nullable, c.column_default
51
+ FROM information_schema.columns c
52
+ JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name
53
+ WHERE c.table_schema = current_schema() AND t.table_type = 'BASE TABLE'
54
+ ORDER BY c.table_name, c.ordinal_position`);
55
+ const indexes = await kernel.query(sql `SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = current_schema() ORDER BY tablename, indexname`);
56
+ const constraints = await kernel.query(sql `SELECT cl.relname AS table_name, co.conname, pg_get_constraintdef(co.oid) AS definition
57
+ FROM pg_constraint co JOIN pg_class cl ON cl.oid = co.conrelid
58
+ JOIN pg_namespace ns ON ns.oid = cl.relnamespace
59
+ WHERE ns.nspname = current_schema() ORDER BY cl.relname, co.conname`);
60
+ const tables = {};
61
+ const table = (name) => (tables[name] ??= { columns: [], indexes: [], constraints: [] });
62
+ for (const c of columns) {
63
+ table(c.table_name).columns.push(`${c.column_name} ${c.data_type.toLowerCase()}${c.is_nullable === "NO" ? " NOT NULL" : ""}${c.column_default === null ? "" : ` DEFAULT ${c.column_default}`}`);
64
+ }
65
+ for (const i of indexes)
66
+ table(i.tablename).indexes.push(`${i.indexname} ${squash(i.indexdef).replace(/ ON \S+\./, " ON ")}`);
67
+ for (const c of constraints)
68
+ table(c.table_name).constraints.push(`${c.conname} ${squash(c.definition)}`);
69
+ for (const shape of Object.values(tables)) {
70
+ shape.indexes.sort();
71
+ shape.constraints.sort();
72
+ }
73
+ const views = await kernel.query(sql `SELECT viewname AS name, definition FROM pg_views WHERE schemaname = current_schema() ORDER BY viewname`);
74
+ return { tables, others: views.map((v) => `view ${v.name}: ${squash(v.definition)}`) };
75
+ }
76
+ /** The main database file of a SQLite kernel; null for an in-memory database or a Postgres kernel. */
77
+ export async function databaseFile(kernel) {
78
+ if (kernel.dialect !== "sqlite")
79
+ return null;
80
+ const rows = await kernel.query(sql `SELECT file FROM pragma_database_list WHERE name = 'main'`);
81
+ return rows[0]?.file ? rows[0].file : null;
82
+ }
83
+ //# sourceMappingURL=schema-shape.js.map
@@ -0,0 +1,8 @@
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
@@ -0,0 +1,8 @@
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
@@ -0,0 +1,71 @@
1
+ import { type StorageKernel } from "../index.js";
2
+ import type { SqliteClient, SqliteOpener } from "../../sqlite/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
@@ -0,0 +1,132 @@
1
+ import path from "node:path";
2
+ import { Kysely, SqliteDialect } from "kysely";
3
+ import { buildKernel, TurnLock } from "../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
@@ -0,0 +1,4 @@
1
+ /** Kysely's SQLite binding and kernel storage operations. */
2
+ export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf, type SqliteConnectionSource, type SqliteKernel } from "./driver.js";
3
+ export { sqliteOps } from "./ops.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ /** Kysely's SQLite binding and kernel storage operations. */
2
+ export { sqliteKernel, openSqliteFileKernel, openMemorySqliteKernel, closeSqliteConnection, sqliteClientOf, sqliteConnectionOf } from "./driver.js";
3
+ export { sqliteOps } from "./ops.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import { type StorageKernel, type StorageOps } from "../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