@kaynooo/cli-db 0.9.1 → 0.10.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 (3) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +473 -217
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -14,7 +14,7 @@ bun install -g @kaynooo/cli-db
14
14
  - `--container <name>` (`-c`) reads a running container by name or id, in any compose project or none (a worktree stack, `booki-docker--shot-igesa-db-1`), found with `docker inspect`. It picks the container over the URL, and cannot be combined with `--service`.
15
15
  - The credentials of `--service` and `--container` come from the container's environment, never printed: `POSTGRES_USER`, `POSTGRES_PASSWORD` and `POSTGRES_DB` for Postgres; `MYSQL_USER`, `MYSQL_PASSWORD` and `MYSQL_DATABASE` for MySQL and MariaDB, else `root` with `MYSQL_ROOT_PASSWORD`, each also as `MARIADB_*`. A password kept in a `*_FILE` variable is refused with a hint to give the URL.
16
16
  - `--database <name>` reads another database on the same server, `db dbs` lists them.
17
- - Only a local host (`localhost`, `127.0.0.1`, `::1`, a local socket) or a compose service is connected to. Any other host is refused before connecting, exit 2, with the host (never the URL) and the config path in the message, unless it is listed in `~/.config/db/config.json`: `{ "allowedHosts": ["db.example.com"] }`. A missing or empty list allows only local hosts, and a file that is not valid JSON is ignored with a warning. There is no flag to allow a host.
17
+ - Only a local host (`localhost`, `127.0.0.1`, `::1`, a local socket) or a compose service is connected to. Any other host is refused before connecting, exit 2, with the host (never the URL) and the config path in the message, unless it is listed in `~/.config/kaynooo-cli/db.json` (the older `~/.config/db/config.json` is read while the new file is missing): `{ "allowedHosts": ["db.example.com"] }`. A missing or empty list allows only local hosts, and a file that is not valid JSON is ignored with a warning. There is no flag to allow a host.
18
18
  - MySQL 8 logs in without TLS by fetching the server's RSA key, which `db` allows only for a loopback host and a docker network address (`172.16.0.0/12`). A MySQL 8 elsewhere (an allowed remote host, a docker pool in `192.168.0.0/16`) needs TLS or an account on `mysql_native_password`.
19
19
 
20
20
  ## Commands
@@ -24,20 +24,21 @@ bun install -g @kaynooo/cli-db
24
24
  | `db "<sql>"` / `db query` | runs one read-only statement, as an argument or on stdin |
25
25
  | `db tables` | tables and views with an estimated row count (Postgres: outside the system schemas, MySQL: the connected database) |
26
26
  | `db sample <table>` | a few rows of a table (`-n`, `--where`), sensitive columns masked; `db count <table>` the number of rows |
27
- | `db describe <table>` | columns with type, nullability, default and primary key (`schema.table` to pick a schema, the database on MySQL) |
27
+ | `db describe <table>` | columns with type, nullability, default and primary key, then the indexes and foreign keys (`schema.table` to pick a schema, the database on MySQL); `--json` adds `indexes` and `foreignKeys` |
28
+ | `db search <text>` | tables and columns whose name contains the text, case insensitive, to find where a field lives |
29
+ | `db explain "<sql>"` | the plan of one read without running it: `EXPLAIN` alone through the read-only guard, never `ANALYZE` (a statement not starting with SELECT, WITH, VALUES or TABLE, and a hand-written EXPLAIN or ANALYZE, are refused) |
28
30
  | `db dbs` | databases the connection may open, with their size, the one read marked `current` |
29
31
 
30
- Options: `-n <rows>` caps the rows shown (100) and says when more were left out, `--raw` shows the columns masked by default, `--json` prints `{ columns, rows, truncated, masked }`, `-e <KEY>`, `-s <service>`, `-c <container>` and `-d <database>` pick the connection.
32
+ Options: `-n <rows>` (`--rows`, once `--limit`) caps the rows shown (20) and says when more were left out, `--all` shows up to 100 (the old default, so `-n` for more), `--raw` shows the columns masked by default, `--json` prints `{ columns, rows, truncated, masked }`, `-e <KEY>`, `-s <service>`, `-c <container>` and `-d <database>` pick the connection.
31
33
 
32
34
  ## Safety
33
35
 
34
36
  - Postgres: the session opens with `default_transaction_read_only=on`, `lock_timeout=5s` and `idle_in_transaction_session_timeout=60s`, then the statement runs after `SET LOCAL statement_timeout = '30s'` in `BEGIN READ ONLY`, and the transaction is rolled back, so Postgres itself refuses a write the checks below miss. The transaction does not stop side effects outside it (`pg_terminate_backend`, `COPY ... TO PROGRAM`, `dblink`), which the checks below do.
35
37
  - MySQL and MariaDB: the statement runs in `START TRANSACTION READ ONLY` on one reserved connection, under a 30 second statement timeout (`max_execution_time`, or `max_statement_time` on MariaDB), and the transaction is rolled back. A select is wrapped in `select * from (...) limit n + 1` to stop one row past `-n`, and read whole only when the wrapping does not parse or repeats a column name (errors 1064 and 1060); any other error is reported as is.
36
38
  - A Postgres select is read through a cursor that stops at one row past `-n`, so a huge table is never loaded whole.
37
- - Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused. It must start with `SELECT`, `WITH`, `VALUES`, `TABLE`, `SHOW`, `EXPLAIN`, `DESCRIBE` or `DESC`, and must not use `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `INTO`, `SET`, `FOR UPDATE` and the like anywhere (so a write hidden in a CTE is caught), nor start with `REPLACE`, `LOAD`, `RENAME`, `FLUSH`, `PREPARE`, `EXECUTE` and the like, nor `SET GLOBAL`, `SET PERSIST`, `SET @@...`, nor functions with side effects (`nextval`, `setval`, `set_config`, `pg_terminate_backend`, `pg_sleep`, `pg_ls_*`, `lo_*`, `dblink`, `sleep`, `benchmark`, `get_lock`, `load_file`, ...).
38
- - Such a statement is printed as a `sql` block with the reasons and `db` exits 1 without running it. Several statements in one string are refused unless each reads, and then run one at a time.
39
- - Columns named like emails, phones, tokens, secrets, passwords or hashes show `***` unless `--raw`. `NULL` stays `NULL`.
40
- - Every message, errors included, is scrubbed of the URL, the password (raw and decoded) and any `scheme://user:password@`.
39
+ - Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused. The allowed starts, the refused keywords and the refused functions are in `db query --help`.
40
+ - Such a statement is printed as a `sql` block with the reasons and `db` exits 1 without running it. Several statements in one string are refused (exit 2) even when each reads: one statement at a time.
41
+ - Columns named like emails, phones, tokens, secrets, passwords or hashes show `***` unless `--raw` (`NULL` stays `NULL`), and every message, errors included, is scrubbed of the URL and the password (raw and decoded).
41
42
 
42
43
  ## Writes on a test database
43
44
 
package/dist/cli.js CHANGED
@@ -2,17 +2,16 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process8 from "process";
6
-
5
+ import process13 from "process";
7
6
  // ../kit/src/args.ts
