@jini-ai/db 0.3.4 → 0.3.6

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.
@@ -63,22 +63,9 @@ function readSqliteTableCounts({ db }, { strict = false } = {}) {
63
63
  for (const { name } of names) {
64
64
  if (strict ? name.startsWith('sqlite_') : isSystemTable(name))
65
65
  continue;
66
- try {
67
- const safe = strict ? name : sanitizeTableName(name);
68
- if (!safe)
69
- continue;
70
- const quoted = '"' + safe.replaceAll('"', '""') + '"';
71
- const row = db.prepare(`SELECT count(*) AS c FROM ${quoted}`).get();
72
- if (strict && (!row || !Number.isSafeInteger(row.c) || row.c < 0))
73
- throw new Error(`Could not count table ${name}.`);
74
- tables.push({ name: safe, rowCount: row?.c ?? 0 });
75
- }
76
- catch (error) {
77
- if (strict)
78
- throw error;
79
- // A malformed view / corrupted table shouldn't fail the whole report; record 0 rows.
80
- tables.push({ name, rowCount: 0 });
81
- }
66
+ const count = readSqliteTableCount({ db, name, strict });
67
+ if (count)
68
+ tables.push(count);
82
69
  }
83
70
  }
84
71
  catch (error) {
@@ -89,6 +76,28 @@ function readSqliteTableCounts({ db }, { strict = false } = {}) {
89
76
  }
90
77
  return tables;
91
78
  }
