@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,40 @@
1
+ import { outsideTransactionOf, StorageOpError } from "../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
@@ -0,0 +1,82 @@
1
+ import type { StorageKernel } from "./port.js";
2
+ /**
3
+ * @file A Postgres-to-Postgres copy of a site's whole store (R1g, the host storage move command): every table
4
+ * in the host-supplied schemas (content and AI chat), row for row, from a PGlite
5
+ * source into a Postgres target that the migration runner has already brought to head.
6
+ *
7
+ * Same dialect on both sides, so nothing is translated: rows travel as each column's text form and
8
+ * the target's own input functions read them back (jsonb, tsvector, bytea, arrays alike). Unlike the
9
+ * SQLite transfer (`copy-engine.ts`) nothing is excluded: a move is the switch, so logins and sealed
10
+ * credentials go too (still sealed with the same site key).
11
+ *
12
+ * - Tables the migrations do not create (a plugin's `p_<id>__*` tables, `_plugin_*` bookkeeping) are
13
+ * created on the target from the source's own catalog: columns, identity, constraints, indexes.
14
+ * - Everything happens in ONE target transaction: the target's tables are locked and must still be
15
+ * empty (no migration seeds rows), foreign keys are dropped, rows copied, foreign keys put back
16
+ * (validated), identity counters moved past the copied ids, and each table verified (row count + a
17
+ * checksum of its primary keys). Any failure rolls the target back to its migrated, empty state.
18
+ * - The migration ledgers are not copied: both sides are at head, and the ledgers must agree.
19
+ *
20
+ * The source must not change during the copy (the caller holds its PGlite owner lock). Source reads
21
+ * are short statements, in batches of {@link BATCH_ROWS}, walked by `ctid`.
22
+ * See docs/decisions/DR-003-host-owned-schema-copy.md.
23
+ */
24
+ export interface StoreCopyScope {
25
+ readonly schemas: readonly string[];
26
+ readonly ledgers: readonly {
27
+ schema: string;
28
+ name: string;
29
+ }[];
30
+ }
31
+ /** The migration ledgers: compared, never copied. */
32
+ /** Rows per source read / target insert (fewer for a wide table, to stay under the bind limit). */
33
+ export declare const BATCH_ROWS = 500;
34
+ interface CatalogColumn {
35
+ name: string;
36
+ type: string;
37
+ notNull: boolean;
38
+ /** A default expression, or the generation expression of a generated column. */
39
+ expression: string | null;
40
+ identity: "" | "a" | "d";
41
+ generated: boolean;
42
+ }
43
+ export interface CatalogTable {
44
+ schema: string;
45
+ name: string;
46
+ columns: CatalogColumn[];
47
+ primaryKey: string[];
48
+ }
49
+ export interface CopiedTable {
50
+ /** `schema.table` */
51
+ table: string;
52
+ rows: number;
53
+ /** True for a table the migrations do not create, made on the target from the source's catalog. */
54
+ created: boolean;
55
+ }
56
+ /** The copy found something it must not hand back. The target transaction is rolled back. */
57
+ export declare class StoreCopyError extends Error {
58
+ constructor(message: string);
59
+ }
60
+ /** Public copy API: required host scope and borrowed kernels; no new kernel is opened. */
61
+ export declare function readCatalog({ kernel, scope }: {
62
+ kernel: StorageKernel<unknown>;
63
+ scope: StoreCopyScope;
64
+ }, _optional?: {}): Promise<CatalogTable[]>;
65
+ export declare function nonEmptyTables({ kernel, scope }: {
66
+ kernel: StorageKernel<unknown>;
67
+ scope: StoreCopyScope;
68
+ }, _optional?: {}): Promise<string[]>;
69
+ export declare function assertLedgersAgree({ source, target, scope }: {
70
+ source: StorageKernel<unknown>;
71
+ target: StorageKernel<unknown>;
72
+ scope: StoreCopyScope;
73
+ }, _optional?: {}): Promise<void>;
74
+ export declare function copyPgStore({ source, target, scope }: {
75
+ source: StorageKernel<unknown>;
76
+ target: StorageKernel<unknown>;
77
+ scope: StoreCopyScope;
78
+ }, optional?: {
79
+ onCopied?: () => Promise<void>;
80
+ }): Promise<CopiedTable[]>;
81
+ export {};
82
+ //# sourceMappingURL=store-copy.d.ts.map
@@ -0,0 +1,240 @@
1
+ import { sql } from "kysely";
2
+ /** The migration ledgers: compared, never copied. */
3
+ /** Rows per source read / target insert (fewer for a wide table, to stay under the bind limit). */
4
+ export const BATCH_ROWS = 500;
5
+ const MAX_BIND_PARAMETERS = 60_000;
6
+ /** The copy found something it must not hand back. The target transaction is rolled back. */
7
+ export class StoreCopyError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "StoreCopyError";
11
+ }
12
+ }
13
+ const qualified = (table) => `${table.schema}.${table.name}`;
14
+ const tableRef = (table) => sql.table(qualified(table));
15
+ /** `"schema"."table"` as text, for functions that take a relation name (`pg_get_serial_sequence`). */
16
+ const quotedName = (table) => [table.schema, table.name].map((part) => `"${part.replace(/"/g, '""')}"`).join(".");
17
+ const isLedger = (table, scope) => scope.ledgers.some((l) => l.schema === table.schema && l.name === table.name);
18
+ /** Every base table in the moved schemas, with columns and primary key, in a stable order. */
19
+ async function readCatalogInternal(kernel, scope) {
20
+ const schemas = sql.join(scope.schemas.map((s) => sql.lit(s)));
21
+ const columns = await kernel.query(sql `
22
+ SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, format_type(a.atttypid, a.atttypmod) AS type,
23
+ a.attnotnull AS not_null, pg_get_expr(d.adbin, d.adrelid) AS expression, a.attidentity::text AS identity,
24
+ a.attgenerated::text AS generated
25
+ FROM pg_class c
26
+ JOIN pg_namespace n ON n.oid = c.relnamespace
27
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
28
+ LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
29
+ WHERE c.relkind IN ('r', 'p') AND n.nspname IN (${schemas})
30
+ ORDER BY n.nspname, c.relname, a.attnum`);
31
+ const keys = await kernel.query(sql `
32
+ SELECT n.nspname AS schema, c.relname AS table, a.attname AS column
33
+ FROM pg_constraint con
34
+ JOIN pg_class c ON c.oid = con.conrelid
35
+ JOIN pg_namespace n ON n.oid = c.relnamespace
36
+ JOIN LATERAL unnest(con.conkey) WITH ORDINALITY AS k(attnum, position) ON true
37
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.attnum
38
+ WHERE con.contype = 'p' AND n.nspname IN (${schemas})
39
+ ORDER BY n.nspname, c.relname, k.position`);
40
+ const tables = new Map();
41
+ for (const row of columns) {
42
+ const id = `${row.schema}.${row.table}`;
43
+ let table = tables.get(id);
44
+ if (table === undefined) {
45
+ table = { schema: row.schema, name: row.table, columns: [], primaryKey: [] };
46
+ tables.set(id, table);
47
+ }
48
+ table.columns.push({
49
+ name: row.column,
50
+ type: row.type,
51
+ notNull: row.not_null,
52
+ expression: row.expression,
53
+ identity: row.identity,
54
+ generated: row.generated !== "",
55
+ });
56
+ }
57
+ for (const row of keys)
58
+ tables.get(`${row.schema}.${row.table}`)?.primaryKey.push(row.column);
59
+ return [...tables.values()];
60
+ }
61
+ async function readConstraints(kernel, scope) {
62
+ return kernel.query(sql `
63
+ SELECT n.nspname AS schema, c.relname AS table, con.conname AS name, con.contype::text AS type,
64
+ pg_get_constraintdef(con.oid) AS definition
65
+ FROM pg_constraint con
66
+ JOIN pg_class c ON c.oid = con.conrelid
67
+ JOIN pg_namespace n ON n.oid = c.relnamespace
68
+ WHERE n.nspname IN (${sql.join(scope.schemas.map((s) => sql.lit(s)))}) AND con.contype IN ('p', 'u', 'c', 'f', 'x')
69
+ ORDER BY n.nspname, c.relname, con.conname`);
70
+ }
71
+ /** Indexes that are not a constraint's own (those come back with the constraint). */
72
+ async function readIndexes(kernel, scope) {
73
+ return kernel.query(sql `
74
+ SELECT n.nspname AS schema, t.relname AS table, pg_get_indexdef(i.indexrelid) AS definition
75
+ FROM pg_index i
76
+ JOIN pg_class t ON t.oid = i.indrelid
77
+ JOIN pg_namespace n ON n.oid = t.relnamespace
78
+ WHERE n.nspname IN (${sql.join(scope.schemas.map((s) => sql.lit(s)))})
79
+ AND NOT EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = i.indexrelid AND con.conrelid = i.indrelid AND con.contype IN ('p', 'u', 'x'))
80
+ ORDER BY n.nspname, t.relname, 1`);
81
+ }
82
+ /**
83
+ * The target's tables that hold rows (ledgers aside). A move goes into an empty database only.
84
+ * @returns `schema.table` names, empty when the target may be used.
85
+ */
86
+ async function nonEmptyTablesInternal(kernel, scope) {
87
+ const found = [];
88
+ for (const table of await readCatalogInternal(kernel, scope)) {
89
+ if (isLedger(table, scope))
90
+ continue;
91
+ const [row] = await kernel.query(sql `SELECT EXISTS (SELECT 1 FROM ${tableRef(table)}) AS any`);
92
+ if (row?.any)
93
+ found.push(qualified(table));
94
+ }
95
+ return found;
96
+ }
97
+ /** Throws unless both ledgers hold the same steps with the same checksums on both sides. */
98
+ async function assertLedgersAgreeInternal(source, target, scope) {
99
+ for (const ledger of scope.ledgers) {
100
+ const read = async (kernel) => (await kernel.query(sql `SELECT id, checksum FROM ${tableRef(ledger)} ORDER BY id`))
101
+ .map((r) => `${r.id}:${r.checksum}`)
102
+ .join(",");
103
+ const [a, b] = [await read(source), await read(target)];
104
+ if (a !== b)
105
+ throw new StoreCopyError(`the migration ledger ${qualified(ledger)} differs between the source (${a}) and the target (${b})`);
106
+ }
107
+ }
108
+ function columnDdl(column) {
109
+ let ddl = sql `${sql.ref(column.name)} ${sql.raw(column.type)}`;
110
+ if (column.generated)
111
+ return sql `${ddl} GENERATED ALWAYS AS (${sql.raw(column.expression ?? "NULL")}) STORED`;
112
+ if (column.identity !== "")
113
+ ddl = sql `${ddl} GENERATED ${sql.raw(column.identity === "a" ? "ALWAYS" : "BY DEFAULT")} AS IDENTITY`;
114
+ if (column.notNull)
115
+ ddl = sql `${ddl} NOT NULL`;
116
+ if (column.expression !== null && column.identity === "") {
117
+ if (/\bnextval\s*\(/i.test(column.expression)) {
118
+ throw new StoreCopyError(`column ${column.name} takes its default from a sequence (${column.expression}); this move cannot recreate it`);
119
+ }
120
+ ddl = sql `${ddl} DEFAULT ${sql.raw(column.expression)}`;
121
+ }
122
+ return ddl;
123
+ }
124
+ /** The columns a row is copied through (a generated column is recomputed by the target). */
125
+ const copiedColumns = (table) => table.columns.filter((c) => !c.generated);
126
+ /**
127
+ * Copies the table's non-generated columns through their Postgres text representation.
128
+ * Reads source rows and inserts into the caller's target transaction; driver/SQL errors propagate.
129
+ * @returns Number of inserted rows.
130
+ * @complexity O(rows × columns) work and O(batch rows × columns) memory.
131
+ */
132
+ async function copyRows(source, target, table) {
133
+ const columns = copiedColumns(table);
134
+ if (columns.length === 0)
135
+ return 0;
136
+ const batch = Math.max(1, Math.min(BATCH_ROWS, Math.floor(MAX_BIND_PARAMETERS / columns.length)));
137
+ const select = sql.join(columns.map((c) => sql `${sql.ref(c.name)}::text AS ${sql.ref(c.name)}`));
138
+ const into = sql.join(columns.map((c) => sql.ref(c.name)));
139
+ let after = "(0,0)";
140
+ let copied = 0;
141
+ for (;;) {
142
+ const rows = await source.query(sql `SELECT ctid::text AS "__ctid", ${select} FROM ${tableRef(table)} WHERE ctid > ${after}::tid ORDER BY ctid LIMIT ${batch}`);
143
+ if (rows.length === 0)
144
+ return copied;
145
+ // Bind text before the catalog type cast: PGlite's bytea serializer accepts bytes, not text.
146
+ // The server's input functions decode the unchanged text, including nulls, JSON and arrays.
147
+ const values = sql.join(rows.map((row) => sql `(${sql.join(columns.map((c) => sql `${row[c.name]}::text::${sql.raw(c.type)}`))})`));
148
+ await target.execute(sql `INSERT INTO ${tableRef(table)} (${into}) OVERRIDING SYSTEM VALUE VALUES ${values}`);
149
+ copied += rows.length;
150
+ after = rows[rows.length - 1].__ctid;
151
+ }
152
+ }
153
+ /** Row count and an order-independent checksum of the primary keys (count only without one). */
154
+ async function fingerprint(kernel, table) {
155
+ const key = table.primaryKey.length === 0 ? sql `''` : sql `concat_ws(E'\\t', ${sql.join(table.primaryKey.map((c) => sql `${sql.ref(c)}::text`))})`;
156
+ const [row] = await kernel.query(sql `SELECT count(*)::int AS n, md5(coalesce(string_agg(k, E'\\n' ORDER BY k COLLATE "C"), '')) AS sum
157
+ FROM (SELECT ${key} AS k FROM ${tableRef(table)}) keyed`);
158
+ return `${row.n}:${row.sum}`;
159
+ }
160
+ /**
161
+ * Copies every table of `source` into `target` (see this file's header). Call it with both at head
162
+ * and the target empty ({@link nonEmptyTables}); the ledgers are checked here first.
163
+ *
164
+ * @param optional.onCopied runs inside the target transaction after everything is verified; a throw
165
+ * rolls the copy back (tests inject a failure here).
166
+ * @throws {StoreCopyError} ledgers disagree, a table's columns differ between the sides, the target
167
+ * holds rows once locked, a table cannot be recreated, or a table's rows do not verify.
168
+ * @complexity O(total rows) reads and writes, in batches of {@link BATCH_ROWS}.
169
+ */
170
+ async function copyPgStoreInternal(source, target, scope, optional = {}) {
171
+ await assertLedgersAgreeInternal(source, target, scope);
172
+ const sourceTables = (await readCatalogInternal(source, scope)).filter((t) => !isLedger(t, scope));
173
+ const targetTables = new Map((await readCatalogInternal(target, scope)).map((t) => [qualified(t), t]));
174
+ for (const table of sourceTables) {
175
+ const other = targetTables.get(qualified(table));
176
+ if (other === undefined)
177
+ continue;
178
+ const shape = (t) => t.columns.map((c) => `${c.name} ${c.type}`).join(", ");
179
+ if (shape(table) !== shape(other)) {
180
+ throw new StoreCopyError(`table ${qualified(table)} differs: source (${shape(table)}), target (${shape(other)})`);
181
+ }
182
+ }
183
+ const created = sourceTables.filter((t) => !targetTables.has(qualified(t)));
184
+ const createdIds = new Set(created.map(qualified));
185
+ const sourceConstraints = await readConstraints(source, scope);
186
+ const sourceIndexes = await readIndexes(source, scope);
187
+ return target.transaction(async () => {
188
+ // Foreign keys off for the copy (any order, self-references, cycles), back on and validated after.
189
+ const foreignKeys = (await readConstraints(target, scope)).filter((c) => c.type === "f");
190
+ for (const fk of foreignKeys) {
191
+ await target.execute(sql `ALTER TABLE ${tableRef({ schema: fk.schema, name: fk.table })} DROP CONSTRAINT ${sql.ref(fk.name)}`);
192
+ }
193
+ // Emptiness again, under locks this transaction holds to the end: a row another process wrote
194
+ // after the caller's check would otherwise be lost or mixed in.
195
+ const existing = [...targetTables.values()].filter((t) => !isLedger(t, scope));
196
+ if (existing.length > 0)
197
+ await target.execute(sql `LOCK TABLE ${sql.join(existing.map(tableRef))} IN ACCESS EXCLUSIVE MODE`);
198
+ const occupied = await nonEmptyTablesInternal(target, scope);
199
+ if (occupied.length > 0)
200
+ throw new StoreCopyError(`the target database already holds data (${occupied.join(", ")}); nothing was copied`);
201
+ for (const table of created) {
202
+ await target.execute(sql `CREATE TABLE ${tableRef(table)} (${sql.join(table.columns.map(columnDdl))})`);
203
+ }
204
+ const createdConstraints = sourceConstraints.filter((c) => createdIds.has(`${c.schema}.${c.table}`));
205
+ for (const constraint of createdConstraints.filter((c) => c.type !== "f")) {
206
+ await target.execute(sql `ALTER TABLE ${tableRef({ schema: constraint.schema, name: constraint.table })} ADD CONSTRAINT ${sql.ref(constraint.name)} ${sql.raw(constraint.definition)}`);
207
+ }
208
+ for (const index of sourceIndexes.filter((i) => createdIds.has(`${i.schema}.${i.table}`))) {
209
+ await target.execute(sql.raw(index.definition));
210
+ }
211
+ const report = [];
212
+ for (const table of sourceTables) {
213
+ const rows = await copyRows(source, target, table);
214
+ report.push({ table: qualified(table), rows, created: createdIds.has(qualified(table)) });
215
+ }
216
+ for (const fk of [...foreignKeys, ...createdConstraints.filter((c) => c.type === "f")]) {
217
+ await target.execute(sql `ALTER TABLE ${tableRef({ schema: fk.schema, name: fk.table })} ADD CONSTRAINT ${sql.ref(fk.name)} ${sql.raw(fk.definition)}`);
218
+ }
219
+ // Identity counters past the copied ids, or the first insert after the move collides.
220
+ for (const table of sourceTables) {
221
+ for (const column of table.columns.filter((c) => c.identity !== "")) {
222
+ await target.execute(sql `SELECT setval(pg_get_serial_sequence(${quotedName(table)}, ${column.name}),
223
+ COALESCE((SELECT max(${sql.ref(column.name)}) FROM ${tableRef(table)}), 0) + 1, false)`);
224
+ }
225
+ }
226
+ for (const table of sourceTables) {
227
+ const [a, b] = [await fingerprint(source, table), await fingerprint(target, table)];
228
+ if (a !== b)
229
+ throw new StoreCopyError(`table ${qualified(table)} did not verify after the copy: source ${a}, target ${b}`);
230
+ }
231
+ await optional.onCopied?.();
232
+ return report;
233
+ });
234
+ }
235
+ /** Public copy API: required host scope and borrowed kernels; no new kernel is opened. */
236
+ export function readCatalog({ kernel, scope }, _optional = {}) { return readCatalogInternal(kernel, scope); }
237
+ export function nonEmptyTables({ kernel, scope }, _optional = {}) { return nonEmptyTablesInternal(kernel, scope); }
238
+ export function assertLedgersAgree({ source, target, scope }, _optional = {}) { return assertLedgersAgreeInternal(source, target, scope); }
239
+ export function copyPgStore({ source, target, scope }, optional = {}) { return copyPgStoreInternal(source, target, scope, optional); }
240
+ //# sourceMappingURL=store-copy.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @file Many `run()` bodies OR one transaction at a time, first come first served.
3
+ *
4
+ * Needed where every caller shares ONE connection (better-sqlite3, PGlite): a transaction is just
5
+ * `BEGIN` on that connection, so a `run()` body from an unrelated request that executes while it is
6
+ * open would land inside it — and roll back with it (the SQLite lock-in audit, §3.6, "latent
7
+ * hazard"). A transaction therefore waits until in-flight `run()` bodies finish, and `run()` bodies
8
+ * that arrive while a transaction is open or queued wait for it. FIFO, so neither side starves.
9
+ */
10
+ type Kind = "shared" | "exclusive";
11
+ export declare class TurnLock {
12
+ private shared;
13
+ private exclusive;
14
+ private readonly waiting;
15
+ acquire(kind: Kind): Promise<void>;
16
+ release(kind: Kind): void;
17
+ private fits;
18
+ private take;
19
+ }
20
+ export {};
21
+ //# sourceMappingURL=turn-lock.d.ts.map
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @file Many `run()` bodies OR one transaction at a time, first come first served.
3
+ *
4
+ * Needed where every caller shares ONE connection (better-sqlite3, PGlite): a transaction is just
5
+ * `BEGIN` on that connection, so a `run()` body from an unrelated request that executes while it is
6
+ * open would land inside it — and roll back with it (the SQLite lock-in audit, §3.6, "latent
7
+ * hazard"). A transaction therefore waits until in-flight `run()` bodies finish, and `run()` bodies
8
+ * that arrive while a transaction is open or queued wait for it. FIFO, so neither side starves.
9
+ */
10
+ export class TurnLock {
11
+ shared = 0;
12
+ exclusive = false;
13
+ waiting = [];
14
+ acquire(kind) {
15
+ if (this.waiting.length === 0 && this.fits(kind)) {
16
+ this.take(kind);
17
+ return Promise.resolve();
18
+ }
19
+ return new Promise((grant) => this.waiting.push({ kind, grant }));
20
+ }
21
+ release(kind) {
22
+ if (kind === "exclusive")
23
+ this.exclusive = false;
24
+ else
25
+ this.shared -= 1;
26
+ while (this.waiting.length > 0 && this.fits(this.waiting[0].kind)) {
27
+ const next = this.waiting.shift();
28
+ this.take(next.kind);
29
+ next.grant();
30
+ }
31
+ }
32
+ fits(kind) {
33
+ return kind === "exclusive" ? !this.exclusive && this.shared === 0 : !this.exclusive;
34
+ }
35
+ take(kind) {
36
+ if (kind === "exclusive")
37
+ this.exclusive = true;
38
+ else
39
+ this.shared += 1;
40
+ }
41
+ }
42
+ //# sourceMappingURL=turn-lock.js.map
@@ -0,0 +1,13 @@
1
+ import type { StorageKernel } from "./port.js";
2
+ /**
3
+ * The `.ts` source of a Kysely database interface for every table in the kernel's current schema.
4
+ *
5
+ * @param required.interfaceName e.g. `ContentDatabase`.
6
+ * @param required.source one line naming where the reference database came from (printed in the header).
7
+ */
8
+ export declare function renderDatabaseTypes(kernel: StorageKernel<unknown>, required: {
9
+ interfaceName: string;
10
+ source: string;
11
+ regenerate: string;
12
+ }): Promise<string>;
13
+ //# sourceMappingURL=typegen.d.ts.map
@@ -0,0 +1,76 @@
1
+ import { sql } from "kysely";
2
+ const SCALAR = {
3
+ text: "string",
4
+ "character varying": "string",
5
+ character: "string",
6
+ integer: "number",
7
+ smallint: "number",
8
+ bigint: "number",
9
+ real: "number",
10
+ "double precision": "number",
11
+ numeric: "number",
12
+ json: "string",
13
+ jsonb: "string",
14
+ bytea: "Uint8Array",
15
+ };
16
+ function pascal(name) {
17
+ return name
18
+ .split("_")
19
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
20
+ .join("");
21
+ }
22
+ function columnType(column) {
23
+ const nullable = column.is_nullable === "YES";
24
+ const generated = column.column_default !== null || column.is_identity === "YES";
25
+ if (column.data_type === "boolean")
26
+ return nullable ? "NullableBool" : generated ? "GeneratedBool" : "Bool";
27
+ const scalar = SCALAR[column.data_type];
28
+ if (scalar === undefined) {
29
+ throw new Error(`typegen: no TypeScript type for ${column.table_name}.${column.column_name} (${column.data_type})`);
30
+ }
31
+ if (nullable)
32
+ return `${scalar} | null`;
33
+ return generated ? `Generated<${scalar}>` : scalar;
34
+ }
35
+ /**
36
+ * The `.ts` source of a Kysely database interface for every table in the kernel's current schema.
37
+ *
38
+ * @param required.interfaceName e.g. `ContentDatabase`.
39
+ * @param required.source one line naming where the reference database came from (printed in the header).
40
+ */
41
+ export async function renderDatabaseTypes(kernel, required) {
42
+ if (kernel.dialect !== "postgres")
43
+ throw new Error("typegen reads a Postgres reference database");
44
+ const rows = await kernel.query(sql `SELECT table_name, column_name, data_type, is_nullable, column_default, is_identity
45
+ FROM information_schema.columns
46
+ WHERE table_schema = current_schema()
47
+ ORDER BY table_name, ordinal_position`);
48
+ const tables = new Map();
49
+ for (const row of rows)
50
+ tables.set(row.table_name, [...(tables.get(row.table_name) ?? []), row]);
51
+ const names = [...tables.keys()].sort();
52
+ const out = [
53
+ "/**",
54
+ ` * @file GENERATED — do not edit. Kysely types for ${required.interfaceName}, read from ${required.source}`,
55
+ ` * by \`platform/db/kernel/typegen.ts\`. Regenerate: ${required.regenerate}`,
56
+ " */",
57
+ 'import type { ColumnType, Generated, SqlBool } from "kysely";',
58
+ "",
59
+ "/** A boolean column: reads `true`/`false` (Postgres) or `1`/`0` (SQLite); convert with `toBool`. */",
60
+ "export type Bool = ColumnType<SqlBool, boolean, boolean>;",
61
+ "export type GeneratedBool = ColumnType<SqlBool, boolean | undefined, boolean>;",
62
+ "export type NullableBool = ColumnType<SqlBool | null, boolean | null | undefined, boolean | null>;",
63
+ "",
64
+ `export interface ${required.interfaceName} {`,
65
+ ...names.map((name) => ` ${name}: ${pascal(name)}Table;`),
66
+ "}",
67
+ ];
68
+ for (const name of names) {
69
+ out.push("", `export interface ${pascal(name)}Table {`);
70
+ for (const column of tables.get(name))
71
+ out.push(` ${column.column_name}: ${columnType(column)};`);
72
+ out.push("}");
73
+ }
74
+ return `${out.join("\n")}\n`;
75
+ }
76
+ //# sourceMappingURL=typegen.js.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The checksum a `MigrationStep` pins: sha256 hex of the text that defines the step, exactly
3
+ * as given. A consumer's pin test re-derives each step's checksum with this and compares it to the
4
+ * pinned value, so an edited shipped step fails the test before it reaches a database whose ledger
5
+ * recorded the old one. Normalising the text first (stripping comments, collapsing whitespace) is
6
+ * the consumer's choice and must stay the same for the life of its history.
7
+ *
8
+ * @complexity O(length of `text`).
9
+ */
10
+ export declare function sourceChecksum(text: string): string;
11
+ //# sourceMappingURL=checksum.d.ts.map
@@ -0,0 +1,14 @@
1
+ import { createHash } from "node:crypto";
2
+ /**
3
+ * The checksum a `MigrationStep` pins: sha256 hex of the text that defines the step, exactly
4
+ * as given. A consumer's pin test re-derives each step's checksum with this and compares it to the
5
+ * pinned value, so an edited shipped step fails the test before it reaches a database whose ledger
6
+ * recorded the old one. Normalising the text first (stripping comments, collapsing whitespace) is
7
+ * the consumer's choice and must stay the same for the life of its history.
8
+ *
9
+ * @complexity O(length of `text`).
10
+ */
11
+ export function sourceChecksum(text) {
12
+ return createHash("sha256").update(text, "utf8").digest("hex");
13
+ }
14
+ //# sourceMappingURL=checksum.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
3
+ * their pinned checksums and the ledger table's name (required, no default).
4
+ */
5
+ export { assertValidSteps, hasLedger, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
6
+ export { MIGRATION_ID, MigrationChecksumError, type MigrationContext, type MigrationStep, UnknownAppliedMigrationError, } from "./step.js";
7
+ export { sourceChecksum } from "./checksum.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
3
+ * their pinned checksums and the ledger table's name (required, no default).
4
+ */
5
+ export { assertValidSteps, hasLedger, runMigrations } from "./runner.js";
6
+ export { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
7
+ export { sourceChecksum } from "./checksum.js";
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,33 @@
1
+ import { type StorageKernel } from "../kernel/index.js";
2
+ import { type MigrationStep } from "./step.js";
3
+ export interface MigrationOptions {
4
+ /** The ledger table (REQUIRED, no default); also the migration lock's key. */
5
+ ledgerTable: string;
6
+ /** Where to copy an existing database before the first pending step changes it (see the file header). */
7
+ backupPath?: string;
8
+ /** Postgres only: the schema holding the ledger, created with it when missing. */
9
+ schema?: string;
10
+ /** Names the newer runtime in {@link UnknownAppliedMigrationError}'s message (default "version"). */
11
+ appName?: string;
12
+ }
13
+ export interface MigrationReport {
14
+ /** Steps this call applied, in order. */
15
+ applied: string[];
16
+ /** Steps already recorded (by an earlier run or a concurrent process). */
17
+ alreadyApplied: string[];
18
+ notes: string[];
19
+ }
20
+ /** Throws on duplicate, unordered or malformed ids and on a checksum that is not sha256 hex. */
21
+ export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
22
+ /**
23
+ * Applies every pending step of `steps`, in order, to `kernel`'s database.
24
+ *
25
+ * @param options.ledgerTable the ledger table (required).
26
+ * @param options.backupPath where an existing database is copied before the first pending step.
27
+ * @throws UnknownAppliedMigrationError / MigrationChecksumError before applying anything; whatever a
28
+ * step throws (its transaction is rolled back, later steps are not attempted).
29
+ */
30
+ export declare function runMigrations(kernel: StorageKernel<unknown>, steps: readonly MigrationStep[], options: MigrationOptions): Promise<MigrationReport>;
31
+ /** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
32
+ export declare function hasLedger(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<boolean>;
33
+ //# sourceMappingURL=runner.d.ts.map