@kaynooo/cli-db 0.9.2 → 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 +282 -108
  3. package/package.json +1 -1
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 process11 from "process";
6
-
5
+ import process13 from "process";
7
6
  // ../kit/src/args.ts
8
- import process5 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)));
@@ -356,24 +355,30 @@ function narrow(rows, widths, limit) {
356
355
  }
357
356
 
358
357
  // ../kit/src/help.ts
359
- import process3 from "process";
358
+ import process4 from "process";
360
359
  var OPTIONAL = /\[[^\]]+\]/g;
361
360
  var USAGE_PREFIX = /^usage:\s*/i;
362
361
  var FULL_STOP = /\.$/;
363
- function usageLine(usage, colors = paint(process3.stdout)) {
362
+ function usageLine(usage, colors = paint(process4.stdout)) {
364
363
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
365
364
  }
366
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
367
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
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(`
368
367
  `);
369
368
  }
370
- function replacesRows(replaces, colors = paint(process3.stdout)) {
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)) {
371
376
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
372
377
  }
373
- function wantsHelpJson(env = process3.env) {
378
+ function wantsHelpJson(env = process4.env) {
374
379
  return env.KIT_HELP === "json";
375
380
  }
376
- function description(usage, { examples = [], replaces } = {}) {
381
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
377
382
  const lines = usage.replace(USAGE_PREFIX, "").split(`
378
383
  `);
379
384
  const first = lines[0];
@@ -384,15 +389,17 @@ function description(usage, { examples = [], replaces } = {}) {
384
389
  synopsis: colon === -1 ? first : first.slice(0, colon),
385
390
  summary: colon === -1 ? fallback : first.slice(colon + 2),
386
391
  ...replaces === undefined ? {} : { replaces },
387
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
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 } })) }
388
395
  };
389
396
  }