79
+ function requireValidCount({ row, name }, _options = {}) {
80
+ if (!row || !Number.isSafeInteger(row.c) || row.c < 0)
81
+ throw new Error(`Could not count table ${name}.`);
82
+ }
83
+ function readSqliteTableCount({ db, name, strict }, _options = {}) {
84
+ try {
85
+ const safe = strict ? name : sanitizeTableName(name);
86
+ if (!safe)
87
+ return null;
88
+ const quoted = '"' + safe.replaceAll('"', '""') + '"';
89
+ const row = db.prepare(`SELECT count(*) AS c FROM ${quoted}`).get();
90
+ if (strict)
91
+ requireValidCount({ row, name });
92
+ return { name: safe, rowCount: row?.c ?? 0 };
93
+ }
94
+ catch (error) {
95
+ if (strict)
96
+ throw error;
97
+ // A malformed view / corrupted table shouldn't fail the whole report; record 0 rows.
98
+ return { name, rowCount: 0 };
99
+ }
100
+ }
92
101
  async function sumFileSizes(paths) {
93
102
  let total = 0;
94
103
  for (const p of paths) {
@@ -109,25 +118,16 @@ function sanitizeTableName(name) {
109
118
  return null;
110
119
  return name;
111
120
  }
112
- /**
113
- * Runs `PRAGMA integrity_check` (or `quick_check`) plus `PRAGMA foreign_key_check`
114
- * against an open database and returns a structured report so a CLI can
115
- * pretty-print it and automation can parse the JSON.
116
- *
117
- * @param opts - The open database handle and whether to use the faster `quick_check` variant.
118
- * @returns `{ ok: true }` when both pragmas report clean; otherwise the list of issues found.
119
- * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
120
- * propagating — a caller polling DB health should always get a report, not an exception.
121
- */
122
- export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
123
- const { db, quick = false } = opts;
124
- const startedAt = Date.now();
121
+ function hasSuccessfulIntegrityResult({ rows, pragma }, _options = {}) {
122
+ // Exactly one row, read once: `row !== undefined` and an empty `rest` together are `rows.length === 1`.
123
+ const [row, ...rest] = rows;
124
+ return row !== undefined && rest.length === 0 && String(row[pragma] ?? Object.values(row)[0]).toLowerCase() === 'ok';
125
+ }
126
+ function readIntegrityIssues({ db, pragma }, { strict = false } = {}) {
125
127
  const issues = [];
126
- // 1. integrity_check / quick_check.
127
- const pragma = quick ? 'quick_check' : 'integrity_check';
128
128
  try {
129
129
  const rows = db.pragma(pragma);
130
- if (includeRowCounts && (rows.length !== 1 || String(rows[0]?.[pragma] ?? Object.values(rows[0] ?? {})[0]).toLowerCase() !== 'ok')) {
130
+ if (strict && !hasSuccessfulIntegrityResult({ rows, pragma })) {
131
131
  issues.push({ kind: 'integrity', message: 'A stopped transfer requires exactly one successful integrity result.' });
132
132
  }
133
133
  for (const row of rows) {
@@ -144,7 +144,10 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
144
144
  catch (err) {
145
145
  issues.push({ kind: 'integrity', message: `pragma ${pragma} threw: ${err.message}` });
146
146
  }
147
- // 2. foreign_key_check.
147
+ return issues;
148
+ }
149
+ function readForeignKeyIssues({ db }, _options = {}) {
150
+ const issues = [];
148
151
  try {
149
152
  const rows = db.pragma('foreign_key_check');
150
153
  for (const row of rows) {
@@ -161,6 +164,26 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
161
164
  catch (err) {
162
165
  issues.push({ kind: 'foreign_key', message: `pragma foreign_key_check threw: ${err.message}` });
163
166
  }
167
+ return issues;
168
+ }
169
+ /**
170
+ * Runs `PRAGMA integrity_check` (or `quick_check`) plus `PRAGMA foreign_key_check`
171
+ * against an open database and returns a structured report so a CLI can
172
+ * pretty-print it and automation can parse the JSON.
173
+ *
174
+ * @param opts - The open database handle and whether to use the faster `quick_check` variant.
175
+ * @returns `{ ok: true }` when both pragmas report clean; otherwise the list of issues found.
176
+ * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
177
+ * propagating — a caller polling DB health should always get a report, not an exception.
178
+ */
179
+ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
180
+ const { db, quick = false } = opts;
181
+ const startedAt = Date.now();
182
+ // 1. integrity_check / quick_check.
183
+ const pragma = quick ? 'quick_check' : 'integrity_check';
184
+ const integrityIssues = readIntegrityIssues({ db, pragma }, { strict: includeRowCounts });
185
+ // 2. foreign_key_check.
186
+ const issues = integrityIssues.concat(readForeignKeyIssues({ db }));
164
187
  let rowCounts;
165
188
  if (includeRowCounts && issues.length === 0) {
166
189
  try {
@@ -173,7 +196,7 @@ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
173
196
  return {
174
197
  ...(includeRowCounts ? { rowCounts } : {}),
175
198
  ok: issues.length === 0,
176
- mode: quick ? 'quick_check' : 'integrity_check',
199
+ mode: pragma,
177
200
  issues,
178
201
  elapsedMs: Date.now() - startedAt,
179
202
  generatedAt: Date.now(),
@@ -15,11 +15,12 @@ export class DatabaseTransferPlanStore {
15
15
  if (plan.expiresAtMs <= nowMs)
16
16
  this.plans.delete(id);
17
17
  }
18
- while (this.plans.size >= DEFAULT_MAX_PLANS) {
19
- const oldest = this.plans.keys().next().value;
20
- if (oldest === undefined)
18
+ // Evict oldest-first (a Map iterates in insertion order) until there is room for this plan. The
19
+ // former `oldest === undefined` guard is gone: iterating the keys themselves cannot yield a missing one.
20
+ for (const id of this.plans.keys()) {
21
+ if (this.plans.size < DEFAULT_MAX_PLANS)
21
22
  break;
22
- this.plans.delete(oldest);
23
+ this.plans.delete(id);
23
24
  }
24
25
  const plan = { ...input.content, planId: randomUUID(), principalId: input.principalId, workspaceId: input.workspaceId, expiresAtMs: nowMs + DEFAULT_PLAN_TTL_MS };
25
26
  this.plans.set(plan.planId, plan);
@@ -76,6 +76,9 @@ export function createDatabaseReadTools(ports, _optional = {}) {
76
76
  return captured;
77
77
  },
78
78
  }, { messages });
79
+ // `createDatabaseRestorePoint` resolves only after awaiting `capture()` (restore-points.ts), so
80
+ // `captured` is always set here; the former `captured?.… ?? null` fallbacks could never apply.
81
+ const { watermarkAtCapture, artifactRef } = captured;
79
82
  await ports.restorePoints.save({
80
83
  restorePointId: summary.id,
81
84
  idempotencyKey: ports.idGen.newId(),
@@ -87,8 +90,8 @@ export function createDatabaseReadTools(ports, _optional = {}) {
87
90
  createdBy: ctx.principal.id,
88
91
  costClass: summary.costClass,
89
92
  kind: summary.kind,
90
- watermarkAtCapture: captured?.watermarkAtCapture ?? null,
91
- artifactRef: captured?.artifactRef,
93
+ watermarkAtCapture,
94
+ artifactRef,
92
95
  });
93
96
  return { restorePoint: summary };
94
97
  },
@@ -69,14 +69,21 @@ export interface DatabaseTransferToolPorts {
69
69
  readers: Pick<InputReaders, "inputRecord" | "string">;
70
70
  surfaces: TransferSurfacePorts;
71
71
  }
72
+ /** The restore-point file the plan reads once and then deletes; defaults to `node:fs/promises`. */
73
+ export interface SnapshotFilePort {
74
+ readFile(path: string): Promise<Buffer>;
75
+ unlink(path: string): Promise<void>;
76
+ }
72
77
  /**
73
78
  * Returns core registrations; the host applies its independent risk/error plumbing.
74
79
  * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
75
80
  * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
81
+ * `optional.files` reads and deletes the restore-point snapshot file; it defaults to `node:fs/promises`.
76
82
  * @complexity O(1) fixed tool records plus the description formatter's text length.
77
83
  * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
78
84
  */
79
85
  export declare function createDatabaseTransferTools(deps: DatabaseTransferToolPorts, optional?: {
80
86
  messages?: DbTransferMessages & Partial<DbMessages>;
87
+ files?: SnapshotFilePort;
81
88
  }): ToolRegistration[];
82
89
  //# sourceMappingURL=transfer-tools.d.ts.map
@@ -6,6 +6,7 @@ import { defaultDbMessages } from "../core/messages.js";
6
6
  import { registrations } from "./registration.js";
7
7
  const SET_DESTINATION_TOOL_ID = "database_transfer_set_destination";
8
8
  const DATABASE_TRANSFER_RUN_TOOL_ID = "database_transfer_run";
9
+ const nodeSnapshotFiles = { readFile, unlink };
9
10
  function destinationsOf(deps) {
10
11
  return deps.ports.destinations;
11
12
  }
@@ -34,16 +35,18 @@ async function captureSnapshot(deps) {
34
35
  log(deps, `snapshot failed: ${deps.ports.describeError(err)}`);
35
36
  return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database could not be snapshotted; nothing was copied" };
36
37
  }
38
+ let bytes;
37
39
  try {
38
- return { ok: true, bytes: await readFile(artifactRef) };
40
+ bytes = await deps.files.readFile(artifactRef);
39
41
  }
40
42
  catch (err) {
41
43
  log(deps, `snapshot read failed: ${deps.ports.describeError(err)}`);
42
44
  return { code: "DATABASE_SNAPSHOT_FAILED", message: "the site database snapshot could not be read; nothing was copied" };
43
45
  }
44
46
  finally {
45
- await unlink(artifactRef).catch(() => undefined);
47
+ await deps.files.unlink(artifactRef).catch(() => undefined);
46
48
  }
49
+ return { ok: true, bytes };
47
50
  }
48
51
  /** The site name copies are marked with; it also picks the site's schema (`copy-engine.ts`). */
49
52
  function siteOf(deps) {
@@ -89,6 +92,7 @@ function snapshotSources(deps, snapshot, chatSnapshot) {
89
92
  /** Row counts and reasons use each physical source's own catalog; no raw-SQL tables disappear. */
90
93
  function countSnapshot(deps, bytes, chatSnapshot) {
91
94
  let sources = [];
95
+ let counted;
92
96
  try {
93
97
  sources = snapshotSources(deps, bytes, chatSnapshot);
94
98
  const counts = sources.flatMap(entry => countSourceRows({ source: entry.source, tables: entry.tables }, { messages: deps.messages }));
@@ -98,7 +102,7 @@ function countSnapshot(deps, bytes, chatSnapshot) {
98
102
  ...entry.leftOut.filter(item => item.reason !== LEFT_OUT_REASON.bookkeeping && item.reason !== LEFT_OUT_REASON.derived).map(item => ({ ...item, rows: entry.source.countRows(item.table) })),
99
103
  ...deps.ports.partialExclusions(entry.name, entry.source),
100
104
  ]);
101
- return { ok: true, tableCount: counts.length, rowCount: counts.reduce((sum, count) => sum + count.rows, 0), leftOut };
105
+ counted = { ok: true, tableCount: counts.length, rowCount: counts.reduce((sum, count) => sum + count.rows, 0), leftOut };
102
106
  }
103
107
  catch (err) {
104
108
  if (err instanceof SourceSchemaMismatchError || err instanceof IncompleteTransferPlanError)
@@ -109,6 +113,7 @@ function countSnapshot(deps, bytes, chatSnapshot) {
109
113
  for (const entry of sources)
110
114
  entry.source.close();
111
115
  }
116
+ return counted;
112
117
  }
113
118
  function planResult(plan) {
114
119
  return {
@@ -239,8 +244,9 @@ async function handleRun(deps, surfaces, ctx, optional = {}) {
239
244
  askHuman: ({ ctx: snapshot, description }, options) => {
240
245
  if (!options.emitSurface)
241
246
  throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
242
- if (!description)
243
- throw new ToolInputError({ message: "No transfer plan can be approved. Nothing was copied." });
247
+ // core's createApprovalHandler asks only when `describe` set `ask`, and `ask` is true only beside a
248
+ // taken plan, so `description` is always that plan here; the former "No transfer plan can be
249
+ // approved" refusal could never run.
244
250
  return surfaces.confirmApproval({ ctx: snapshot, plan: description }, options);
245
251
  },
246
252
  notConfirmed: ({ reason }) => reason === "declined" ? { copied: false, cancelled: true } : { copied: false, cancelled: false, reason },
@@ -327,11 +333,12 @@ async function handleStatus(deps, ctx) {
327
333
  * Returns core registrations; the host applies its independent risk/error plumbing.
328
334
  * Descriptions reflect required persisted naming; optional messages replace model-facing copy only.
329
335
  * Construction performs no I/O. Host formatter exceptions propagate without mutating ports.
336
+ * `optional.files` reads and deletes the restore-point snapshot file; it defaults to `node:fs/promises`.
330
337
  * @complexity O(1) fixed tool records plus the description formatter's text length.
331
338
  * @example createDatabaseTransferTools(ports, { messages: defaultDbMessages })
332
339
  */
333
340
  export function createDatabaseTransferTools(deps, optional = {}) {
334
- const runtime = { ports: deps, messages: { ...defaultDbMessages, ...optional.messages } };
341
+ const runtime = { ports: deps, messages: { ...defaultDbMessages, ...optional.messages }, files: optional.files ?? nodeSnapshotFiles };
335
342
  const handlers = {
336
343
  [PLAN_TOOL_ID]: ctx => handlePlan(runtime, ctx),
337
344
  [DATABASE_TRANSFER_RUN_TOOL_ID]: (ctx, optional) => handleRun(runtime, runtime.ports.surfaces, ctx, optional),
@@ -1,3 +1,4 @@
1
+ import { FOREIGN_SCHEMA_SIGNAL, COUNT_MISMATCH_SIGNAL } from "./signals.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { defaultDbMessages } from "../core/messages.js";
3
4
  import { constraintSql, createTableSql, indexSql, qualified, quoteIdent, quoteLiteral, reseedIdentitySql } from "./internal-ddl.js";
@@ -124,8 +125,6 @@ function* copyTableData(source, schema, table) {
124
125
  }
125
126
  yield `${batch}\\.\n`;
126
127
  }
127
- const FOREIGN_SCHEMA_SIGNAL = "TRANSFER_TARGET_NOT_OURS";
128
- const COUNT_MISMATCH_SIGNAL = "TRANSFER_COUNT_MISMATCH";
129
128
  /**
130
129
  * Aborts the transaction unless `schema` is absent or holds only this site's copy. The marker is read
131
130
  * with dynamic SQL so a table merely named like it (other columns) also counts as someone else's.
@@ -177,15 +176,25 @@ function* copyScript(sources, naming, schema, counts, marker, replaceExisting) {
177
176
  yield markerSql(schema, marker, counts, naming);
178
177
  yield "COMMIT;\n";
179
178
  }
180
- /** The constraints the committed copy left NOT VALID, from its marker. */
181
- async function readUnvalidated(target, schema, TRANSFER_MARKER_TABLE) {
182
- const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, TRANSFER_MARKER_TABLE)} LIMIT 1`);
183
- const cell = read.ok ? read.value[0]?.[0] : undefined;
184
- if (cell === undefined)
185
- return { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
186
- return { unvalidatedConstraints: JSON.parse(cell) };
179
+ /** Reads the committed constraint list; malformed or failed readback yields a safe warning.
180
+ * O(n) time/space in marker bytes; performs one target query. */
181
+ async function readUnvalidated({ target, schema, markerTable }, _options = {}) {
182
+ const unreadable = { unvalidatedConstraints: [], warning: "the copy finished, but its list of unchecked constraints could not be read back" };
183
+ try {
184
+ const read = await target.query(`SELECT unvalidated FROM ${qualified(schema, markerTable)} LIMIT 1`);
185
+ const cell = read.ok ? read.value[0]?.[0] : undefined;
186
+ if (cell === undefined)
187
+ return unreadable;
188
+ const constraints = JSON.parse(cell);
189
+ if (!Array.isArray(constraints) || !constraints.every(value => typeof value === "string"))
190
+ return unreadable;
191
+ return { unvalidatedConstraints: constraints };
192
+ }
193
+ catch {
194
+ return unreadable;
195
+ }
187
196
  }
188
- export async function runCopy(input, _optional = {}) {
197
+ function prepareCopy(input, _optional = {}) {
189
198
  if (!/^[a-z_][a-z0-9_]*$/.test(input.naming.sqlTag ?? "transfer"))
190
199
  throw new Error("invalid SQL dollar-quote tag");
191
200
  const { sources } = planTransfer({ sources: input.sources });
@@ -206,6 +215,11 @@ export async function runCopy(input, _optional = {}) {
206
215
  if (schema === "public" || !/^[a-z_][a-z0-9_]*$/.test(schema) || Buffer.byteLength(schema) > MAX_IDENTIFIER_BYTES) {
207
216
  throw new Error(`runCopy: '${schema}' is not a schema this copier may write`);
208
217
  }
218
+ return { counted, counts };
219
+ }
220
+ export async function runCopy(input, _optional = {}) {
221
+ const { counted, counts } = prepareCopy(input, _optional);
222
+ const { schema } = input;
209
223
  let result;
210
224
  try {
211
225
  result = await input.target.runScript(copyScript(counted, input.naming, schema, counts, input.marker, input.replaceExisting));
@@ -216,7 +230,7 @@ export async function runCopy(input, _optional = {}) {
216
230
  throw err;
217
231
  }
218
232
  if (result.ok)
219
- return { ok: true, tables: counts.map(({ table, rows }) => ({ name: table.name, rows })), ...(await readUnvalidated(input.target, schema, input.naming.markerTable)) };
233
+ return { ok: true, tables: counts.map(({ table, rows }) => ({ name: table.name, rows })), ...(await readUnvalidated({ target: input.target, schema, markerTable: input.naming.markerTable })) };
220
234
  if (result.error.includes(FOREIGN_SCHEMA_SIGNAL)) {
221
235
  return { ok: false, code: "TARGET_NOT_OURS", message: `the destination already has a '${schema}' area that holds other data. Nothing was written, and it was left untouched.` };
222
236
  }
@@ -17,8 +17,8 @@ export interface TargetDescription {
17
17
  readonly database: string;
18
18
  readonly user: string;
19
19
  }
20
- /** `error` is psql's first ERROR line with every quoted part blanked (Postgres quotes the offending
21
- * value there); `copyTable` names the table a failed `COPY` was loading. */
20
+ /** `error` is a copier-owned failure code or a fixed safe message; server text is private.
21
+ * `copyTable` names the table a failed COPY was loading. */
22
22
  export type TargetResult<T> = {
23
23
  readonly ok: true;
24
24
  readonly value: T;
@@ -50,16 +50,30 @@ export declare function parseConnectionString({ raw }: {
50
50
  }, { applicationName }?: {
51
51
  applicationName?: string;
52
52
  }): ParsedConnection;
53
+ /** The slice of a spawned `psql` child this adapter drives: its three pipes, `error` and `close`. */
54
+ export interface PsqlProcess {
55
+ readonly stdin: NodeJS.WritableStream;
56
+ readonly stdout: NodeJS.ReadableStream;
57
+ readonly stderr: NodeJS.ReadableStream;
58
+ on(event: "error", listener: (error: Error) => void): unknown;
59
+ on(event: "close", listener: (code: number | null) => void): unknown;
60
+ }
61
+ /** Starts `psql` with the given argv and environment; the default resolves it on the host PATH. */
62
+ export type PsqlSpawn = (args: readonly string[], options: {
63
+ env: Record<string, string>;
64
+ }) => PsqlProcess;
53
65
  /**
54
- * The P0 adapter: every call is one short-lived `psql` process.
66
+ * The P0 adapter: every call is one short-lived `psql` process, started through `spawnProcess`
67
+ * (default: `psql` on the host PATH).
55
68
  *
56
69
  * @throws {InvalidConnectionStringError} When the string cannot be parsed.
57
70
  */
58
71
  export declare function createPsqlPostgresTarget({ connectionString }: {
59
72
  connectionString: string;
60
- }, { parentEnv, applicationName }?: {
73
+ }, { parentEnv, applicationName, spawnProcess }?: {
61
74
  parentEnv?: NodeJS.ProcessEnv;
62
75
  applicationName?: string;
76
+ spawnProcess?: PsqlSpawn;
63
77
  }): PostgresTargetPort;
64
78
  export {};
65
79
  //# sourceMappingURL=postgres-target.d.ts.map
@@ -1,12 +1,8 @@
1
+ import { FOREIGN_SCHEMA_SIGNAL, COUNT_MISMATCH_SIGNAL } from "./signals.js";
1
2
  import { spawn } from "node:child_process";
2
3
  export class InvalidConnectionStringError extends Error {
3
4
  }
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" } = {}) {
5
+ function parsePostgresUrl({ raw }, _options = {}) {
10
6
  let url;
11
7
  try {
12
8
  url = new URL(raw.trim());
@@ -17,6 +13,15 @@ export function parseConnectionString({ raw }, { applicationName = "database-tra
17
13
  if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") {
18
14
  throw new InvalidConnectionStringError("the connection string must start with postgres:// or postgresql://");
19
15
  }
16
+ return url;
17
+ }
18
+ /**
19
+ * Splits a `postgres://` / `postgresql://` URL into libpq environment variables.
20
+ *
21
+ * @throws {InvalidConnectionStringError} With a message that never quotes the string itself.
22
+ */
23
+ export function parseConnectionString({ raw }, { applicationName = "database-transfer" } = {}) {
24
+ const url = parsePostgresUrl({ raw });
20
25
  const host = url.searchParams.get("host") ?? decodeURIComponent(url.hostname);
21
26
  const database = decodeURIComponent(url.pathname.replace(/^\//, ""));
22
27
  const user = decodeURIComponent(url.username);
@@ -41,24 +46,31 @@ function environmentWithout(parent) {
41
46
  }
42
47
  return env;
43
48
  }
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) {
49
+ /** Classifies copier failure codes; arbitrary psql text never reaches public errors or logs.
50
+ * @complexity O(n) time/space in stderr length. */
51
+ function failureFrom({ stderr }, _options = {}) {
47
52
  const lines = stderr.split("\n").map((line) => line.trim()).filter((line) => line !== "");
48
53
  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, "");
54
+ const message = line.replace(/^psql:[^ ]*: /, "").replace(/^ERROR:\s*/, "");
55
+ const countMismatch = new RegExp(`^${COUNT_MISMATCH_SIGNAL} ([A-Za-z_][A-Za-z0-9_]{0,62})$`).exec(message);
56
+ const error = message === FOREIGN_SCHEMA_SIGNAL ? FOREIGN_SCHEMA_SIGNAL
57
+ : message.startsWith(`${COUNT_MISMATCH_SIGNAL} `) ? `${COUNT_MISMATCH_SIGNAL} ${countMismatch?.[1] ?? "[redacted]"}` : "psql request failed";
58
+ const copyMatch = /\bCOPY ([A-Za-z0-9_."]+), line \d+/.exec(stderr);
59
+ const copyTable = copyMatch ? copyMatch[1].replace(/"/g, "") : undefined;
51
60
  return copyTable === undefined ? { ok: false, error } : { ok: false, error, copyTable };
52
61
  }
53
- function runPsql(env, args, chunks) {
62
+ const spawnPsql = (args, { env }) =>
63
+ // eslint-disable-next-line sonarjs/no-os-command-from-path -- Operator-installed psql intentionally resolves through the trusted host PATH; connection input supplies PG fields, never the executable or PATH.
64
+ spawn("psql", args, { env, stdio: ["pipe", "pipe", "pipe"] });
65
+ function runPsql(env, args, chunks, launch) {
54
66
  return new Promise((resolve) => {
55
- const child = spawn("psql", ["-X", "-q", "-v", "ON_ERROR_STOP=1", ...args], { env, stdio: ["pipe", "pipe", "pipe"] });
67
+ const child = launch(["-X", "-q", "-v", "ON_ERROR_STOP=1", ...args], { env });
56
68
  let stdout = "";
57
69
  let stderr = "";
58
70
  child.stdout.setEncoding("utf8").on("data", (data) => (stdout += data));
59
71
  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)));
72
+ child.on("error", () => resolve({ ok: false, error: "psql could not be started" }));
73
+ child.on("close", (code) => resolve(code === 0 ? { ok: true, value: stdout } : failureFrom({ stderr })));
62
74
  child.stdin.on("error", () => undefined);
63
75
  void (async () => {
64
76
  for (const chunk of chunks ?? []) {
@@ -70,24 +82,25 @@ function runPsql(env, args, chunks) {
70
82
  });
71
83
  }
72
84
  /**
73
- * The P0 adapter: every call is one short-lived `psql` process.
85
+ * The P0 adapter: every call is one short-lived `psql` process, started through `spawnProcess`
86
+ * (default: `psql` on the host PATH).
74
87
  *
75
88
  * @throws {InvalidConnectionStringError} When the string cannot be parsed.
76
89
  */
77
- export function createPsqlPostgresTarget({ connectionString }, { parentEnv = process.env, applicationName } = {}) {
90
+ export function createPsqlPostgresTarget({ connectionString }, { parentEnv = process.env, applicationName, spawnProcess = spawnPsql } = {}) {
78
91
  const parsed = parseConnectionString({ raw: connectionString }, applicationName === undefined ? {} : { applicationName });
79
92
  const env = { ...environmentWithout(parentEnv), ...parsed.env };
80
93
  return {
81
94
  describe: () => parsed.description,
82
95
  async query(sql) {
83
- const result = await runPsql(env, ["-t", "-A", "-F", "\t", "-c", sql], null);
96
+ const result = await runPsql(env, ["-t", "-A", "-F", "\t", "-c", sql], null, spawnProcess);
84
97
  if (!result.ok)
85
98
  return result;
86
99
  const rows = result.value.split("\n").filter((line) => line !== "").map((line) => line.split("\t"));
87
100
  return { ok: true, value: rows };
88
101
  },
89
102
  async runScript(chunks) {
90
- const result = await runPsql(env, ["-f", "-"], chunks);
103
+ const result = await runPsql(env, ["-f", "-"], chunks, spawnProcess);
91
104
  return result.ok ? { ok: true, value: null } : result;
92
105
  },
93
106
  };
@@ -0,0 +1,4 @@
1
+ /** Copier-owned failure codes shared by generated SQL and the psql error boundary. */
2
+ export declare const FOREIGN_SCHEMA_SIGNAL = "TRANSFER_TARGET_NOT_OURS";
3
+ export declare const COUNT_MISMATCH_SIGNAL = "TRANSFER_COUNT_MISMATCH";
4
+ //# sourceMappingURL=signals.d.ts.map
@@ -0,0 +1,4 @@
1
+ /** Copier-owned failure codes shared by generated SQL and the psql error boundary. */
2
+ export const FOREIGN_SCHEMA_SIGNAL = "TRANSFER_TARGET_NOT_OURS";
3
+ export const COUNT_MISMATCH_SIGNAL = "TRANSFER_COUNT_MISMATCH";
4
+ //# sourceMappingURL=signals.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -192,7 +192,7 @@
192
192
  "registry": "https://registry.npmjs.org"
193
193
  },
194
194
  "dependencies": {
195
- "@jini-ai/core": "^0.4.4"
195
+ "@jini-ai/core": "^0.4.9"
196
196
  },
197
197
  "peerDependencies": {
198
198
  "kysely": "^0.29.6",
@@ -226,8 +226,8 @@
226
226
  "better-sqlite3": "13.0.3",
227
227
  "kysely": "0.29.6",
228
228
  "pg": "8.23.0",
229
- "@jini-ai/platform": "0.5.6",
230
- "@jini-ai/core": "0.4.4"
229
+ "@jini-ai/platform": "0.5.10",
230
+ "@jini-ai/core": "0.4.9"
231
231
  },
232
232
  "scripts": {
233
233
  "build": "tsc -p tsconfig.build.json",