@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,95 @@
1
+ import { spawn } from "node:child_process";
2
+ export class InvalidConnectionStringError extends Error {
3
+ }
4
+ /**
5
+ * Splits a `postgres://` / `postgresql://` URL into libpq environment variables.
6
+ *
7
+ * @throws {InvalidConnectionStringError} With a message that never quotes the string itself.
8
+ */
9
+ export function parseConnectionString({ raw }, { applicationName = "database-transfer" } = {}) {
10
+ let url;
11
+ try {
12
+ url = new URL(raw.trim());
13
+ }
14
+ catch {
15
+ throw new InvalidConnectionStringError("the connection string is not a valid postgres:// URL");
16
+ }
17
+ if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
18
+ throw new InvalidConnectionStringError("the connection string must start with postgres:// or postgresql://");
19
+ }
20
+ const host = url.searchParams.get("host") ?? decodeURIComponent(url.hostname);
21
+ const database = decodeURIComponent(url.pathname.replace(/^\//, ""));
22
+ const user = decodeURIComponent(url.username);
23
+ if (host === "" || database === "" || user === "") {
24
+ throw new InvalidConnectionStringError("the connection string must name a host, a user and a database");
25
+ }
26
+ const port = url.port || "5432";
27
+ const env = { PGHOST: host, PGPORT: port, PGDATABASE: database, PGUSER: user, PGCONNECT_TIMEOUT: "5", PGAPPNAME: applicationName };
28
+ if (url.password !== "")
29
+ env.PGPASSWORD = decodeURIComponent(url.password);
30
+ const sslmode = url.searchParams.get("sslmode");
31
+ if (sslmode !== null)
32
+ env.PGSSLMODE = sslmode;
33
+ return { description: { host, port, database, user }, env };
34
+ }
35
+ /** The parent environment without any `PG*` variable. */
36
+ function environmentWithout(parent) {
37
+ const env = {};
38
+ for (const [key, value] of Object.entries(parent)) {
39
+ if (!key.startsWith("PG") && value !== undefined)
40
+ env[key] = value;
41
+ }
42
+ return env;
43
+ }
44
+ /** psql's own `ERROR:` line (or its first line) with quoted parts blanked; never a CONTEXT or
45
+ * DETAIL line, which quote row data. */
46
+ function failureFrom(stderr) {
47
+ const lines = stderr.split("\n").map((line) => line.trim()).filter((line) => line !== "");
48
+ const line = lines.find((candidate) => /\bERROR:|FATAL:|could not|timeout/i.test(candidate)) ?? lines[0] ?? "psql failed without a message";
49
+ const error = line.replace(/^psql:[^ ]*: /, "").replace(/"[^"]*"/g, '"…"');
50
+ const copyTable = /\bCOPY ([A-Za-z0-9_."]+), line \d+/.exec(stderr)?.[1]?.replace(/"/g, "");
51
+ return copyTable === undefined ? { ok: false, error } : { ok: false, error, copyTable };
52
+ }
53
+ function runPsql(env, args, chunks) {
54
+ return new Promise((resolve) => {
55
+ const child = spawn("psql", ["-X", "-q", "-v", "ON_ERROR_STOP=1", ...args], { env, stdio: ["pipe", "pipe", "pipe"] });
56
+ let stdout = "";
57
+ let stderr = "";
58
+ child.stdout.setEncoding("utf8").on("data", (data) => (stdout += data));
59
+ child.stderr.setEncoding("utf8").on("data", (data) => (stderr += data));
60
+ child.on("error", (err) => resolve({ ok: false, error: `psql could not be started (${err.message})` }));
61
+ child.on("close", (code) => resolve(code === 0 ? { ok: true, value: stdout } : failureFrom(stderr)));
62
+ child.stdin.on("error", () => undefined);
63
+ void (async () => {
64
+ for (const chunk of chunks ?? []) {
65
+ if (!child.stdin.write(chunk))
66
+ await new Promise((drain) => child.stdin.once("drain", drain));
67
+ }
68
+ child.stdin.end();
69
+ })();
70
+ });
71
+ }
72
+ /**
73
+ * The P0 adapter: every call is one short-lived `psql` process.
74
+ *
75
+ * @throws {InvalidConnectionStringError} When the string cannot be parsed.
76
+ */
77
+ export function createPsqlPostgresTarget({ connectionString }, { parentEnv = process.env, applicationName } = {}) {
78
+ const parsed = parseConnectionString({ raw: connectionString }, applicationName === undefined ? {} : { applicationName });
79
+ const env = { ...environmentWithout(parentEnv), ...parsed.env };
80
+ return {
81
+ describe: () => parsed.description,
82
+ async query(sql) {
83
+ const result = await runPsql(env, ["-t", "-A", "-F", "\t", "-c", sql], null);
84
+ if (!result.ok)
85
+ return result;
86
+ const rows = result.value.split("\n").filter((line) => line !== "").map((line) => line.split("\t"));
87
+ return { ok: true, value: rows };
88
+ },
89
+ async runScript(chunks) {
90
+ const result = await runPsql(env, ["-f", "-"], chunks);
91
+ return result.ok ? { ok: true, value: null } : result;
92
+ },
93
+ };
94
+ }
95
+ //# sourceMappingURL=postgres-target.js.map
@@ -0,0 +1,78 @@
1
+ /** Structural snapshot client: the consumer chooses and owns its driver installation. */
2
+ export interface SnapshotStatement {
3
+ all(...args: unknown[]): unknown[];
4
+ get(...args: unknown[]): unknown;
5
+ raw(): SnapshotStatement;
6
+ safeIntegers(): SnapshotStatement;
7
+ iterate(): Iterable<unknown[]>;
8
+ }
9
+ export interface SnapshotClient {
10
+ prepare(sql: string): SnapshotStatement;
11
+ close(): void;
12
+ }
13
+ export type SnapshotOpener = (bytes: Buffer, options: {
14
+ readonly: true;
15
+ }) => SnapshotClient;
16
+ /**
17
+ * @file The SQLite side of a database transfer: a snapshot held as bytes (from
18
+ * `DbOpsPort.captureRestorePoint`, never the live file), opened in memory, read only. The copier sees
19
+ * only {@link TransferSource}, so a Postgres source for the later "switch back" is a second adapter,
20
+ * not a copier change.
21
+ */
22
+ /** One column as the source declares it (SQLite `PRAGMA table_info`). */
23
+ export interface SourceColumn {
24
+ readonly name: string;
25
+ /** The declared type, as written (`INTEGER`, `TEXT`, `` for none). */
26
+ readonly declaredType: string;
27
+ readonly notNull: boolean;
28
+ /** The default as SQL text, as written, or `null`. */
29
+ readonly defaultSql: string | null;
30
+ /** 1-based position in the primary key; 0 when not part of it. */
31
+ readonly primaryKeyPosition: number;
32
+ }
33
+ export interface SourceForeignKey {
34
+ readonly columns: readonly string[];
35
+ readonly foreignTable: string;
36
+ /** `null` entries mean "the parent's primary key" (SQLite lets a foreign key omit its columns). */
37
+ readonly foreignColumns: readonly (string | null)[];
38
+ readonly onDelete: string;
39
+ readonly onUpdate: string;
40
+ }
41
+ export interface SourceIndex {
42
+ readonly name: string;
43
+ readonly unique: boolean;
44
+ /** `c` CREATE INDEX, `u` a UNIQUE constraint, `pk` the primary key. */
45
+ readonly origin: string;
46
+ readonly partial: boolean;
47
+ /** `null` for an expression column. */
48
+ readonly columns: readonly (string | null)[];
49
+ }
50
+ /** A table's layout as the source declares it, for tables no host schema file describes (plugins). */
51
+ export interface SourceTableLayout {
52
+ /** A virtual table (FTS and the like): its rows are derived, never copied. */
53
+ readonly virtual: boolean;
54
+ readonly columns: readonly SourceColumn[];
55
+ readonly foreignKeys: readonly SourceForeignKey[];
56
+ readonly indexes: readonly SourceIndex[];
57
+ }
58
+ export interface TransferSource {
59
+ /** Every table in the source, virtual and internal ones included, by name. */
60
+ tableNames(): readonly string[];
61
+ /** The table's declared layout, or `null` when the source has no such table. */
62
+ layout(table: string): SourceTableLayout | null;
63
+ /** The table's column names, or `null` when the source has no such table. */
64
+ columns(table: string): readonly string[] | null;
65
+ /** `keep`, when given, is a predicate in the source's own SQL selecting the rows that count. */
66
+ countRows(table: string, keep?: string): number;
67
+ /** Every row (or every row matching `keep`), cells in `columns` order; integers as `bigint`, so no
68
+ * 64-bit value loses precision. */
69
+ rows(table: string, columns: readonly string[], keep?: string): Iterable<unknown[]>;
70
+ close(): void;
71
+ }
72
+ /** @complexity O(database size) to deserialize the snapshot. */
73
+ export declare function openSqliteSnapshotSource({ bytes }: {
74
+ bytes: Buffer;
75
+ }, { open }: {
76
+ open: SnapshotOpener;
77
+ }): TransferSource;
78
+ //# sourceMappingURL=sqlite-source.d.ts.map
@@ -0,0 +1,79 @@
1
+ function quoteIdent(name) {
2
+ return `"${name.replace(/"/g, '""')}"`;
3
+ }
4
+ /** `keep` comes only from trusted host exclusion policy, never from tool input. */
5
+ function where(keep) {
6
+ return keep === undefined ? "" : ` WHERE ${keep}`;
7
+ }
8
+ /**
9
+ * A site database runs in WAL mode, and its snapshot's header says so (bytes 18-19 = 2). SQLite
10
+ * cannot open WAL-mode bytes in memory ("unable to open database file"), so a copy of the bytes is
11
+ * marked rollback-journal (1) first. The pages themselves are complete: a backup never needs the WAL.
12
+ */
13
+ function inMemoryReadableBytes(bytes) {
14
+ if (bytes[18] !== 2 && bytes[19] !== 2)
15
+ return bytes;
16
+ const copy = Buffer.from(bytes);
17
+ copy[18] = 1;
18
+ copy[19] = 1;
19
+ return copy;
20
+ }
21
+ function foreignKeysOf(db, table) {
22
+ const rows = db.prepare(`PRAGMA foreign_key_list(${quoteIdent(table)})`).all();
23
+ const byId = new Map();
24
+ for (const row of rows)
25
+ byId.set(row.id, [...(byId.get(row.id) ?? []), row]);
26
+ return [...byId.values()].map((parts) => ({
27
+ columns: parts.map((part) => part.from),
28
+ foreignTable: parts[0].table,
29
+ foreignColumns: parts.map((part) => part.to),
30
+ onDelete: parts[0].on_delete,
31
+ onUpdate: parts[0].on_update,
32
+ }));
33
+ }
34
+ function indexesOf(db, table) {
35
+ const list = db.prepare(`PRAGMA index_list(${quoteIdent(table)})`).all();
36
+ return list.map((index) => ({
37
+ name: index.name,
38
+ unique: index.unique === 1,
39
+ origin: index.origin,
40
+ partial: index.partial === 1,
41
+ columns: db.prepare(`PRAGMA index_info(${quoteIdent(index.name)})`).all().map((column) => column.name),
42
+ }));
43
+ }
44
+ function layoutOf(db, table) {
45
+ const master = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
46
+ if (master === undefined)
47
+ return null;
48
+ const columns = db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all().map((column) => ({
49
+ name: column.name,
50
+ declaredType: column.type,
51
+ notNull: column.notnull === 1,
52
+ defaultSql: column.dflt_value,
53
+ primaryKeyPosition: column.pk,
54
+ }));
55
+ const virtual = /^\s*CREATE\s+VIRTUAL\s+TABLE/i.test(master.sql ?? "");
56
+ return { virtual, columns, foreignKeys: virtual ? [] : foreignKeysOf(db, table), indexes: virtual ? [] : indexesOf(db, table) };
57
+ }
58
+ /** @complexity O(database size) to deserialize the snapshot. */
59
+ export function openSqliteSnapshotSource({ bytes }, { open }) {
60
+ const db = open(inMemoryReadableBytes(bytes), { readonly: true });
61
+ return {
62
+ tableNames() {
63
+ return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all().map((row) => row.name);
64
+ },
65
+ layout: (table) => layoutOf(db, table),
66
+ columns(table) {
67
+ const info = db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all();
68
+ return info.length === 0 ? null : info.map((column) => column.name);
69
+ },
70
+ countRows(table, keep) {
71
+ return db.prepare(`SELECT count(*) AS n FROM ${quoteIdent(table)}${where(keep)}`).get().n;
72
+ },
73
+ rows(table, columns, keep) {
74
+ return db.prepare(`SELECT ${columns.map(quoteIdent).join(", ")} FROM ${quoteIdent(table)}${where(keep)}`).raw().safeIntegers().iterate();
75
+ },
76
+ close: () => db.close(),
77
+ };
78
+ }
79
+ //# sourceMappingURL=sqlite-source.js.map
@@ -0,0 +1,44 @@
1
+ import type { SourceTableLayout, TransferSource } from "./sqlite-source.js";
2
+ import type { TransferTable } from "./types.js";
3
+ /** A table no host schema file describes, in the layout the snapshot declares. */
4
+ export declare function introspectedTable({ name, layout }: {
5
+ name: string;
6
+ layout: SourceTableLayout;
7
+ }, _optional?: {}): TransferTable;
8
+ export declare const LEFT_OUT_REASON: {
9
+ readonly bookkeeping: "the database's own bookkeeping is not copied";
10
+ readonly derived: "search indexes are rebuilt from the content, not copied";
11
+ readonly secret: "tables holding passwords, keys or sign-in tokens are not copied";
12
+ };
13
+ export interface SnapshotTablePlan {
14
+ /** Core tables first (foreign-key-safe order), then the snapshot's other tables by name. */
15
+ readonly tables: readonly TransferTable[];
16
+ readonly leftOut: readonly {
17
+ readonly table: string;
18
+ readonly reason: string;
19
+ }[];
20
+ }
21
+ /**
22
+ * The migration ledgers (supplied by the host) stay behind: the
23
+ * target is built to head by its own runner, and a copied SQLite ledger would tell it steps had run there.
24
+ */
25
+ export interface SnapshotTablePolicy {
26
+ readonly coreTables: readonly TransferTable[];
27
+ readonly coreNames: ReadonlySet<string>;
28
+ readonly excludedTables: Readonly<Record<string, string>>;
29
+ readonly derivedNames: ReadonlySet<string>;
30
+ readonly migrationLedgers: ReadonlySet<string>;
31
+ readonly bookkeepingPrefixes: readonly string[];
32
+ readonly secretColumnPattern: RegExp;
33
+ }
34
+ /**
35
+ * Sorts every table in the snapshot into copied or left out (with the reason). Core tables come from
36
+ * the injected host catalog even when the snapshot lacks them, so {@link countSourceRows} can name the gap.
37
+ *
38
+ * @complexity O(snapshot tables) PRAGMA reads.
39
+ */
40
+ export declare function planSnapshotTables({ source, policy }: {
41
+ source: TransferSource;
42
+ policy: SnapshotTablePolicy;
43
+ }, _optional?: {}): SnapshotTablePlan;
44
+ //# sourceMappingURL=table-catalog.d.ts.map
@@ -0,0 +1,109 @@
1
+ /** SQLite type affinity (https://sqlite.org/datatype3.html §3.1), mapped onto a Postgres type. */
2
+ function postgresTypeFor(declaredType) {
3
+ const type = declaredType.toUpperCase();
4
+ if (type.includes("INT"))
5
+ return "bigint";
6
+ if (/CHAR|CLOB|TEXT/.test(type))
7
+ return "text";
8
+ if (type.includes("BLOB"))
9
+ return "bytea";
10
+ if (/REAL|FLOA|DOUB/.test(type))
11
+ return "double precision";
12
+ return "text";
13
+ }
14
+ /** Only plain literals travel: a number, or a single-quoted string. Anything else (a function call) is dropped. */
15
+ function literalDefault(defaultSql, sqlType) {
16
+ if (defaultSql === null || sqlType === "bytea")
17
+ return undefined;
18
+ const text = defaultSql.trim();
19
+ if (/^-?\d+(\.\d+)?$/.test(text) || /^'(?:[^']|'')*'$/.test(text))
20
+ return text;
21
+ return undefined;
22
+ }
23
+ function introspectedColumn(column, rowId) {
24
+ const sqlType = postgresTypeFor(column.declaredType);
25
+ const fallback = literalDefault(column.defaultSql, sqlType);
26
+ return {
27
+ name: column.name,
28
+ sqlType,
29
+ notNull: column.notNull || column.primaryKeyPosition > 0,
30
+ ...(fallback === undefined ? {} : { default: fallback }),
31
+ ...(rowId ? { identity: "BY DEFAULT" } : {}),
32
+ };
33
+ }
34
+ /** A table no host schema file describes, in the layout the snapshot declares. */
35
+ export function introspectedTable({ name, layout }, _optional = {}) {
36
+ const primaryKey = layout.columns.filter((column) => column.primaryKeyPosition > 0).sort((a, b) => a.primaryKeyPosition - b.primaryKeyPosition).map((column) => column.name);
37
+ const rowIdColumn = primaryKey.length === 1 ? layout.columns.find((column) => column.name === primaryKey[0] && column.declaredType.toUpperCase() === "INTEGER") : undefined;
38
+ const indexes = layout.indexes
39
+ .filter((index) => index.origin !== "pk" && !index.partial && index.columns.every((column) => column !== null))
40
+ .map((index) => {
41
+ const columns = index.columns;
42
+ return { name: index.origin === "u" ? `${name}_${columns.join("_")}_key` : index.name, columns, unique: index.unique };
43
+ });
44
+ return {
45
+ name,
46
+ columns: layout.columns.map((column) => introspectedColumn(column, column === rowIdColumn)),
47
+ primaryKey,
48
+ indexes,
49
+ foreignKeys: layout.foreignKeys.map((fk) => ({
50
+ name: `${name}_${fk.columns.join("_")}_fkey`,
51
+ columns: fk.columns,
52
+ foreignTable: fk.foreignTable,
53
+ foreignColumns: fk.foreignColumns.some((column) => column === null) ? null : fk.foreignColumns,
54
+ onDelete: fk.onDelete.toLowerCase(),
55
+ onUpdate: fk.onUpdate.toLowerCase(),
56
+ })),
57
+ checks: [],
58
+ };
59
+ }
60
+ export const LEFT_OUT_REASON = {
61
+ bookkeeping: "the database's own bookkeeping is not copied",
62
+ derived: "search indexes are rebuilt from the content, not copied",
63
+ secret: "tables holding passwords, keys or sign-in tokens are not copied",
64
+ };
65
+ function isBookkeeping(name, policy) {
66
+ return policy.migrationLedgers.has(name) || policy.bookkeepingPrefixes.some(prefix => name.startsWith(prefix));
67
+ }
68
+ /** The reason a non-core table stays behind, or `null` when it is copied. */
69
+ function reasonToLeaveOut(name, layout, derived, virtualTables, policy) {
70
+ if (isBookkeeping(name, policy))
71
+ return LEFT_OUT_REASON.bookkeeping;
72
+ if (derived.has(name) || layout.virtual || virtualTables.some((vt) => name.startsWith(`${vt}_`)))
73
+ return LEFT_OUT_REASON.derived;
74
+ if (layout.columns.some((column) => new RegExp(policy.secretColumnPattern.source, policy.secretColumnPattern.flags.replace(/[gy]/g, "")).test(column.name)))
75
+ return LEFT_OUT_REASON.secret;
76
+ return null;
77
+ }
78
+ /**
79
+ * Sorts every table in the snapshot into copied or left out (with the reason). Core tables come from
80
+ * the injected host catalog even when the snapshot lacks them, so {@link countSourceRows} can name the gap.
81
+ *
82
+ * @complexity O(snapshot tables) PRAGMA reads.
83
+ */
84
+ export function planSnapshotTables({ source, policy }, _optional = {}) {
85
+ const core = policy.coreNames;
86
+ const tables = [...policy.coreTables];
87
+ const leftOut = [];
88
+ const derived = policy.derivedNames;
89
+ const names = source.tableNames();
90
+ const layouts = new Map(names.map((name) => [name, source.layout(name)]));
91
+ const virtualTables = names.filter((name) => layouts.get(name)?.virtual === true);
92
+ for (const name of names) {
93
+ const excluded = policy.excludedTables[name];
94
+ if (excluded !== undefined) {
95
+ leftOut.push({ table: name, reason: excluded });
96
+ continue;
97
+ }
98
+ const layout = layouts.get(name);
99
+ if (core.has(name) || layout === null || layout === undefined)
100
+ continue;
101
+ const reason = reasonToLeaveOut(name, layout, derived, virtualTables, policy);
102
+ if (reason === null)
103
+ tables.push(introspectedTable({ name, layout }));
104
+ else
105
+ leftOut.push({ table: name, reason });
106
+ }
107
+ return { tables, leftOut };
108
+ }
109
+ //# sourceMappingURL=table-catalog.js.map
@@ -0,0 +1,47 @@
1
+ export interface TransferColumn {
2
+ readonly name: string;
3
+ readonly sqlType: string;
4
+ readonly notNull: boolean;
5
+ /** A Postgres default expression, already SQL. */
6
+ readonly default?: string;
7
+ /** Postgres identity kind; the copy writes the source's numbers, then moves the counter past them. */
8
+ readonly identity?: "ALWAYS" | "BY DEFAULT";
9
+ }
10
+ export interface TransferIndex {
11
+ readonly name: string;
12
+ readonly columns: readonly string[];
13
+ readonly unique: boolean;
14
+ }
15
+ export interface TransferForeignKey {
16
+ readonly name: string;
17
+ readonly columns: readonly string[];
18
+ readonly foreignTable: string;
19
+ /** `null` = the parent's primary key (a SQLite foreign key may leave its columns out). */
20
+ readonly foreignColumns: readonly string[] | null;
21
+ readonly onDelete: string;
22
+ readonly onUpdate: string;
23
+ }
24
+ export interface TransferCheck {
25
+ readonly name: string;
26
+ readonly sql: string;
27
+ }
28
+ export interface TransferTable {
29
+ readonly name: string;
30
+ readonly columns: readonly TransferColumn[];
31
+ readonly primaryKey: readonly string[];
32
+ /** A source-side predicate selecting the rows that are copied; absent = every row. */
33
+ readonly keep?: string;
34
+ readonly indexes: readonly TransferIndex[];
35
+ readonly foreignKeys: readonly TransferForeignKey[];
36
+ readonly checks: readonly TransferCheck[];
37
+ }
38
+ /** Host identifiers are required: changing a marker name would orphan earlier copies. */
39
+ export interface TransferNaming {
40
+ readonly defaultSchema: string;
41
+ readonly markerTable: string;
42
+ readonly unvalidatedTable: string;
43
+ readonly schemaPrefix: string;
44
+ /** Optional SQL dollar-quote tag for compatibility with existing script consumers. */
45
+ readonly sqlTag?: string;
46
+ }
47
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
package/package.json ADDED
@@ -0,0 +1,184 @@
1
+ {
2
+ "name": "@jini-ai/db",
3
+ "version": "0.2.0",
4
+ "description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/AINSEP/Jini.git",
9
+ "directory": "packages/db"
10
+ },
11
+ "jini": {
12
+ "domain": "server",
13
+ "kind": "persistence-adapter",
14
+ "runtime": "node",
15
+ "neutralEntries": [
16
+ "src/core"
17
+ ]
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "exports": {
22
+ "./core": {
23
+ "types": "./dist/core/index.d.ts",
24
+ "import": "./dist/core/index.js",
25
+ "default": "./dist/core/index.js"
26
+ },
27
+ "./sqlite": {
28
+ "types": "./dist/sqlite/index.d.ts",
29
+ "import": "./dist/sqlite/index.js",
30
+ "default": "./dist/sqlite/index.js"
31
+ },
32
+ "./pglite": {
33
+ "types": "./dist/pglite/index.d.ts",
34
+ "import": "./dist/pglite/index.js",
35
+ "default": "./dist/pglite/index.js"
36
+ },
37
+ "./postgres": {
38
+ "types": "./dist/postgres/index.d.ts",
39
+ "import": "./dist/postgres/index.js",
40
+ "default": "./dist/postgres/index.js"
41
+ },
42
+ "./kernel": {
43
+ "types": "./dist/kernel/index.d.ts",
44
+ "import": "./dist/kernel/index.js",
45
+ "default": "./dist/kernel/index.js"
46
+ },
47
+ "./kernel/sqlite": {
48
+ "types": "./dist/kernel/sqlite/index.d.ts",
49
+ "import": "./dist/kernel/sqlite/index.js",
50
+ "default": "./dist/kernel/sqlite/index.js"
51
+ },
52
+ "./kernel/pglite": {
53
+ "types": "./dist/kernel/pglite/index.d.ts",
54
+ "import": "./dist/kernel/pglite/index.js",
55
+ "default": "./dist/kernel/pglite/index.js"
56
+ },
57
+ "./kernel/postgres": {
58
+ "types": "./dist/kernel/postgres/index.d.ts",
59
+ "import": "./dist/kernel/postgres/index.js",
60
+ "default": "./dist/kernel/postgres/index.js"
61
+ },
62
+ "./migrate": {
63
+ "types": "./dist/migrate/index.d.ts",
64
+ "import": "./dist/migrate/index.js",
65
+ "default": "./dist/migrate/index.js"
66
+ },
67
+ "./package.json": "./package.json",
68
+ "./transfer": {
69
+ "types": "./dist/transfer/index.d.ts",
70
+ "import": "./dist/transfer/index.js",
71
+ "default": "./dist/transfer/index.js"
72
+ },
73
+ "./tools": {
74
+ "types": "./dist/tools/index.d.ts",
75
+ "import": "./dist/tools/index.js",
76
+ "default": "./dist/tools/index.js"
77
+ },
78
+ "./kernel/store-copy": {
79
+ "types": "./dist/kernel/store-copy.d.ts",
80
+ "import": "./dist/kernel/store-copy.js",
81
+ "default": "./dist/kernel/store-copy.js"
82
+ }
83
+ },
84
+ "typesVersions": {
85
+ "*": {
86
+ "core": [
87
+ "./dist/core/index.d.ts"
88
+ ],
89
+ "sqlite": [
90
+ "./dist/sqlite/index.d.ts"
91
+ ],
92
+ "pglite": [
93
+ "./dist/pglite/index.d.ts"
94
+ ],
95
+ "postgres": [
96
+ "./dist/postgres/index.d.ts"
97
+ ],
98
+ "kernel": [
99
+ "./dist/kernel/index.d.ts"
100
+ ],
101
+ "kernel/sqlite": [
102
+ "./dist/kernel/sqlite/index.d.ts"
103
+ ],
104
+ "kernel/pglite": [
105
+ "./dist/kernel/pglite/index.d.ts"
106
+ ],
107
+ "kernel/postgres": [
108
+ "./dist/kernel/postgres/index.d.ts"
109
+ ],
110
+ "migrate": [
111
+ "./dist/migrate/index.d.ts"
112
+ ],
113
+ "package.json": [
114
+ "./package.json"
115
+ ],
116
+ "transfer": [
117
+ "./dist/transfer/index.d.ts"
118
+ ],
119
+ "tools": [
120
+ "./dist/tools/index.d.ts"
121
+ ],
122
+ "kernel/store-copy": [
123
+ "./dist/kernel/store-copy.d.ts"
124
+ ]
125
+ }
126
+ },
127
+ "files": [
128
+ "dist",
129
+ "README.md",
130
+ "CHANGELOG.md",
131
+ "LICENSE",
132
+ "NOTICE.md",
133
+ "LICENSE.pglite-socket",
134
+ "!dist/**/*.test.js",
135
+ "!dist/**/*.test.d.ts",
136
+ "!dist/**/__tests__/**",
137
+ "!dist/**/testing/**",
138
+ "!dist/**/*.map"
139
+ ],
140
+ "publishConfig": {
141
+ "access": "public",
142
+ "registry": "https://registry.npmjs.org"
143
+ },
144
+ "peerDependencies": {
145
+ "kysely": "^0.29.6",
146
+ "better-sqlite3": "^13.0.0",
147
+ "@electric-sql/pglite": "0.5.8",
148
+ "pg": "^8.23.0"
149
+ },
150
+ "peerDependenciesMeta": {
151
+ "better-sqlite3": {
152
+ "optional": true
153
+ },
154
+ "@electric-sql/pglite": {
155
+ "optional": true
156
+ },
157
+ "pg": {
158
+ "optional": true
159
+ },
160
+ "kysely": {
161
+ "optional": true
162
+ }
163
+ },
164
+ "devDependencies": {
165
+ "@electric-sql/pglite": "0.5.8",
166
+ "@types/better-sqlite3": "7.6.13",
167
+ "@types/pg": "8.23.1",
168
+ "@vitest/coverage-v8": "^2.1.9",
169
+ "better-sqlite3": "13.0.3",
170
+ "kysely": "0.29.6",
171
+ "pg": "8.23.0",
172
+ "@jini-ai/core": "0.4.0"
173
+ },
174
+ "dependencies": {
175
+ "@jini-ai/core": "0.4.0"
176
+ },
177
+ "scripts": {
178
+ "build": "tsc -p tsconfig.build.json",
179
+ "typecheck": "tsc -p tsconfig.json --noEmit",
180
+ "test": "vitest run",
181
+ "test:coverage": "vitest run --coverage",
182
+ "test:postgres": "vitest run --config vitest.postgres.config.ts"
183
+ }
184
+ }