390
- function exampleRows(examples, colors = paint(process3.stdout)) {
397
+ function exampleRows(examples, colors = paint(process4.stdout)) {
391
398
  if (examples.length === 0)
392
399
  return [];
393
400
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
394
401
  }
395
- function optionRows(options, colors = paint(process3.stdout)) {
402
+ function optionRows(options, colors = paint(process4.stdout)) {
396
403
  const rows = Object.entries(options).map(([name, option]) => {
397
404
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
398
405
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -424,7 +431,7 @@ function closest(name, names) {
424
431
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
425
432
  }
426
433
  // ../kit/src/input.ts
427
- import process4 from "process";
434
+ import process5 from "process";
428
435
  var WHOLE = /^\d+$/;
429
436
  function wholeNumber(value, name, fallback, min = 1) {
430
437
  if (value === undefined)
@@ -436,7 +443,7 @@ function wholeNumber(value, name, fallback, min = 1) {
436
443
  }
437
444
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
438
445
  if (path === "-") {
439
- if (process4.stdin.isTTY)
446
+ if (process5.stdin.isTTY)
440
447
  fail(noStdin);
441
448
  return Bun.stdin.text();
442
449
  }
@@ -495,7 +502,7 @@ var OUTPUT_OPTIONS = {
495
502
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
496
503
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
497
504
  };
498
- function applyOutput(color, plain, env = process5.env) {
505
+ function applyOutput(color, plain, env = process6.env) {
499
506
  const when = plain === true ? "never" : color ?? "auto";
500
507
  if (when === "auto")
501
508
  return;
@@ -518,7 +525,7 @@ function parse(args, usage, options, settings = {}) {
518
525
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
519
526
  let parsed;
520
527
  try {
521
- 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 });
522
529
  } catch (error) {
523
530
  const message = parseError(error);
524
531
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -526,7 +533,7 @@ function parse(args, usage, options, settings = {}) {
526
533
  const values = parsed.values;
527
534
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
528
535
  if (values.help === true) {
529
- 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));
530
537
  throw new HelpShown;
531
538
  }
532
539
  checkChoices(parsed.values, all);
@@ -568,6 +575,18 @@ function listed(options, allowNegative) {
568
575
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
569
576
  }));
570
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
+ }
571
590
  function withBare(args, options) {
572
591
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
573
592
  if (bare.size === 0)
@@ -654,7 +673,7 @@ function nearestOption(message, options, allowNegative) {
654
673
  }
655
674
  // ../kit/src/process.ts
656
675
  import { constants } from "os";
657
- import process6 from "process";
676
+ import process7 from "process";
658
677
  var KILL_GRACE_MS = 2000;
659
678
  function exitCodeOf(code, signal) {
660
679
  if (code !== null)
@@ -674,7 +693,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
674
693
  return;
675
694
  try {
676
695
  if (grouped)
677
- process6.kill(-proc.pid, killing);
696
+ process7.kill(-proc.pid, killing);
678
697
  else
679
698
  proc.kill(killing);
680
699
  } catch {}
@@ -748,13 +767,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
748
767
  var RESET_STYLE = `${ESC}[0m`;
749
768
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
750
769
  // ../kit/src/cli.ts
751
- import process8 from "process";
770
+ import { readFileSync, realpathSync } from "fs";
771
+ import { dirname as dirname2, join as join2 } from "path";
772
+ import process9 from "process";
752
773
 
753
774
  // ../kit/src/usage.ts
754
775
  import { appendFileSync, mkdirSync } from "fs";
755
776
  import { homedir } from "os";
756
777
  import { dirname, isAbsolute, join } from "path";
757
- import process7 from "process";
778
+ import process8 from "process";
758
779
 
759
780
  // ../kit/src/logs.ts
760
781
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -768,14 +789,14 @@ var usageError;
768
789
  function noteUsageError(message) {
769
790
  usageError = message;
770
791
  }
771
- function stateHome(env = process7.env) {
792
+ function stateHome(env = process8.env) {
772
793
  const dir = env.XDG_STATE_HOME;
773
794
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
774
795
  }
775
- function usagePath(env = process7.env) {
796
+ function usagePath(env = process8.env) {
776
797
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
777
798
  }
778
- function usageRecorded(env = process7.env) {
799
+ function usageRecorded(env = process8.env) {
779
800
  const off = env.KAYNOOO_CLI_NO_USAGE;
780
801
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
781
802
  }
@@ -789,7 +810,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
789
810
  usageError = undefined;
790
811
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
791
812
  }
792
- function recordUsage(entry, env = process7.env) {
813
+ function recordUsage(entry, env = process8.env) {
793
814
  if (!usageRecorded(env))
794
815
  return;
795
816
  try {
@@ -880,8 +901,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
880
901
  `);
881
902
  }
882
903
  function printError(prefix, message, hint, cause) {
883
- const colors = paint(process8.stderr);
884
- const styled = takesControlCodes(process8.stderr);
904
+ const colors = paint(process9.stderr);
905
+ const styled = takesControlCodes(process9.stderr);
885
906
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
886
907
  const under = (label, text, tint) => text === undefined ? "" : `
887
908
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -924,11 +945,11 @@ async function dispatch(level, typed, { version, redact }) {
924
945
  }
925
946
  }
926
947
  if (name === undefined && level.path.length > 1) {
927
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
948
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stderr));
928
949
  return 2;
929
950
  }
930
951
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
931
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
952
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process9.stdout));
932
953
  return 0;
933
954
  }
934
955
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1044,10 +1065,22 @@ async function printCandidates(found) {
1044
1065
  console.log(line);
1045
1066
  return 0;
1046
1067
  }
1047
- async function runCli(cli, argv = process8.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();
1048
1081
  if (argv[0] === COMPLETE)
1049
1082
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1050
- const code = await 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 });
1051
1084
  if (cli.usage !== false) {
1052
1085
  try {
1053
1086
  recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
@@ -1070,6 +1103,22 @@ function commandPath(scope, argv) {
1070
1103
  }
1071
1104
  return path.length === 0 ? undefined : path.join(" ");
1072
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));
1121
+ }
1073
1122
  // ../kit/src/secrets.ts
1074
1123
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1075
1124
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1081,13 +1130,31 @@ function isSecretName(name) {
1081
1130
  var {Glob } = globalThis.Bun;
1082
1131
  var SESSION_FILES = new Glob("*.json");
1083
1132
  var ACCOUNT_DIRS = new Glob("*/sessions");
1084
- // package.json
1085
- var version = "0.9.2";
1086
-
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
+ }
1087
1152
  // src/args.ts
1088
1153
  var DEFAULT_ENV = "DATABASE_URL";
1089
- var DEFAULT_LIMIT = 100;
1090
- 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.';
1091
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.";
1092
1159
  var connectionOptions = {
1093
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` },
@@ -1095,8 +1162,19 @@ var connectionOptions = {
1095
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" },
1096
1163
  database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" }
1097
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
+ };
1098
1175
  var outputOptions = {
1099
- limit: { type: "string", short: "n", description: `rows shown (${DEFAULT_LIMIT})` },
1176
+ rows,
1177
+ all,
1100
1178
  raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
1101
1179
  json: jsonOption()
1102
1180
  };
@@ -1456,8 +1534,7 @@ function render(shown, json) {
1456
1534
 
1457
1535
  // src/run.ts
1458
1536
  import { isIP } from "net";
1459
- import { homedir as homedir3 } from "os";
1460
- import process10 from "process";
1537
+ import process12 from "process";
1461
1538
  var {SQL } = globalThis.Bun;
1462
1539
 
1463
1540
  // src/compose.ts
@@ -1467,13 +1544,6 @@ var POSTGRES_IMAGE = /(?:^|\/)(?:postgres|postgis|timescaledb)[\w.-]*(?::|$)/;
1467
1544
  var MYSQL_IMAGE = /(?:^|\/)(?:mysql|mariadb|percona)[\w.-]*(?::|$)/;
1468
1545
  var LOOPBACK = new Set(["", "0.0.0.0", "::", "127.0.0.1", "::1"]);
1469
1546
  var LEADING_SLASH = /^\//;
1470
- function parsePs(text) {
1471
- const trimmed = text.trim();
1472
- if (trimmed === "")
1473
- return [];
1474
- return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1475
- `).map((line) => JSON.parse(line));
1476
- }
1477
1547
  function envOf(lines) {
1478
1548
  return Object.fromEntries(lines.map((line) => {
1479
1549
  const at = line.indexOf("=");
@@ -1555,12 +1625,12 @@ function stdoutOf(chunks) {
1555
1625
  async function composeServices() {
1556
1626
  let ps;
1557
1627
  try {
1558
- ps = await runCommand(["docker", "compose", "ps", "--format", "json"]);
1628
+ ps = await compose(["ps", "--format", "json"]);
1559
1629
  } catch {
1560
1630
  return [];
1561
1631
  }
1562
1632
  try {
1563
- 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) : [];
1564
1634
  if (rows.length === 0)
1565
1635
  return [];
1566
1636
  const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
@@ -1626,12 +1696,10 @@ function serviceUrl(service) {
1626
1696
  }
1627
1697
 
1628
1698
  // src/settings.ts
1629
- import { homedir as homedir2 } from "os";
1630
- import { join as join2 } from "path";
1631
- function settingsPath(home = homedir2()) {
1632
- return join2(home, ".config", "db", "config.json");
1699
+ function settingsPath(home) {
1700
+ return userConfigReadPath("db", [["db", "config.json"]], { home });
1633
1701
  }
1634
- async function loadSettings(home = homedir2()) {
1702
+ async function loadSettings(home) {
1635
1703
  const path = settingsPath(home);
1636
1704
  const file = Bun.file(path);
1637
1705
  if (!await file.exists())
@@ -1681,7 +1749,7 @@ var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
1681
1749
  function allowsKeyRetrieval(url) {
1682
1750
  try {
1683
1751
  const host = hostOf(new URL(url));
1684
- return isLocal(host) || DOCKER_NETWORK.test(host);
1752
+ return isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host);
1685
1753
  } catch {
1686
1754
  return false;
1687
1755
  }
@@ -1696,7 +1764,7 @@ function serviceNamed(services, host, dialect) {
1696
1764
  fail(`${host} names several services (${aliased.map((candidate) => candidate.name).join(", ")}): pick one with --service`);
1697
1765
  return aliased[0];
1698
1766
  }
1699
- async function reachable(value, home = homedir3()) {
1767
+ async function reachable(value, home) {
1700
1768
  let url;
1701
1769
  try {
1702
1770
  url = new URL(value);
@@ -1717,11 +1785,11 @@ async function reachable(value, home = homedir3()) {
1717
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`);
1718
1786
  return url;
1719
1787
  }
1720
- async function connectionUrl({ env, service, container, database }, home = homedir3()) {
1788
+ async function connectionUrl({ env, service, container, database }, home) {
1721
1789
  if (service !== undefined && container !== undefined)
1722
1790
  fail("--service and --container name two databases: pick one");
1723
1791
  const isNamed = service !== undefined || container !== undefined;
1724
- const value = isNamed ? undefined : process10.env[env ?? DEFAULT_ENV];
1792
+ const value = isNamed ? undefined : process12.env[env ?? DEFAULT_ENV];
1725
1793
  let url;
1726
1794
  if (value !== undefined && value !== "")
1727
1795
  url = await reachable(value, home);
@@ -1870,11 +1938,12 @@ var usage2 = `db query "<sql>"
1870
1938
 
1871
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.
1872
1940
 
1873
- ${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.
1874
1943
 
1875
- ${HOSTS_NOTE}
1944
+ ${WRITE_NOTE}
1876
1945
 
1877
- 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}`;
1878
1947
  var options = { ...connectionOptions, ...outputOptions };
1879
1948
  var WRITE_EXIT = 1;
1880
1949
  var NO_SQL = "no SQL given: pass it as an argument or on stdin";
@@ -1896,9 +1965,9 @@ function isWrite(sql) {
1896
1965
  return inspect(sql, "postgres").reasons.length > 0 || inspect(sql, "mysql").reasons.length > 0;
1897
1966
  }
1898
1967
  async function query(args) {
1899
- const parsed = parse(args, usage2, options);
1968
+ const parsed = parse(args, usage2, options, { exits: EXITS });
1900
1969
  const { values, positionals } = parsed;
1901
- const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
1970
+ const limit = rowLimit(values);
1902
1971
  const sql = await readSql(positionals);
1903
1972
  let url;
1904
1973
  try {
@@ -1929,9 +1998,37 @@ ${render(shown, false)}`}`);
1929
1998
  return 0;
1930
1999
  }
1931
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
+
1932
2030
  // src/commands/schema.ts
1933
- var options2 = { ...connectionOptions, ...outputOptions };
1934
- 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 };
1935
2032
  var TABLES = `
1936
2033
  select n.nspname as schema, c.relname as name,
1937
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,
@@ -1955,6 +2052,30 @@ from information_schema.columns c
1955
2052
  where c.table_name = $1 and ($2::text is null or c.table_schema = $2)
1956
2053
  and c.table_schema not in ('pg_catalog', 'information_schema')
1957
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`;
1958
2079
  var MYSQL_SYSTEM = "'mysql', 'information_schema', 'performance_schema', 'sys'";
1959
2080
  var MYSQL_TABLES = `
1960
2081
  select table_schema as \`schema\`, table_name as name,
@@ -1974,11 +2095,30 @@ var MYSQL_COLUMNS = `
1974
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
1975
2096
  from information_schema.columns
1976
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, "\\$&")}%`;
1977
2117
  async function show(args, usage, work) {
1978
- const parsed = parse(args, usage, options2);
2118
+ const parsed = parse(args, usage, options3, { exits: EXITS });
1979
2119
  const { values, positionals } = parsed;
1980
2120
  const plans = work(positionals);
1981
- const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
2121
+ const limit = rowLimit(values);
1982
2122
  const url = await connectionUrl(values);
1983
2123
  const { sql, params } = plans[dialectOf(new URL(url))];
1984
2124
  const rows = await readRows(url, sql, params, limit);
@@ -1990,44 +2130,81 @@ async function tables(args) {
1990
2130
 
1991
2131
  Lists the tables, views and materialized views outside the system schemas, with an estimated row count.
1992
2132
 
1993
- ${HOSTS_NOTE}
1994
-
1995
- ${EXITS}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
2133
+ ${HOSTS_NOTE}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
1996
2134
  }
1997
2135
  async function databases(args) {
1998
2136
  return show(args, `db dbs
1999
2137
 
2000
2138
  Lists the databases the connection may open, with their size, marking the one it reads, so --database can pick another.
2001
2139
 
2002
- ${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.
2003
2146
 
2004
- ${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
+ };
2005
2175
  }
2006
2176
  async function describe(args) {
2007
- 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).
2008
2180
 
2009
- 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)}
2010
2196
 
2011
- ${HOSTS_NOTE}
2197
+ indexes
2198
+ ${render(shape(indexes, indexes.length, true), false)}
2012
2199
 
2013
- ${EXITS}`, ([target, ...extra]) => {
2014
- if (target === undefined || extra.length > 0)
2015
- fail("db describe takes one table name");
2016
- const [first, second] = target.split(".");
2017
- const table = second ?? first;
2018
- const mysqlScope = second === undefined ? ` and table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})` : " and table_schema = ?";
2019
- return {
2020
- postgres: { sql: COLUMNS, params: second === undefined ? [first, null] : [second, first] },
2021
- mysql: { sql: `${MYSQL_COLUMNS}${mysqlScope}
2022
- order by table_schema, ordinal_position`, params: second === undefined ? [table] : [table, first] }
2023
- };
2024
- });
2200
+ foreign keys
2201
+ ${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
2202
+ return 0;
2025
2203
  }
2026
2204
 
2027
2205
  // src/commands/table.ts
2028
2206
  var SAMPLE_LIMIT = 5;
2029
2207
  var NAME = /^[A-Z_][\w$]*(?:\.[A-Z_][\w$]*)?$/i;
2030
- 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.";
2031
2208
  function quotedTable(target, dialect) {
2032
2209
  if (!NAME.test(target))
2033
2210
  fail(`${target} is not a table name: use name or schema.name`);
@@ -2045,14 +2222,14 @@ var where = { type: "string", short: "w", description: "only the rows matching t
2045
2222
  var sampleOptions = { ...connectionOptions, ...outputOptions, where };
2046
2223
  var countOptions = { ...connectionOptions, json: outputOptions.json, where };
2047
2224
  async function run(args, usage, options, build) {
2048
- const parsed = parse(args, usage, options);
2225
+ const parsed = parse(args, usage, options, { exits: EXITS });
2049
2226
  const { values, positionals } = parsed;
2050
2227
  const [target, ...extra] = positionals;
2051
2228
  if (target === undefined || extra.length > 0)
2052
2229
  fail("give one table name");
2053
2230
  const url = await connectionUrl(values);
2054
2231
  const dialect = dialectOf(new URL(url));
2055
- const limit = wholeNumber(values.limit, "limit", SAMPLE_LIMIT, 0);
2232
+ const limit = rowLimit(values, SAMPLE_LIMIT);
2056
2233
  const sql = build(target, dialect, { limit, where: values.where });
2057
2234
  const verdict = inspect(sql, dialect);
2058
2235
  if (verdict.reasons.length > 0 || verdict.statements > 1)
@@ -2061,35 +2238,32 @@ async function run(args, usage, options, build) {
2061
2238
  return 0;
2062
2239
  }
2063
2240
  async function sample(args) {
2064
- return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}] [--where <sql>]
2241
+ return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}|--all] [--where <sql>]
2065
2242
 
2066
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.
2067
2244
 
2068
- ${HOSTS_NOTE}
2069
-
2070
- ${EXITS2}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
2245
+ ${HOSTS_NOTE}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
2071
2246
  }
2072
2247
  async function count(args) {
2073
2248
  return run(args, `db count <table> [--where <sql>]
2074
2249
 
2075
2250
  Prints the number of rows of a table (the name is case sensitive on Postgres), or of those matching a condition.
2076
2251
 
2077
- ${HOSTS_NOTE}
2078
-
2079
- ${EXITS2}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
2252
+ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
2080
2253
  }
2081
2254
 
2082
2255
  // src/cli.ts
2083
- process11.exitCode = await runCli({
2256
+ process13.exitCode = await runCli({
2084
2257
  name: "db",
2085
- version,
2086
2258
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2087
2259
  replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
2088
- 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"]],
2089
2261
  commands: {
2090
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' },
2091
2263
  tables: { run: tables, summary: "list tables and views with an estimated row count" },
2092
- 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)" },
2093
2267
  sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
2094
2268
  count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
2095
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.2",
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",