8
- import process3 from "process";
7
+ import process6 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/format.ts
12
- import process2 from "process";
11
+ import process3 from "process";
13
12
 
14
13
  // ../kit/src/style.ts
15
- import process from "process";
14
+ import process2 from "process";
16
15
 
17
16
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
17
  function x(s) {
@@ -282,20 +281,20 @@ var MARKS = {
282
281
  problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
282
  note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
283
  };
285
- function takesControlCodes(stream, env = process.env) {
284
+ function takesControlCodes(stream, env = process2.env) {
286
285
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
286
  }
288
- function paint(stream, env = process.env) {
287
+ function paint(stream, env = process2.env) {
289
288
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
289
  }
291
- function marked(mark, text, stream, detail, env = process.env) {
290
+ function marked(mark, text, stream, detail, env = process2.env) {
292
291
  const colors = paint(stream, env);
293
292
  const { symbol, word, paint: tint } = MARKS[mark];
294
293
  const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
295
294
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
296
295
  }
297
296
  function warn(text, detail) {
298
- console.error(marked("warn", text, process.stderr, detail));
297
+ console.error(marked("warn", text, process2.stderr, detail));
299
298
  }
300
299
  var STATUSES = {
301
300
  passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
@@ -327,7 +326,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
327
326
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
328
327
  }
329
328
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
330
- const colors = paint(process2.stdout);
329
+ const colors = paint(process3.stdout);
331
330
  const lines = shown.map((row) => row.map((cell, index) => {
332
331
  const width = widths[index] ?? 0;
333
332
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -355,6 +354,63 @@ function narrow(rows, widths, limit) {
355
354
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
356
355
  }
357
356
 
357
+ // ../kit/src/help.ts
358
+ import process4 from "process";
359
+ var OPTIONAL = /\[[^\]]+\]/g;
360
+ var USAGE_PREFIX = /^usage:\s*/i;
361
+ var FULL_STOP = /\.$/;
362
+ function usageLine(usage, colors = paint(process4.stdout)) {
363
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
364
+ }
365
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
366
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
367
+ `);
368
+ }
369
+ function exitRows(exits, colors = paint(process4.stdout)) {
370
+ if (exits.length === 0)
371
+ return [];
372
+ const width = Math.max(...exits.map(([code]) => String(code).length));
373
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
374
+ }
375
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
376
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
+ }
378
+ function wantsHelpJson(env = process4.env) {
379
+ return env.KIT_HELP === "json";
380
+ }
381
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
382
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
383
+ `);
384
+ const first = lines[0];
385
+ const colon = first.indexOf(": ");
386
+ const prose = lines[lines.indexOf("") + 1] ?? "";
387
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
388
+ return {
389
+ synopsis: colon === -1 ? first : first.slice(0, colon),
390
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
391
+ ...replaces === undefined ? {} : { replaces },
392
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
393
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
394
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
395
+ };
396
+ }
397
+ function exampleRows(examples, colors = paint(process4.stdout)) {
398
+ if (examples.length === 0)
399
+ return [];
400
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
401
+ }
402
+ function optionRows(options, colors = paint(process4.stdout)) {
403
+ const rows = Object.entries(options).map(([name, option]) => {
404
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
405
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
406
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
407
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
408
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
409
+ });
410
+ const width = Math.max(0, ...rows.map((row) => row.width));
411
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
412
+ }
413
+
358
414
  // ../kit/src/text.ts
359
415
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
360
416
  function distance(a, b) {
@@ -374,8 +430,31 @@ function closest(name, names) {
374
430
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
375
431
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
376
432
  }
433
+ // ../kit/src/input.ts
434
+ import process5 from "process";
435
+ var WHOLE = /^\d+$/;
436
+ function wholeNumber(value, name, fallback, min = 1) {
437
+ if (value === undefined)
438
+ return fallback;
439
+ const number = Number(value);
440
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
441
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
442
+ return number;
443
+ }
444
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
445
+ if (path === "-") {
446
+ if (process5.stdin.isTTY)
447
+ fail(noStdin);
448
+ return Bun.stdin.text();
449
+ }
450
+ const file = Bun.file(path);
451
+ if (!await file.exists())
452
+ fail(`no file ${path}`);
453
+ return file.text();
454
+ }
377
455
 
378
456
  // ../kit/src/args.ts
457
+ var DASHES = /^-+/;
379
458
  function jsonOption(holds) {
380
459
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
381
460
  }
@@ -419,58 +498,11 @@ class Completing {
419
498
  }
420
499
  }
421
500
  var completion = { active: false };
422
- var OPTIONAL = /\[[^\]]+\]/g;
423
- var USAGE_PREFIX = /^usage:\s*/i;
424
- var FULL_STOP = /\.$/;
425
- var DASHES = /^-+/;
426
- function usageLine(usage, colors = paint(process3.stdout)) {
427
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
428
- }
429
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
430
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
431
- `);
432
- }
433
- function replacesRows(replaces, colors = paint(process3.stdout)) {
434
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
435
- }
436
- function wantsHelpJson(env = process3.env) {
437
- return env.KIT_HELP === "json";
438
- }
439
- function description(usage, { examples = [], replaces } = {}) {
440
- const lines = usage.replace(USAGE_PREFIX, "").split(`
441
- `);
442
- const first = lines[0];
443
- const colon = first.indexOf(": ");
444
- const prose = lines[lines.indexOf("") + 1] ?? "";
445
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
446
- return {
447
- synopsis: colon === -1 ? first : first.slice(0, colon),
448
- summary: colon === -1 ? fallback : first.slice(colon + 2),
449
- ...replaces === undefined ? {} : { replaces },
450
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
451
- };
452
- }
453
- function exampleRows(examples, colors = paint(process3.stdout)) {
454
- if (examples.length === 0)
455
- return [];
456
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
457
- }
458
- function optionRows(options, colors = paint(process3.stdout)) {
459
- const rows = Object.entries(options).map(([name, option]) => {
460
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
461
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
462
- const placeholder = option.optional === undefined ? named : `[${named}]`;
463
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
464
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
465
- });
466
- const width = Math.max(0, ...rows.map((row) => row.width));
467
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
468
- }
469
501
  var OUTPUT_OPTIONS = {
470
502
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
471
503
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
472
504
  };
473
- function applyOutput(color, plain, env = process3.env) {
505
+ function applyOutput(color, plain, env = process6.env) {
474
506
  const when = plain === true ? "never" : color ?? "auto";
475
507
  if (when === "auto")
476
508
  return;
@@ -493,7 +525,7 @@ function parse(args, usage, options, settings = {}) {
493
525
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
494
526
  let parsed;
495
527
  try {
496
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
528
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
497
529
  } catch (error) {
498
530
  const message = parseError(error);
499
531
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -501,7 +533,7 @@ function parse(args, usage, options, settings = {}) {
501
533
  const values = parsed.values;
502
534
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
503
535
  if (values.help === true) {
504
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
536
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
505
537
  throw new HelpShown;
506
538
  }
507
539
  checkChoices(parsed.values, all);
@@ -543,6 +575,18 @@ function listed(options, allowNegative) {
543
575
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
544
576
  }));
545
577
  }
578
+ function withAliases(args, options) {
579
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
580
+ if (named.size === 0)
581
+ return args;
582
+ const separator = args.indexOf("--");
583
+ const own = separator === -1 ? args : args.slice(0, separator);
584
+ return [...own.map((arg) => {
585
+ const at = arg.indexOf("=");
586
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
587
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
588
+ }), ...separator === -1 ? [] : args.slice(separator)];
589
+ }
546
590
  function withBare(args, options) {
547
591
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
548
592
  if (bare.size === 0)
@@ -627,29 +671,9 @@ function nearestOption(message, options, allowNegative) {
627
671
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
628
672
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
629
673
  }
630
- var WHOLE = /^\d+$/;
631
- function wholeNumber(value, name, fallback, min = 1) {
632
- if (value === undefined)
633
- return fallback;
634
- const number = Number(value);
635
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
636
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
637
- return number;
638
- }
639
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
640
- if (path === "-") {
641
- if (process3.stdin.isTTY)
642
- fail(noStdin);
643
- return Bun.stdin.text();
644
- }
645
- const file = Bun.file(path);
646
- if (!await file.exists())
647
- fail(`no file ${path}`);
648
- return file.text();
649
- }
650
674
  // ../kit/src/process.ts
651
675
  import { constants } from "os";
652
- import process4 from "process";
676
+ import process7 from "process";
653
677
  var KILL_GRACE_MS = 2000;
654
678
  function exitCodeOf(code, signal) {
655
679
  if (code !== null)
@@ -669,7 +693,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
669
693
  return;
670
694
  try {
671
695
  if (grouped)
672
- process4.kill(-proc.pid, killing);
696
+ process7.kill(-proc.pid, killing);
673
697
  else
674
698
  proc.kill(killing);
675
699
  } catch {}
@@ -743,7 +767,61 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
743
767
  var RESET_STYLE = `${ESC}[0m`;
744
768
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
745
769
  // ../kit/src/cli.ts
746
- import process5 from "process";
770
+ import { readFileSync, realpathSync } from "fs";
771
+ import { dirname as dirname2, join as join2 } from "path";
772
+ import process9 from "process";
773
+
774
+ // ../kit/src/usage.ts
775
+ import { appendFileSync, mkdirSync } from "fs";
776
+ import { homedir } from "os";
777
+ import { dirname, isAbsolute, join } from "path";
778
+ import process8 from "process";
779
+
780
+ // ../kit/src/logs.ts
781
+ var DAY_MS = 24 * 60 * 60 * 1000;
782
+ var CLI_FOLDER = "kaynooo-cli";
783
+
784
+ // ../kit/src/usage.ts
785
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
786
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
787
+ var LONGEST_NAME = 40;
788
+ var usageError;
789
+ function noteUsageError(message) {
790
+ usageError = message;
791
+ }
792
+ function stateHome(env = process8.env) {
793
+ const dir = env.XDG_STATE_HOME;
794
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
795
+ }
796
+ function usagePath(env = process8.env) {
797
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
798
+ }
799
+ function usageRecorded(env = process8.env) {
800
+ const off = env.KAYNOOO_CLI_NO_USAGE;
801
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
802
+ }
803
+ function flagNames(argv) {
804
+ const end = argv.indexOf("--");
805
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
806
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
807
+ }
808
+ function usageEntry(bin, command, argv, code, now = new Date) {
809
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
810
+ usageError = undefined;
811
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
812
+ }
813
+ function recordUsage(entry, env = process8.env) {
814
+ if (!usageRecorded(env))
815
+ return;
816
+ try {
817
+ const path = usagePath(env);
818
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
819
+ appendFileSync(path, `${JSON.stringify(entry)}
820
+ `, { mode: 384 });
821
+ } catch {}
822
+ }
823
+
824
+ // ../kit/src/cli.ts
747
825
  var LEVEL_OPTIONS = {
748
826
  ...OUTPUT_OPTIONS,
749
827
  help: { type: "boolean", short: "h", description: "show this help" }
@@ -796,7 +874,7 @@ async function expand(scope, words) {
796
874
  }
797
875
  return { ...scope, commands, lazy: [] };
798
876
  }
799
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
877
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
800
878
  const colors = paint(stream);
801
879
  const prefix = path.join(" ");
802
880
  const summary = await resolveSummary(lazySummary);
@@ -823,8 +901,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
823
901
  `);
824
902
  }
825
903
  function printError(prefix, message, hint, cause) {
826
- const colors = paint(process5.stderr);
827
- const styled = takesControlCodes(process5.stderr);
904
+ const colors = paint(process9.stderr);
905
+ const styled = takesControlCodes(process9.stderr);
828
906
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
829
907
  const under = (label, text, tint) => text === undefined ? "" : `
830
908
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -843,6 +921,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
843
921
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
844
922
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
845
923
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
924
+ if (error instanceof UsageError)
925
+ noteUsageError(error.message);
846
926
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
847
927
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
848
928
  return error instanceof Exit ? error.code : 1;
@@ -865,11 +945,11 @@ async function dispatch(level, typed, { version, redact }) {
865
945
  }
866
946
  }
867
947
  if (name === undefined && level.path.length > 1) {
868
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
948
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
869
949
  return 2;
870
950
  }
871
951
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
872
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
952
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
873
953
  return 0;
874
954
  }
875
955
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -985,13 +1065,60 @@ async function printCandidates(found) {
985
1065
  console.log(line);
986
1066
  return 0;
987
1067
  }
988
- async function runCli(cli, argv = process5.argv.slice(2)) {
1068
+ function packageVersion(entry = Bun.main) {
1069
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1070
+ try {
1071
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1072
+ if (typeof version === "string")
1073
+ return version;
1074
+ } catch {}
1075
+ if (dirname2(dir) === dir)
1076
+ return "0.0.0";
1077
+ }
1078
+ }
1079
+ async function runCli(cli, argv = process9.argv.slice(2)) {
1080
+ const version = cli.version ?? packageVersion();
989
1081
  if (argv[0] === COMPLETE)
990
1082
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
991
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
1083
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1084
+ if (cli.usage !== false) {
1085
+ try {
1086
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1087
+ } catch {}
1088
+ }
1089
+ return code;
1090
+ }
1091
+ function commandPath(scope, argv) {
1092
+ const path = [];
1093
+ let level = scope;
1094
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1095
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1096
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1097
+ if (command === undefined)
1098
+ break;
1099
+ path.push(word);
1100
+ if (!("commands" in command))
1101
+ break;
1102
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1103
+ }
1104
+ return path.length === 0 ? undefined : path.join(" ");
1105
+ }
1106
+ // ../kit/src/compose.ts
1107
+ async function captureOutput(argv, { cwd, env } = {}) {
1108
+ const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1109
+ const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1110
+ return { code, stdout, stderr };
1111
+ }
1112
+ async function compose(args, { flags = [], ...options } = {}) {
1113
+ return captureOutput(["docker", "compose", ...flags, ...args], options);
1114
+ }
1115
+ function jsonLines(text) {
1116
+ const trimmed = text.trim();
1117
+ if (trimmed === "")
1118
+ return [];
1119
+ return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1120
+ `).map((line) => JSON.parse(line));
992
1121
  }
