@jini-ai/db 0.3.5 → 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.
@@ -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.5",
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.7"
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/core": "0.4.7",
230
- "@jini-ai/platform": "0.5.9"
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",