993
- // ../kit/src/logs.ts
994
- var DAY_MS = 24 * 60 * 60 * 1000;
995
1122
  // ../kit/src/secrets.ts
996
1123
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
997
1124
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1003,13 +1130,31 @@ function isSecretName(name) {
1003
1130
  var {Glob } = globalThis.Bun;
1004
1131
  var SESSION_FILES = new Glob("*.json");
1005
1132
  var ACCOUNT_DIRS = new Glob("*/sessions");
1006
- // package.json
1007
- var version = "0.9.1";
1008
-
1133
+ // ../kit/src/user-config.ts
1134
+ import { existsSync } from "fs";
1135
+ import { homedir as homedir2 } from "os";
1136
+ import { join as join3 } from "path";
1137
+ import process10 from "process";
1138
+ function configBase(where = {}) {
1139
+ const xdg = where.xdg ?? (where.home === undefined ? process10.env.XDG_CONFIG_HOME : undefined);
1140
+ return xdg !== undefined && xdg !== "" ? xdg : join3(where.home ?? homedir2(), ".config");
1141
+ }
1142
+ function userConfigPath(bin, where = {}) {
1143
+ return join3(configBase(where), "kaynooo-cli", `${bin}.json`);
1144
+ }
1145
+ function userConfigReadPath(bin, legacy = [], where = {}) {
1146
+ const current = userConfigPath(bin, where);
1147
+ if (existsSync(current))
1148
+ return current;
1149
+ const base = configBase(where);
1150
+ return legacy.map((parts) => join3(base, ...parts)).find((path) => existsSync(path)) ?? current;
1151
+ }
1009
1152
  // src/args.ts
1010
1153
  var DEFAULT_ENV = "DATABASE_URL";
1011
- var DEFAULT_LIMIT = 100;
1012
- var HOSTS_NOTE = 'db connects to a local host (localhost, 127.0.0.1, ::1) or a compose service only: any other host is refused (exit 2) unless it is listed under "allowedHosts" in ~/.config/db/config.json.';
1154
+ var DEFAULT_LIMIT = 20;
1155
+ var ALL_LIMIT = 100;
1156
+ var EXITS = [[0, "it ran"], [1, "the database refused it, was unreachable, or the statement would write and was not run"], [2, "a usage error or a host that is not allowed"]];
1157
+ var HOSTS_NOTE = 'db connects to a local host (localhost, 127.0.0.1, ::1) or a compose service only: any other host is refused (exit 2) unless it is listed under "allowedHosts" in ~/.config/kaynooo-cli/db.json.';
1013
1158
  var WRITE_NOTE = "A write runs only when the database actually connected to has a name ending in _test (checked on the server, and a statement that names another database, or uses USE, SET, files or server objects, is not run); any other write is printed for you to run.";
1014
1159
  var connectionOptions = {
1015
1160
  env: { type: "string", short: "e", description: `environment key holding the connection URL (${DEFAULT_ENV}, postgres:// or mysql://), a compose service's host in it reached from here` },
@@ -1017,19 +1162,29 @@ var connectionOptions = {
1017
1162
  container: { type: "string", short: "c", description: "read the running Postgres, MySQL or MariaDB container of this name, in any compose project or none, credentials from its environment" },
1018
1163
  database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" }
1019
1164
  };
1165
+ var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
1166
+ var all = { type: "boolean", description: `show up to ${ALL_LIMIT} rows, the cap before the default was lowered to ${DEFAULT_LIMIT} (-n goes higher)`, conflicts: ["rows"] };
1167
+ function rowLimit(values, fallback = DEFAULT_LIMIT) {
1168
+ return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
1169
+ }
1170
+ var catalogOptions = {
1171
+ rows,
1172
+ all,
1173
+ json: jsonOption()
1174
+ };
1020
1175
  var outputOptions = {
1021
- limit: { type: "string", short: "n", description: `rows shown (${DEFAULT_LIMIT})` },
1176
+ rows,
1177
+ all,
1022
1178
  raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
1023
1179
  json: jsonOption()
1024
1180
  };
1025
1181
 
1026
- // src/guard.ts
1182
+ // src/sql-tokens.ts
1027
1183
  var WORD_START = /[a-z_\P{ASCII}]/iu;
1028
1184
  var WORD_PART = /[\w$\P{ASCII}]/u;
1029
1185
  var SPACE = /\s/;
1030
1186
  var ESCAPE_PREFIX = /e/i;
1031
1187
  var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
1032
- var LOCK_KIND = /^(?:update|share|no|key)$/;
1033
1188
  var DIGITS = /\d/;
1034
1189
  var COMMAND_ENDS = ";";
1035
1190
  var UNCLOSED = "unclosed";
@@ -1037,11 +1192,6 @@ var NUL = "\x00";
1037
1192
  var UNICODE_IDENTIFIER = 'U&"';
1038
1193
  var UNICODE_PREFIX = /u&$/i;
1039
1194
  var LINE_END = /[\r\n]/;
1040
- var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1041
- var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1042
- var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1043
- var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1044
- var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1045
1195
  function tokenize(sql, dialect = "postgres") {
1046
1196
  const tokens = [];
1047
1197
  const isMysql = dialect === "mysql";
@@ -1139,6 +1289,64 @@ function splitStatements(tokens) {
1139
1289
  }
1140
1290
  return statements.filter((statement) => statement.length > 0);
1141
1291
  }
1292
+
1293
+ // src/guard-test.ts
1294
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1295
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1296
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1297
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1298
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1299
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1300
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1301
+ function foreignDatabases(statement, database) {
1302
+ const found = [];
1303
+ for (const [index, token] of statement.entries()) {
1304
+ if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
1305
+ found.push(token.text);
1306
+ }
1307
+ return found;
1308
+ }
1309
+ function definesServerObject(statement, dialect) {
1310
+ if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1311
+ return null;
1312
+ const kind = statement.slice(1).find((token) => !DEFINITION_MODIFIERS.has(token.text))?.text ?? "";
1313
+ if (STORED_CODE.has(kind) && statement[0]?.text !== "drop")
1314
+ return kind;
1315
+ if (statement[0]?.text !== "drop" && statement.some((token) => token.kind === "word" && token.text === "definer"))
1316
+ return "definer";
1317
+ return SERVER_OBJECTS.has(kind) || dialect === "mysql" && kind === "schema" ? kind : null;
1318
+ }
1319
+ function testWriteBlockers(sql, dialect, database) {
1320
+ const statements = splitStatements(tokenize(sql, dialect));
1321
+ const reasons = [];
1322
+ if (statements.length > 1)
1323
+ reasons.push("several statements");
1324
+ for (const statement of statements) {
1325
+ const [first] = statement;
1326
+ const serverObject = definesServerObject(statement, dialect);
1327
+ if (first?.kind !== "word" || !TEST_WRITE_STARTS.has(first.text))
1328
+ reasons.push(`starts with ${first?.text ?? "nothing"}`);
1329
+ if (serverObject !== null)
1330
+ reasons.push(`defines a ${serverObject}`);
1331
+ if (dialect === "mysql")
1332
+ reasons.push(...foreignDatabases(statement, database).map((name) => `names the database ${name}`));
1333
+ for (const [index, token] of statement.entries()) {
1334
+ if (isPunct(token, UNCLOSED) || isPunct(token, NUL) || isPunct(token, UNICODE_IDENTIFIER) || isPunct(token, "\\"))
1335
+ reasons.push("has a quote that never closes, a NUL byte, an escaped identifier or a meta-command");
1336
+ else if (token.kind !== "punct" && (SIDE_EFFECT_FUNCTIONS.test(token.text) && !SEQUENCE_FUNCTIONS.has(token.text) || token.kind === "word" && (FILE_WORDS.has(token.text) || token.text === "federated" || token.text === "connection" && isPunct(statement[index + 1], "="))))
1337
+ reasons.push(`uses ${token.text}`);
1338
+ }
1339
+ }
1340
+ return [...new Set(reasons)];
1341
+ }
1342
+
1343
+ // src/guard.ts
1344
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
1345
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1346
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1347
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1348
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1349
+ var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1142
1350
  var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1143
1351
  function copyReads(statement, index) {
1144
1352
  let depth = 0;
@@ -1204,54 +1412,6 @@ function inspect(sql, dialect = "postgres") {
1204
1412
  }
1205
1413
  return { reasons: [...new Set(reasons)], statements: statements.length };
1206
1414
  }
1207
- var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1208
- var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1209
- var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1210
- var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1211
- var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1212
- var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1213
- var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1214
- function foreignDatabases(statement, database) {
1215
- const found = [];
1216
- for (const [index, token] of statement.entries()) {
1217
- if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
1218
- found.push(token.text);
1219
- }
1220
- return found;
1221
- }
1222
- function definesServerObject(statement, dialect) {
1223
- if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1224
- return null;
1225
- const kind = statement.slice(1).find((token) => !DEFINITION_MODIFIERS.has(token.text))?.text ?? "";
1226
- if (STORED_CODE.has(kind) && statement[0]?.text !== "drop")
1227
- return kind;
1228
- if (statement[0]?.text !== "drop" && statement.some((token) => token.kind === "word" && token.text === "definer"))
1229
- return "definer";
1230
- return SERVER_OBJECTS.has(kind) || dialect === "mysql" && kind === "schema" ? kind : null;
1231
- }
1232
- function testWriteBlockers(sql, dialect, database) {
1233
- const statements = splitStatements(tokenize(sql, dialect));
1234
- const reasons = [];
1235
- if (statements.length > 1)
1236
- reasons.push("several statements");
1237
- for (const statement of statements) {
1238
- const [first] = statement;
1239
- const serverObject = definesServerObject(statement, dialect);
1240
- if (first?.kind !== "word" || !TEST_WRITE_STARTS.has(first.text))
1241
- reasons.push(`starts with ${first?.text ?? "nothing"}`);
1242
- if (serverObject !== null)
1243
- reasons.push(`defines a ${serverObject}`);
1244
- if (dialect === "mysql")
1245
- reasons.push(...foreignDatabases(statement, database).map((name) => `names the database ${name}`));
1246
- for (const [index, token] of statement.entries()) {
1247
- if (isPunct(token, UNCLOSED) || isPunct(token, NUL) || isPunct(token, UNICODE_IDENTIFIER) || isPunct(token, "\\"))
1248
- reasons.push("has a quote that never closes, a NUL byte, an escaped identifier or a meta-command");
1249
- else if (token.kind !== "punct" && (SIDE_EFFECT_FUNCTIONS.test(token.text) && !SEQUENCE_FUNCTIONS.has(token.text) || token.kind === "word" && (FILE_WORDS.has(token.text) || token.text === "federated" || token.text === "connection" && isPunct(statement[index + 1], "="))))
1250
- reasons.push(`uses ${token.text}`);
1251
- }
1252
- }
1253
- return [...new Set(reasons)];
1254
- }
1255
1415
 
1256
1416
  // src/mask.ts
1257
1417
  var MASK = "***";
@@ -1374,8 +1534,7 @@ function render(shown, json) {
1374
1534
 
1375
1535
  // src/run.ts
1376
1536
  import { isIP } from "net";
1377
- import { homedir as homedir2 } from "os";
1378
- import process7 from "process";
1537
+ import process12 from "process";
1379
1538
  var {SQL } = globalThis.Bun;
1380
1539
 
1381
1540
  // src/compose.ts
@@ -1385,13 +1544,6 @@ var POSTGRES_IMAGE = /(?:^|\/)(?:postgres|postgis|timescaledb)[\w.-]*(?::|$)/;
1385
1544
  var MYSQL_IMAGE = /(?:^|\/)(?:mysql|mariadb|percona)[\w.-]*(?::|$)/;
1386
1545
  var LOOPBACK = new Set(["", "0.0.0.0", "::", "127.0.0.1", "::1"]);
1387
1546
  var LEADING_SLASH = /^\//;
1388
- function parsePs(text) {
1389
- const trimmed = text.trim();
1390
- if (trimmed === "")
1391
- return [];
1392
- return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1393
- `).map((line) => JSON.parse(line));
1394
- }
1395
1547
  function envOf(lines) {
1396
1548
  return Object.fromEntries(lines.map((line) => {
1397
1549
  const at = line.indexOf("=");
@@ -1473,12 +1625,12 @@ function stdoutOf(chunks) {
1473
1625
  async function composeServices() {
1474
1626
  let ps;
1475
1627
  try {
1476
- ps = await runCommand(["docker", "compose", "ps", "--format", "json"]);
1628
+ ps = await compose(["ps", "--format", "json"]);
1477
1629
  } catch {
1478
1630
  return [];
1479
1631
  }
1480
1632
  try {
1481
- const rows = ps.code === 0 ? parsePs(stdoutOf(ps.chunks)).filter((row) => row.State === "running" && row.ID !== undefined) : [];
1633
+ const rows = ps.code === 0 ? jsonLines(ps.stdout).filter((row) => row.State === "running" && row.ID !== undefined) : [];
1482
1634
  if (rows.length === 0)
1483
1635
  return [];
1484
1636
  const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
@@ -1544,12 +1696,10 @@ function serviceUrl(service) {
1544
1696
  }
1545
1697
 
1546
1698
  // src/settings.ts
1547
- import { homedir } from "os";
1548
- import { join } from "path";
1549
- function settingsPath(home = homedir()) {
1550
- return join(home, ".config", "db", "config.json");
1699
+ function settingsPath(home) {
1700
+ return userConfigReadPath("db", [["db", "config.json"]], { home });
1551
1701
  }
1552
- async function loadSettings(home = homedir()) {
1702
+ async function loadSettings(home) {
1553
1703
  const path = settingsPath(home);
1554
1704
  const file = Bun.file(path);
1555
1705
  if (!await file.exists())
@@ -1599,7 +1749,7 @@ var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
1599
1749
  function allowsKeyRetrieval(url) {
1600
1750
  try {
1601
1751
  const host = hostOf(new URL(url));
1602
- return isLocal(host) || DOCKER_NETWORK.test(host);
1752
+ return isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host);
1603
1753
  } catch {
1604
1754
  return false;
1605
1755
  }
@@ -1614,7 +1764,7 @@ function serviceNamed(services, host, dialect) {
1614
1764
  fail(`${host} names several services (${aliased.map((candidate) => candidate.name).join(", ")}): pick one with --service`);
1615
1765
  return aliased[0];
1616
1766
  }
1617
- async function reachable(value, home = homedir2()) {
1767
+ async function reachable(value, home) {
1618
1768
  let url;
1619
1769
  try {
1620
1770
  url = new URL(value);
@@ -1635,11 +1785,11 @@ async function reachable(value, home = homedir2()) {
1635
1785
  fail(`${host} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
1636
1786
  return url;
1637
1787
  }
1638
- async function connectionUrl({ env, service, container, database }, home = homedir2()) {
1788
+ async function connectionUrl({ env, service, container, database }, home) {
1639
1789
  if (service !== undefined && container !== undefined)
1640
1790
  fail("--service and --container name two databases: pick one");
1641
1791
  const isNamed = service !== undefined || container !== undefined;
1642
- const value = isNamed ? undefined : process7.env[env ?? DEFAULT_ENV];
1792
+ const value = isNamed ? undefined : process12.env[env ?? DEFAULT_ENV];
1643
1793
  let url;
1644
1794
  if (value !== undefined && value !== "")
1645
1795
  url = await reachable(value, home);
@@ -1784,15 +1934,16 @@ async function closeQuietly(session, url) {
1784
1934
  }
1785
1935
 
1786
1936
  // src/commands/query.ts
1787
- var usage = `db query "<sql>"
1937
+ var usage2 = `db query "<sql>"
1788
1938
 
1789
1939
  Runs one read-only statement (the SQL as an argument, or on stdin) in a READ ONLY transaction that is rolled back, on Postgres, MySQL or MariaDB. A statement that would write is printed for you to run instead, and exits 1 without running.
1790
1940
 
1791
- ${WRITE_NOTE}
1941
+ The SQL is tokenized the way its engine reads it and refused unless it starts with SELECT, WITH, VALUES, TABLE, SHOW, EXPLAIN, DESCRIBE or DESC and uses no INSERT, UPDATE, DELETE, MERGE, INTO, SET or FOR UPDATE anywhere (a write hidden in a CTE is caught), nor a function with side effects (nextval, setval, set_config, pg_terminate_backend, pg_sleep, dblink, sleep, load_file...). Several statements are refused (exit 2) even when each reads.
1942
+ Statements time out after 30 seconds and show at most -n rows (${DEFAULT_LIMIT}, --all for 100), a Postgres select being read through a cursor that stops one row past it. Columns named like emails, phones, tokens, secrets, passwords or hashes show *** unless --raw, and every message is scrubbed of the URL and password.
1792
1943
 
1793
- ${HOSTS_NOTE}
1944
+ ${WRITE_NOTE}
1794
1945
 
1795
- Exits 0 when the statement ran, 1 when the database refused it, was unreachable or the statement would write and was not run, 2 on a usage error or a host that is not allowed.`;
1946
+ ${HOSTS_NOTE}`;
1796
1947
  var options = { ...connectionOptions, ...outputOptions };
1797
1948
  var WRITE_EXIT = 1;
1798
1949
  var NO_SQL = "no SQL given: pass it as an argument or on stdin";
@@ -1814,9 +1965,9 @@ function isWrite(sql) {
1814
1965
  return inspect(sql, "postgres").reasons.length > 0 || inspect(sql, "mysql").reasons.length > 0;
1815
1966
  }
1816
1967
  async function query(args) {
1817
- const parsed = parse(args, usage, options);
1968
+ const parsed = parse(args, usage2, options, { exits: EXITS });
1818
1969
  const { values, positionals } = parsed;
1819
- const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
1970
+ const limit = rowLimit(values);
1820
1971
  const sql = await readSql(positionals);
1821
1972
  let url;
1822
1973
  try {
@@ -1847,9 +1998,37 @@ ${render(shown, false)}`}`);
1847
1998
  return 0;
1848
1999
  }
1849
2000
 
2001
+ // src/commands/explain.ts
2002
+ var usage3 = `db explain "<sql>"
2003
+
2004
+ Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone, never ANALYZE, which would execute the statement. The statement must start with SELECT, WITH, VALUES or TABLE and passes the same read-only guard as a query; EXPLAIN and ANALYZE written by hand are refused.
2005
+
2006
+ ${HOSTS_NOTE}`;
2007
+ var options2 = { ...connectionOptions, json: jsonOption() };
2008
+ var READ_START = /^\s*(?:select|with|values|table)\b/i;
2009
+ var TRAILING_SEMICOLON = /;\s*$/;
2010
+ function explainSql(sql, dialect) {
2011
+ const verdict = inspect(sql, dialect);
2012
+ if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
2013
+ fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
2014
+ return `EXPLAIN ${sql.trim().replace(TRAILING_SEMICOLON, "")}`;
2015
+ }
2016
+ async function explain(args) {
2017
+ const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
2018
+ const sql = await readSql(positionals);
2019
+ const url = await connectionUrl(values);
2020
+ const dialect = dialectOf(new URL(url));
2021
+ const rows = await readRows(url, explainSql(sql, dialect));
2022
+ if (dialect === "postgres" && values.json !== true)
2023
+ console.log(rows.map((row) => String(row["QUERY PLAN"])).join(`
2024
+ `));
2025
+ else
2026
+ console.log(render(shape(rows, rows.length, true), values.json === true));
2027
+ return 0;
2028
+ }
2029
+
1850
2030
  // src/commands/schema.ts
1851
- var options2 = { ...connectionOptions, ...outputOptions };
1852
- var EXITS = "Exits 0 when it listed them, 1 when the database refused or was unreachable, 2 on a usage error or a host that is not allowed.";
2031
+ var options3 = { ...connectionOptions, ...catalogOptions };
1853
2032
  var TABLES = `
1854
2033
  select n.nspname as schema, c.relname as name,
1855
2034
  case c.relkind when 'r' then 'table' when 'p' then 'partitioned' when 'v' then 'view' when 'm' then 'matview' else 'foreign' end as kind,
@@ -1873,6 +2052,30 @@ from information_schema.columns c
1873
2052
  where c.table_name = $1 and ($2::text is null or c.table_schema = $2)
1874
2053
  and c.table_schema not in ('pg_catalog', 'information_schema')
1875
2054
  order by c.table_schema, c.ordinal_position`;
2055
+ var INDEXES = `
2056
+ select i.relname as name, ix.indisunique as is_unique, ix.indisprimary as primary_key, pg_get_indexdef(ix.indexrelid) as definition
2057
+ from pg_index ix
2058
+ join pg_class t on t.oid = ix.indrelid
2059
+ join pg_class i on i.oid = ix.indexrelid
2060
+ join pg_namespace n on n.oid = t.relnamespace
2061
+ where t.relname = $1 and ($2::text is null or n.nspname = $2) and n.nspname not in ('pg_catalog', 'information_schema')
2062
+ order by n.nspname, i.relname`;
2063
+ var FOREIGN_KEYS = `
2064
+ select c.conname as name, pg_get_constraintdef(c.oid) as definition
2065
+ from pg_constraint c
2066
+ join pg_class t on t.oid = c.conrelid
2067
+ join pg_namespace n on n.oid = t.relnamespace
2068
+ where c.contype = 'f' and t.relname = $1 and ($2::text is null or n.nspname = $2) and n.nspname not in ('pg_catalog', 'information_schema')
2069
+ order by n.nspname, c.conname`;
2070
+ var SEARCH = `
2071
+ select table_schema as schema, table_name as "table", null::text as "column", null::text as type
2072
+ from information_schema.tables
2073
+ where table_schema not in ('pg_catalog', 'information_schema') and table_name ilike $1
2074
+ union all
2075
+ select table_schema, table_name, column_name, data_type
2076
+ from information_schema.columns
2077
+ where table_schema not in ('pg_catalog', 'information_schema') and column_name ilike $1
2078
+ order by 1, 2, 3`;
1876
2079
  var MYSQL_SYSTEM = "'mysql', 'information_schema', 'performance_schema', 'sys'";
1877
2080
  var MYSQL_TABLES = `
1878
2081
  select table_schema as \`schema\`, table_name as name,
@@ -1892,11 +2095,30 @@ var MYSQL_COLUMNS = `
1892
2095
  select table_schema as \`schema\`, column_name as name, column_type as type, is_nullable as nullable, column_default as default_value, column_key = 'PRI' as primary_key
1893
2096
  from information_schema.columns
1894
2097
  where table_name = ?`;
2098
+ var MYSQL_SEARCH = `
2099
+ select table_schema as \`schema\`, table_name as \`table\`, null as \`column\`, null as type
2100
+ from information_schema.tables
2101
+ where table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM}) and lower(table_name) like lower(?)
2102
+ union all
2103
+ select table_schema, table_name, column_name, column_type
2104
+ from information_schema.columns
2105
+ where table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM}) and lower(column_name) like lower(?)
2106
+ order by 1, 2, 3`;
2107
+ var MYSQL_INDEXES = `
2108
+ select index_name as name, non_unique = 0 as is_unique, index_name = 'PRIMARY' as primary_key, group_concat(column_name order by seq_in_index) as columns, index_type as type
2109
+ from information_schema.statistics
2110
+ where table_name = ?`;
2111
+ var MYSQL_FOREIGN_KEYS = `
2112
+ select constraint_name as name, group_concat(column_name order by ordinal_position) as columns, concat(referenced_table_schema, '.', referenced_table_name) as references_table, group_concat(referenced_column_name order by ordinal_position) as referenced_columns
2113
+ from information_schema.key_column_usage
2114
+ where referenced_table_name is not null and table_name = ?`;
2115
+ var LIKE_SPECIALS = /[\\%_]/g;
2116
+ var containing = (text) => `%${text.replace(LIKE_SPECIALS, "\\$&")}%`;
1895
2117
  async function show(args, usage, work) {
1896
- const parsed = parse(args, usage, options2);
2118
+ const parsed = parse(args, usage, options3, { exits: EXITS });
1897
2119
  const { values, positionals } = parsed;
1898
2120
  const plans = work(positionals);
1899
- const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
2121
+ const limit = rowLimit(values);
1900
2122
  const url = await connectionUrl(values);
1901
2123
  const { sql, params } = plans[dialectOf(new URL(url))];
1902
2124
  const rows = await readRows(url, sql, params, limit);
@@ -1908,44 +2130,81 @@ async function tables(args) {
1908
2130
 
1909
2131
  Lists the tables, views and materialized views outside the system schemas, with an estimated row count.
1910
2132
 
1911
- ${HOSTS_NOTE}
1912
-
1913
- ${EXITS}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
2133
+ ${HOSTS_NOTE}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
1914
2134
  }
1915
2135
  async function databases(args) {
1916
2136
  return show(args, `db dbs
1917
2137
 
1918
2138
  Lists the databases the connection may open, with their size, marking the one it reads, so --database can pick another.
1919
2139
 
1920
- ${HOSTS_NOTE}
2140
+ ${HOSTS_NOTE}`, () => ({ postgres: { sql: DATABASES, params: [] }, mysql: { sql: MYSQL_DATABASES, params: [] } }));
2141
+ }
2142
+ async function search(args) {
2143
+ return show(args, `db search <text>
2144
+
2145
+ Finds the tables and columns whose name contains the text, case insensitive, outside the system schemas (a table match has no column). Use it to locate where a field lives before describing a table.
1921
2146
 
1922
- ${EXITS}`, () => ({ postgres: { sql: DATABASES, params: [] }, mysql: { sql: MYSQL_DATABASES, params: [] } }));
2147
+ ${HOSTS_NOTE}`, ([text, ...extra]) => {
2148
+ if (text === undefined || extra.length > 0)
2149
+ fail("db search takes one text");
2150
+ const pattern = containing(text);
2151
+ return { postgres: { sql: SEARCH, params: [pattern] }, mysql: { sql: MYSQL_SEARCH, params: [pattern, pattern] } };
2152
+ });
2153
+ }
2154
+ function tableScope(target, extra) {
2155
+ if (target === undefined || extra.length > 0)
2156
+ fail("db describe takes one table name");
2157
+ const [first, second] = target.split(".");
2158
+ return second === undefined ? { table: target, schema: undefined } : { table: second, schema: first };
2159
+ }
2160
+ var MYSQL_ANY_SCHEMA = ` and table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})`;
2161
+ function describePlans(table, schema) {
2162
+ const scope = schema === undefined ? MYSQL_ANY_SCHEMA : " and table_schema = ?";
2163
+ const mysqlParams = schema === undefined ? [table] : [table, schema];
2164
+ const postgresParams = [table, schema ?? null];
2165
+ return {
2166
+ columns: { postgres: { sql: COLUMNS, params: postgresParams }, mysql: { sql: `${MYSQL_COLUMNS}${scope}
2167
+ order by table_schema, ordinal_position`, params: mysqlParams } },
2168
+ indexes: { postgres: { sql: INDEXES, params: postgresParams }, mysql: { sql: `${MYSQL_INDEXES}${scope}
2169
+ group by table_schema, index_name, non_unique, index_type
2170
+ order by table_schema, index_name`, params: mysqlParams } },
2171
+ foreignKeys: { postgres: { sql: FOREIGN_KEYS, params: postgresParams }, mysql: { sql: `${MYSQL_FOREIGN_KEYS}${scope}
2172
+ group by table_schema, constraint_name, referenced_table_schema, referenced_table_name
2173
+ order by table_schema, constraint_name`, params: mysqlParams } }
2174
+ };
1923
2175
  }
1924
2176
  async function describe(args) {
1925
- return show(args, `db describe <table>
2177
+ const usage = `db describe <table>
2178
+
2179
+ Lists a table's columns with type, nullability, default and primary key, then its indexes and foreign keys. Takes \`schema.table\` to tell apart tables of the same name (the database, on MySQL).
1926
2180
 
1927
- Lists a table's columns with type, nullability, default and primary key. Takes \`schema.table\` to tell apart tables of the same name (the database, on MySQL).
2181
+ ${HOSTS_NOTE}`;
2182
+ const { values, positionals: [target, ...extra] } = parse(args, usage, options3, { exits: EXITS });
2183
+ const { table, schema } = tableScope(target, extra);
2184
+ const plans = describePlans(table, schema);
2185
+ const limit = rowLimit(values);
2186
+ const url = await connectionUrl(values);
2187
+ const dialect = dialectOf(new URL(url));
2188
+ const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap);
2189
+ const columns = shape(await ask(plans.columns, limit), limit, true, false);
2190
+ const indexes = await ask(plans.indexes);
2191
+ const foreignKeys = await ask(plans.foreignKeys);
2192
+ if (values.json === true)
2193
+ console.log(JSON.stringify({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue, 2));
2194
+ else
2195
+ console.log(`${render(columns, false)}
1928
2196
 
1929
- ${HOSTS_NOTE}
2197
+ indexes
2198
+ ${render(shape(indexes, indexes.length, true), false)}
1930
2199
 
1931
- ${EXITS}`, ([target, ...extra]) => {
1932
- if (target === undefined || extra.length > 0)
1933
- fail("db describe takes one table name");
1934
- const [first, second] = target.split(".");
1935
- const table = second ?? first;
1936
- const mysqlScope = second === undefined ? ` and table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})` : " and table_schema = ?";
1937
- return {
1938
- postgres: { sql: COLUMNS, params: second === undefined ? [first, null] : [second, first] },
1939
- mysql: { sql: `${MYSQL_COLUMNS}${mysqlScope}
1940
- order by table_schema, ordinal_position`, params: second === undefined ? [table] : [table, first] }
1941
- };
1942
- });
2200
+ foreign keys
2201
+ ${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
2202
+ return 0;
1943
2203
  }
1944
2204
 
1945
2205
  // src/commands/table.ts
1946
2206
  var SAMPLE_LIMIT = 5;
1947
2207
  var NAME = /^[A-Z_][\w$]*(?:\.[A-Z_][\w$]*)?$/i;
1948
- var EXITS2 = "Exits 0 when it ran, 1 when the database refused or was unreachable, 2 on a usage error or a host that is not allowed.";
1949
2208
  function quotedTable(target, dialect) {
1950
2209
  if (!NAME.test(target))
1951
2210
  fail(`${target} is not a table name: use name or schema.name`);
@@ -1963,14 +2222,14 @@ var where = { type: "string", short: "w", description: "only the rows matching t
1963
2222
  var sampleOptions = { ...connectionOptions, ...outputOptions, where };
1964
2223
  var countOptions = { ...connectionOptions, json: outputOptions.json, where };
1965
2224
  async function run(args, usage, options, build) {
1966
- const parsed = parse(args, usage, options);
2225
+ const parsed = parse(args, usage, options, { exits: EXITS });
1967
2226
  const { values, positionals } = parsed;
1968
2227
  const [target, ...extra] = positionals;
1969
2228
  if (target === undefined || extra.length > 0)
1970
2229
  fail("give one table name");
1971
2230
  const url = await connectionUrl(values);
1972
2231
  const dialect = dialectOf(new URL(url));
1973
- const limit = wholeNumber(values.limit, "limit", SAMPLE_LIMIT, 0);
2232
+ const limit = rowLimit(values, SAMPLE_LIMIT);
1974
2233
  const sql = build(target, dialect, { limit, where: values.where });
1975
2234
  const verdict = inspect(sql, dialect);
1976
2235
  if (verdict.reasons.length > 0 || verdict.statements > 1)
@@ -1979,35 +2238,32 @@ async function run(args, usage, options, build) {
1979
2238
  return 0;
1980
2239
  }
1981
2240
  async function sample(args) {
1982
- return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}] [--where <sql>]
2241
+ return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}|--all] [--where <sql>]
1983
2242
 
1984
2243
  Prints a few rows of a table (\`schema.table\` to pick a schema, the name is case sensitive on Postgres), sensitive columns masked as in a query.
1985
2244
 
1986
- ${HOSTS_NOTE}
1987
-
1988
- ${EXITS2}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
2245
+ ${HOSTS_NOTE}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
1989
2246
  }
1990
2247
  async function count(args) {
1991
2248
  return run(args, `db count <table> [--where <sql>]
1992
2249
 
1993
2250
  Prints the number of rows of a table (the name is case sensitive on Postgres), or of those matching a condition.
1994
2251
 
1995
- ${HOSTS_NOTE}
1996
-
1997
- ${EXITS2}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
2252
+ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
1998
2253
  }
1999
2254
 
2000
2255
  // src/cli.ts
2001
- process8.exitCode = await runCli({
2256
+ process13.exitCode = await runCli({
2002
2257
  name: "db",
2003
- version,
2004
2258
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2005
2259
  replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
2006
- examples: ['db "select count(*) from users"', ['db -c booki-db-1 "select count(*) from users"', "a container outside the compose project"], ["db describe users", "the columns of a table"]],
2260
+ examples: ['db "select count(*) from users"', ['db -c booki-db-1 "select count(*) from users"', "a container outside the compose project"], ["db describe users", "the columns, indexes and foreign keys of a table"], ["db search email", "where a field lives"], [`db explain "select * from users where email = 'a'"`, "the plan, nothing executed"]],
2007
2261
  commands: {
2008
2262
  query: { run: query, summary: 'run one read-only statement (the default: db "<sql>"), a write runs on a _test database and is printed otherwise' },
2009
2263
  tables: { run: tables, summary: "list tables and views with an estimated row count" },
2010
- describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key" },
2264
+ describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
2265
+ search: { run: search, summary: "find the tables and columns whose name contains a text" },
2266
+ explain: { run: explain, summary: "the plan of one read without running it (EXPLAIN, never ANALYZE)" },
2011
2267
  sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
2012
2268
  count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
2013
2269
  dbs: { run: databases, summary: "databases the connection may open, with their size" }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-db",
3
3
  "type": "module",
4
- "version": "0.9.1",
4
+ "version": "0.10.0",
5
5
  "description": "db: run read-only SQL against Postgres, MySQL and MariaDB from the terminal without ever showing the connection credentials.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -28,6 +28,6 @@
28
28
  "db": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.19.0"
31
+ "@kaynooo/cli-kit": "0.20.0"
32
32
  }
33
33
  }