@kaynooo/cli-db 0.12.0 → 0.13.1

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 +4 -4
  2. package/dist/cli.js +326 -108
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -26,15 +26,15 @@ bun install -g @kaynooo/cli-db
26
26
  | `db sample <table>` | a few rows of a table (`-n`, `--where`), sensitive columns masked; `db count <table>` the number of rows |
27
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
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) |
29
+ | `db explain "<sql>"` | the plan of one read without running it: `EXPLAIN` alone through the read-only guard (a statement not starting with SELECT, WITH, VALUES or TABLE, and a hand-written EXPLAIN or ANALYZE, are refused); `--analyze` runs the read to time it, inside the same rolled-back `READ ONLY` transaction (`EXPLAIN ANALYZE` on Postgres and MySQL 8.0.18+, `ANALYZE` on MariaDB, refused on an older MySQL) |
30
30
  | `db dbs` | databases the connection may open, with their size, the one read marked `current` |
31
31
 
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.
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 }`, `--format tsv|csv|vertical` prints tab-separated values (tabs, newlines and backslashes escaped), RFC 4180 CSV or one `column | value` block per row, cells never truncated and the notes on stderr, `--timeout <duration>` (`500ms`, `30s`, `2m`; 30s) replaces the statement timeout, `-e <KEY>`, `-s <service>`, `-c <container>` and `-d <database>` pick the connection.
33
33
 
34
34
  ## Safety
35
35
 
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.
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
+ - 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'` (`--timeout` changes it) 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.
37
+ - MySQL and MariaDB: the statement runs in `START TRANSACTION READ ONLY` on one reserved connection, under a 30 second statement timeout (`--timeout` changes it) (`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.
38
38
  - A Postgres select is read through a cursor that stops at one row past `-n`, so a huge table is never loaded whole.
39
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
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.
package/dist/cli.js CHANGED
@@ -2,13 +2,14 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process16 from "process";
5
+ import process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // ../kit/src/format.ts
11
11
  import process7 from "process";
12
+
12
13
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
13
14
  var N = new Map;
14
15
  var Nt = /\s+\S*$/;
@@ -26,6 +27,7 @@ function ko(t, e, r = "...") {
26
27
  }
27
28
  var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
28
29
  var z = new Map;
30
+
29
31
  // ../kit/src/mode.ts
30
32
  import process2 from "process";
31
33
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -71,7 +73,7 @@ function C(r, e = globalThis.process?.env ?? {}) {
71
73
  return false;
72
74
  return r?.isTTY === true;
73
75
  }
74
- function f2(r, e = []) {
76
+ function f(r, e = []) {
75
77
  let l = "", n = "";
76
78
  for (let t = 0, i = e.length;t < i; t++)
77
79
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
@@ -81,7 +83,7 @@ function f2(r, e = []) {
81
83
  if (Array.isArray(a)) {
82
84
  let s = g.get(i);
83
85
  if (s === undefined)
84
- s = f2(r, [...e, a]), g.set(i, s);
86
+ s = f(r, [...e, a]), g.set(i, s);
85
87
  return s;
86
88
  }
87
89
  if (typeof a === "function")
@@ -90,20 +92,20 @@ function f2(r, e = []) {
90
92
  if (u === undefined) {
91
93
  if (g.size >= 64)
92
94
  g.clear();
93
- u = f2(r, [...e, a(...s)]), g.set(y, u);
95
+ u = f(r, [...e, a(...s)]), g.set(y, u);
94
96
  }
95
97
  return u;
96
98
  };
97
99
  throw Error(`Unknown style: ${String(i)}`);
98
100
  } });
99
101
  }
100
- function Fe2(r = {}) {
101
- return f2(r);
102
+ function Fe(r = {}) {
103
+ return f(r);
102
104
  }
103
- var o2 = Fe2();
105
+ var o = Fe();
104
106
 
105
107
  // ../kit/src/theme.ts
106
- import { existsSync as existsSync3, readFileSync, statSync } from "fs";
108
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
107
109
  import { homedir as homedir2 } from "os";
108
110
  import { join as join3, resolve as resolve2 } from "path";
109
111
  import process5 from "process";
@@ -124,7 +126,7 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
124
126
  }
125
127
 
126
128
  // ../kit/src/user-config.ts
127
- import { existsSync as existsSync2 } from "fs";
129
+ import { existsSync as existsSync2, readFileSync } from "fs";
128
130
  import { homedir } from "os";
129
131
  import { join as join2 } from "path";
130
132
  import process4 from "process";
@@ -208,7 +210,7 @@ function readThemeFile(path, warn) {
208
210
  warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
209
211
  return;
210
212
  }
211
- const parsed = JSON.parse(readFileSync(path, "utf8"));
213
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
212
214
  if (isRecord(parsed))
213
215
  return parsed;
214
216
  warn(`${path} is not a JSON object, theme ignored`);
@@ -330,7 +332,7 @@ function takesControlCodes(stream, env = process6.env) {
330
332
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
331
333
  }
332
334
  function paint(stream, env = process6.env) {
333
- return Fe2({ stream: { isTTY: takesControlCodes(stream, env) }, env });
335
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
334
336
  }
335
337
  function marked(mark, text, stream, detail, env = process6.env) {
336
338
  const colors = paint(stream, env);
@@ -344,6 +346,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
344
346
  function warn(text, detail) {
345
347
  console.error(marked("warn", text, process6.stderr, detail));
346
348
  }
349
+ function problem(text, detail) {
350
+ console.error(marked("problem", text, process6.stderr, detail));
351
+ }
347
352
  var STATUS_WORDS = {
348
353
  passed: ["passed", "success", "succeeded", "ok"],
349
354
  failed: ["failed", "failure", "error", "errored"],
@@ -354,6 +359,23 @@ var STATUS_WORDS = {
354
359
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
355
360
 
356
361
  // ../kit/src/format.ts
362
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
363
+ function formatSeconds(total) {
364
+ let rest = Math.max(0, Math.round(total));
365
+ const amounts = UNITS.map(([unit, size]) => {
366
+ const amount = Math.floor(rest / size);
367
+ rest -= amount * size;
368
+ return `${amount}${unit}`;
369
+ });
370
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
371
+ if (first === -1)
372
+ return "0s";
373
+ const next = amounts[first + 1];
374
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
375
+ }
376
+ function formatDuration(ms) {
377
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
378
+ }
357
379
  function upTo(text, separator) {
358
380
  const end = text.indexOf(separator);
359
381
  return end === -1 ? text : text.slice(0, end);
@@ -411,24 +433,20 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
411
433
 
412
434
  // ../kit/src/help.ts
413
435
  import process8 from "process";
414
- var OPTIONAL = /\[[^\]]+\]/g;
436
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
415
437
  var USAGE_PREFIX = /^usage:\s*/i;
416
438
  var FULL_STOP = /\.$/;
417
439
  function usageLine(usage, colors = paint(process8.stdout)) {
418
440
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
419
441
  }
420
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
421
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
442
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
443
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
422
444
  `);
423
445
  }
424
446
  function exitRows(exits, colors = paint(process8.stdout)) {
425
447
  if (exits.length === 0)
426
448
  return [];
427
- const width = Math.max(...exits.map(([code]) => String(code).length));
428
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
429
- }
430
- function replacesRows(replaces, colors = paint(process8.stdout)) {
431
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
449
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
432
450
  }
433
451
  function wantsHelpJson(env = process8.env) {
434
452
  return env.KIT_HELP === "json";
@@ -454,29 +472,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
454
472
  return [];
455
473
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
456
474
  }
475
+ var MAX_INLINE_CHOICES = 24;
457
476
  function optionRows(options, colors = paint(process8.stdout)) {
458
477
  const rows = Object.entries(options).map(([name, option]) => {
459
478
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
460
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
479
+ const choices = option.choices?.join("|");
480
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
481
+ const named = inline ? `<${choices}>` : "<value>";
461
482
  const placeholder = option.optional === undefined ? named : `[${named}]`;
462
483
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
463
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
484
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
485
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
464
486
  });
465
487
  const width = Math.max(0, ...rows.map((row) => row.width));
466
488
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
467
489
  }
468
490
 
469
491
  // ../kit/src/text.ts
470
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
471
492
  function distance(a, b) {
472
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
473
- for (const [i, left] of [...a].entries()) {
493
+ const left = [...a];
494
+ const right = [...b];
495
+ let before = [];
496
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
497
+ for (const [i, x] of left.entries()) {
474
498
  const current = [i + 1];
475
- for (const [j, right] of [...b].entries())
476
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
499
+ for (const [j, y] of right.entries()) {
500
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
501
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
502
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
503
+ current.push(cost);
504
+ }
505
+ before = previous;
477
506
  previous = current;
478
507
  }
479
- return previous[b.length] ?? 0;
508
+ return previous[right.length] ?? 0;
480
509
  }
481
510
  function closest(name, names) {
482
511
  const started = names.find((known) => known.startsWith(name));
@@ -496,6 +525,17 @@ function wholeNumber(value, name, fallback, min = 1) {
496
525
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
497
526
  return number;
498
527
  }
528
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
529
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
530
+ function duration(value, name, fallback, unit = "s") {
531
+ if (value === undefined)
532
+ return fallback;
533
+ const match = DURATION.exec(value.trim());
534
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
535
+ if (ms < 1)
536
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
537
+ return ms;
538
+ }
499
539
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
500
540
  if (path === "-") {
501
541
  if (process9.stdin.isTTY)
@@ -553,7 +593,7 @@ class Completing {
553
593
  }
554
594
  var completion = { active: false };
555
595
  var OUTPUT_OPTIONS = {
556
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
596
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
557
597
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
558
598
  };
559
599
  function applyOutput(color, plain, env = process10.env) {
@@ -725,9 +765,33 @@ function nearestOption(message, options, allowNegative) {
725
765
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
726
766
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
727
767
  }
768
+ // ../kit/src/argv.ts
769
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
770
+ import { resolve as resolve3 } from "path";
771
+ import process11 from "process";
772
+ function commandLine() {
773
+ try {
774
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
775
+ } catch {
776
+ return;
777
+ }
778
+ }
779
+ function realPath(word) {
780
+ try {
781
+ return realpathSync(resolve3(word));
782
+ } catch {
783
+ return;
784
+ }
785
+ }
786
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
787
+ const target = script === undefined ? undefined : realPath(script) ?? script;
788
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
789
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
790
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
791
+ }
728
792
  // ../kit/src/process.ts
729
793
  import { constants } from "os";
730
- import process11 from "process";
794
+ import process12 from "process";
731
795
  var KILL_GRACE_MS = 2000;
732
796
  function exitCodeOf(code, signal) {
733
797
  if (code !== null)
@@ -747,7 +811,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
747
811
  return;
748
812
  try {
749
813
  if (grouped)
750
- process11.kill(-proc.pid, killing);
814
+ process12.kill(-proc.pid, killing);
751
815
  else
752
816
  proc.kill(killing);
753
817
  } catch {}
@@ -821,15 +885,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
821
885
  var RESET_STYLE = `${ESC}[0m`;
822
886
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
823
887
  // ../kit/src/cli.ts
824
- import { readFileSync as readFileSync2, realpathSync } from "fs";
888
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
825
889
  import { dirname as dirname3, join as join5 } from "path";
890
+ import process15 from "process";
891
+
892
+ // ../kit/src/completions.ts
893
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
894
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
895
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
896
+ set -l current (commandline -ct)
897
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
898
+ if test "$line" = __files__
899
+ __fish_complete_path $current
900
+ else
901
+ echo $line
902
+ end
903
+ end
904
+ end`;
905
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
906
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
907
+ local -a lines
908
+ COMPREPLY=()
909
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
910
+ for line in "\${lines[@]}"; do
911
+ if [[ $line == __files__ ]]; then
912
+ COMPREPLY+=($(compgen -f -- "$cur"))
913
+ else
914
+ words+="\${line%%$'\\t'*}"$'\\n'
915
+ fi
916
+ done
917
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
918
+ }`;
919
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
920
+ local line
921
+ local -a described plain
922
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
923
+ if [[ $line == __files__ ]]; then
924
+ _files
925
+ elif [[ $line == *$'\\t'* ]]; then
926
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
927
+ else
928
+ plain+=("$line")
929
+ fi
930
+ done
931
+ (( \${#described} )) && _describe -V value described
932
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
933
+ return 0
934
+ }`;
935
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
936
+ if (shell === "fish")
937
+ return `${header}
938
+ ${FISH_FUNCTION}
939
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
940
+ `).join("")}`;
941
+ if (shell === "bash")
942
+ return `${header}
943
+ ${BASH_FUNCTION}
944
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
945
+ `;
946
+ return `${header}
947
+ ${ZSH_FUNCTION}
948
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
949
+ `;
950
+ }
951
+
952
+ // ../kit/src/notify.ts
826
953
  import process13 from "process";
954
+ var NOTIFY_AFTER_MS = 1e4;
955
+ var CANCELLED = 130;
956
+ function base64(text) {
957
+ return Buffer.from(text).toString("base64");
958
+ }
959
+ function notification(title, body, env = process13.env) {
960
+ const id = `kit${process13.pid}`;
961
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
962
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
963
+ }
964
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
965
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
966
+ return;
967
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
968
+ }
827
969
 
828
970
  // ../kit/src/usage.ts
829
971
  import { appendFileSync, mkdirSync } from "fs";
830
972
  import { homedir as homedir3 } from "os";
831
973
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
832
- import process12 from "process";
974
+ import process14 from "process";
833
975
 
834
976
  // ../kit/src/logs.ts
835
977
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -843,14 +985,14 @@ var usageError;
843
985
  function noteUsageError(message) {
844
986
  usageError = message;
845
987
  }
846
- function stateHome(env = process12.env) {
988
+ function stateHome(env = process14.env) {
847
989
  const dir = env.XDG_STATE_HOME;
848
990
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
849
991
  }
850
- function usagePath(env = process12.env) {
992
+ function usagePath(env = process14.env) {
851
993
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
852
994
  }
853
- function usageRecorded(env = process12.env) {
995
+ function usageRecorded(env = process14.env) {
854
996
  const off = env.KAYNOOO_CLI_NO_USAGE;
855
997
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
856
998
  }
@@ -864,7 +1006,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
864
1006
  usageError = undefined;
865
1007
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
866
1008
  }
867
- function recordUsage(entry, env = process12.env) {
1009
+ function recordUsage(entry, env = process14.env) {
868
1010
  if (!usageRecorded(env))
869
1011
  return;
870
1012
  try {
@@ -880,7 +1022,11 @@ var LEVEL_OPTIONS = {
880
1022
  ...OUTPUT_OPTIONS,
881
1023
  help: { type: "boolean", short: "h", description: "show this help" }
882
1024
  };
883
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1025
+ var TOP_OPTIONS = {
1026
+ ...LEVEL_OPTIONS,
1027
+ version: { type: "boolean", short: "v", description: "print the version" },
1028
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1029
+ };
884
1030
  async function commandRows(all, colors) {
885
1031
  const commands = shown(all);
886
1032
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -941,7 +1087,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
941
1087
  header(colors, summary),
942
1088
  "",
943
1089
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
944
- ...replacesRows(replaces, colors),
945
1090
  "",
946
1091
  ...await commandRows(commands, colors),
947
1092
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -955,8 +1100,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
955
1100
  `);
956
1101
  }
957
1102
  function printError(prefix, message, hint, cause) {
958
- const colors = paint(process13.stderr);
959
- const styled = takesControlCodes(process13.stderr);
1103
+ const colors = paint(process15.stderr);
1104
+ const styled = takesControlCodes(process15.stderr);
960
1105
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
961
1106
  const under = (label, text, tint) => text === undefined ? "" : `
962
1107
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -999,11 +1144,11 @@ async function dispatch(level, typed, { version, redact }) {
999
1144
  }
1000
1145
  }
1001
1146
  if (name === undefined && level.path.length > 1) {
1002
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1147
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
1003
1148
  return 2;
1004
1149
  }
1005
1150
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1006
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1151
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
1007
1152
  return 0;
1008
1153
  }
1009
1154
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1059,24 +1204,24 @@ function candidateLine(candidate) {
1059
1204
  }
1060
1205
  function positionalBeingTyped(before, { options, positionals }) {
1061
1206
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1062
- let index = 0;
1207
+ const typed = [];
1063
1208
  let at = 0;
1064
1209
  while (at < before.length) {
1065
1210
  const word = before[at];
1066
1211
  if (word === "--") {
1067
- index += before.length - at - 1;
1212
+ typed.push(...before.slice(at + 1));
1068
1213
  break;
1069
1214
  }
1070
1215
  if (!word.startsWith("-"))
1071
- index++;
1216
+ typed.push(word);
1072
1217
  else if (takesValue(word))
1073
1218
  at++;
1074
1219
  at++;
1075
1220
  }
1076
1221
  const last = positionals.at(-1);
1077
- if (index < positionals.length)
1078
- return positionals[index];
1079
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1222
+ if (typed.length < positionals.length)
1223
+ return { name: positionals[typed.length], typed };
1224
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1080
1225
  }
1081
1226
  async function leafCandidates(run, words) {
1082
1227
  const completing = await completingOf(run);
@@ -1084,12 +1229,12 @@ async function leafCandidates(run, words) {
1084
1229
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1085
1230
  const flag = words.at(-2);
1086
1231
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1232
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1087
1233
  if (option?.type === "string") {
1088
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1234
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1089
1235
  return values === undefined ? [FILES] : values.map(candidateLine);
1090
1236
  }
1091
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1092
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1237
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1093
1238
  return values === undefined ? [FILES] : values.map(candidateLine);
1094
1239
  }
1095
1240
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1114,15 +1259,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1114
1259
  }
1115
1260
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1116
1261
  }
1262
+ var COMPLETIONS = "--completions";
1263
+ function flagValue([flag = "", ...rest]) {
1264
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1265
+ }
1266
+ function printCompletionScript(name, args) {
1267
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1268
+ if (shell === undefined || args.length !== 1) {
1269
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1270
+ return 2;
1271
+ }
1272
+ console.log(completionScript(shell, [name]).trimEnd());
1273
+ return 0;
1274
+ }
1117
1275
  async function printCandidates(found) {
1118
1276
  for (const line of await found)
1119
1277
  console.log(line);
1120
1278
  return 0;
1121
1279
  }
1122
1280
  function packageVersion(entry = Bun.main) {
1123
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1281
+ let resolved = entry;
1282
+ try {
1283
+ resolved = realpathSync2(entry);
1284
+ } catch {}
1285
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1124
1286
  try {
1125
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1287
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1126
1288
  if (typeof version === "string")
1127
1289
  return version;
1128
1290
  } catch {}
@@ -1130,14 +1292,19 @@ function packageVersion(entry = Bun.main) {
1130
1292
  return "0.0.0";
1131
1293
  }
1132
1294
  }
1133
- async function runCli(cli, argv = process13.argv.slice(2)) {
1295
+ async function runCli(cli, argv = scriptArgs()) {
1134
1296
  const version = cli.version ?? packageVersion();
1135
1297
  if (argv[0] === COMPLETE)
1136
1298
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1299
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1300
+ return printCompletionScript(cli.name, flagValue(argv));
1301
+ const started = performance.now();
1137
1302
  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 });
1303
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1304
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1138
1305
  if (cli.usage !== false) {
1139
1306
  try {
1140
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1307
+ recordUsage(usageEntry(cli.name, command, argv, code));
1141
1308
  } catch {}
1142
1309
  }
1143
1310
  return code;
@@ -1160,7 +1327,7 @@ function commandPath(scope, argv) {
1160
1327
  // ../kit/src/compose.ts
1161
1328
  async function captureOutput(argv, { cwd, env } = {}) {
1162
1329
  const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1163
- const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
1330
+ const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]);
1164
1331
  return { code, stdout, stderr };
1165
1332
  }
1166
1333
  async function compose(args, { flags = [], ...options } = {}) {
@@ -1189,7 +1356,9 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
1189
1356
  // src/args.ts
1190
1357
  var DEFAULT_ENV = "DATABASE_URL";
1191
1358
  var DEFAULT_LIMIT = 20;
1359
+ var DEFAULT_TIMEOUT_MS = 30000;
1192
1360
  var ALL_LIMIT = 100;
1361
+ var WRITE_EXIT = 1;
1193
1362
  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"]];
1194
1363
  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.';
1195
1364
  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.";
@@ -1197,23 +1366,30 @@ var connectionOptions = {
1197
1366
  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` },
1198
1367
  service: { type: "string", short: "s", description: "read the running Postgres, MySQL or MariaDB service of this name in the compose project, credentials from its environment" },
1199
1368
  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" },
1200
- database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" }
1369
+ database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" },
1370
+ timeout: { type: "string", description: `stop a statement after this long, a duration such as 500ms, 30s or 2m (${DEFAULT_TIMEOUT_MS / 1000}s)` }
1201
1371
  };
1372
+ function statementTimeout(values) {
1373
+ return Math.ceil(duration(values.timeout, "timeout", DEFAULT_TIMEOUT_MS));
1374
+ }
1202
1375
  var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
1203
1376
  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"] };
1204
1377
  function rowLimit(values, fallback = DEFAULT_LIMIT) {
1205
1378
  return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
1206
1379
  }
1380
+ var format2 = { type: "string", choices: ["tsv", "csv", "vertical"], description: "print the rows as tab-separated values, CSV (RFC 4180) or one `column | value` block per row, cells whole (a table by default)", conflicts: ["json"] };
1207
1381
  var catalogOptions = {
1208
1382
  rows,
1209
1383
  all,
1210
- json: jsonOption()
1384
+ json: jsonOption(),
1385
+ format: format2
1211
1386
  };
1212
1387
  var outputOptions = {
1213
1388
  rows,
1214
1389
  all,
1215
1390
  raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
1216
- json: jsonOption()
1391
+ json: jsonOption(),
1392
+ format: format2
1217
1393
  };
1218
1394
 
1219
1395
  // src/sql-tokens.ts
@@ -1550,28 +1726,57 @@ function shape(rows, limit, raw, exact = true) {
1550
1726
  const { rows: masked, masked: columns } = maskRows(rows.slice(0, limit), raw);
1551
1727
  return { columns: Object.keys(rows[0] ?? {}), rows: masked, total: rows.length, omitted: Math.max(0, rows.length - limit), exact, truncated: rows.length > limit, masked: columns };
1552
1728
  }
1553
- function render(shown, json) {
1554
- if (json)
1555
- return jsonText({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue);
1556
- if (shown.total === 0)
1557
- return "no rows";
1558
- const lines = [table([
1559
- shown.columns,
1560
- ...shown.rows.map((row) => shown.columns.map((column) => cell(row[column])))
1561
- ], { cellWidth: CELL_WIDTH })];
1729
+ var TSV_ESCAPES = { "\\": "\\\\", "\t": "\\t", "\n": "\\n", "\r": "\\r" };
1730
+ var TSV_SPECIALS = /[\\\t\n\r]/g;
1731
+ var CSV_SPECIALS = /["\r\n,]/;
1732
+ var tsvCell = (value) => cell(value).replace(TSV_SPECIALS, (char) => TSV_ESCAPES[char] ?? char);
1733
+ function csvCell(value) {
1734
+ const text = cell(value);
1735
+ return CSV_SPECIALS.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
1736
+ }
1737
+ function vertical(shown) {
1738
+ const width = Math.max(...shown.columns.map((column) => column.length));
1739
+ return shown.rows.map((row, index) => [`-[ RECORD ${index + 1} ]`, ...shown.columns.map((column) => `${column.padEnd(width)} | ${cell(row[column])}`)].join(`
1740
+ `)).join(`
1741
+ `);
1742
+ }
1743
+ function notes(shown) {
1744
+ const lines = [];
1562
1745
  if (shown.truncated && !shown.exact)
1563
1746
  lines.push("... more rows not shown (-n raises the cap)");
1564
1747
  else if (shown.truncated)
1565
1748
  lines.push(`... ${shown.omitted} more ${shown.omitted === 1 ? "row" : "rows"} not shown (${shown.total} in all, -n raises the cap)`);
1566
1749
  if (shown.masked.length > 0)
1567
1750
  lines.push(`masked: ${shown.masked.join(", ")} (--raw shows them)`);
1568
- return lines.join(`
1751
+ return lines;
1752
+ }
1753
+ function delimited(shown, format) {
1754
+ const [separator, escape] = format === "tsv" ? ["\t", tsvCell] : [",", csvCell];
1755
+ for (const note of notes(shown))
1756
+ warn(note);
1757
+ return [shown.columns, ...shown.rows.map((row) => shown.columns.map((column) => row[column]))].map((line) => line.map(escape).join(separator)).join(`
1758
+ `);
1759
+ }
1760
+ function render(shown, json, format) {
1761
+ if (json)
1762
+ return jsonText({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue);
1763
+ if (shown.total === 0)
1764
+ return format === "tsv" || format === "csv" ? "" : "no rows";
1765
+ if (format === "tsv" || format === "csv")
1766
+ return delimited(shown, format);
1767
+ if (format === "vertical")
1768
+ return [vertical(shown), ...notes(shown)].join(`
1769
+ `);
1770
+ return [table([
1771
+ shown.columns,
1772
+ ...shown.rows.map((row) => shown.columns.map((column) => cell(row[column])))
1773
+ ], { cellWidth: CELL_WIDTH }), ...notes(shown)].join(`
1569
1774
  `);
1570
1775
  }
1571
1776
 
1572
1777
  // src/run.ts
1573
1778
  import { isIP } from "net";
1574
- import process15 from "process";
1779
+ import process17 from "process";
1575
1780
  var {SQL } = globalThis.Bun;
1576
1781
 
1577
1782
  // src/compose.ts
@@ -1754,7 +1959,6 @@ async function loadSettings(home) {
1754
1959
  }
1755
1960
 
1756
1961
  // src/run.ts
1757
- var STATEMENT_TIMEOUT = "30s";
1758
1962
  var SESSION_SETTINGS = { lock_timeout: "5s", idle_in_transaction_session_timeout: "60s" };
1759
1963
  var CURSOR = "db_rows";
1760
1964
  var CURSOR_STARTS = /^\s*(?:select|with|values|table)\b/i;
@@ -1765,7 +1969,7 @@ var BRACKETS = /^\[|\]$/g;
1765
1969
  var POSTGRES_SCHEMES = new Set(["postgres:", "postgresql:"]);
1766
1970
  var MYSQL_SCHEMES = new Set(["mysql:", "mysql2:", "mariadb:"]);
1767
1971
  var WRAP_ERRNOS = new Set([1064, 1060]);
1768
- var MYSQL_TIMEOUTS = ["SET SESSION max_execution_time = 30000", "SET SESSION max_statement_time = 30"];
1972
+ var mysqlTimeouts = (ms) => [`SET SESSION max_execution_time = ${ms}`, `SET SESSION max_statement_time = ${ms / 1000}`];
1769
1973
  var TEST_SUFFIX = "_test";
1770
1974
 
1771
1975
  class Rollback extends Error {
@@ -1826,7 +2030,7 @@ async function connectionUrl({ env, service, container, database }, home) {
1826
2030
  if (service !== undefined && container !== undefined)
1827
2031
  fail("--service and --container name two databases: pick one");
1828
2032
  const isNamed = service !== undefined || container !== undefined;
1829
- const value = isNamed ? undefined : process15.env[env ?? DEFAULT_ENV];
2033
+ const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
1830
2034
  let url;
1831
2035
  if (value !== undefined && value !== "")
1832
2036
  url = await reachable(value, home);
@@ -1851,13 +2055,13 @@ function databaseOfUrl(url) {
1851
2055
  function toResult(rows) {
1852
2056
  return Object.assign([...rows], { affected: rows.count ?? rows.affectedRows ?? rows.length });
1853
2057
  }
1854
- var bunConnect = (url, dialect, readOnly) => {
2058
+ var bunConnect = (url, dialect, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1855
2059
  const sql = new SQL({ url, max: 1, connectionTimeout: 10, ...dialect === "postgres" ? { connection: { ...SESSION_SETTINGS, ...readOnly ? { default_transaction_read_only: "on" } : {} } } : { allowPublicKeyRetrieval: allowsKeyRetrieval(url) } });
1856
2060
  return {
1857
2061
  async transaction(work, isReadOnly) {
1858
2062
  if (dialect === "postgres") {
1859
2063
  const body = async (tx) => {
1860
- await tx.unsafe(`SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT}'`);
2064
+ await tx.unsafe(`SET LOCAL statement_timeout = '${timeoutMs}ms'`);
1861
2065
  await work({ unsafe: async (statement, params) => toResult(await tx.unsafe(statement, params)) });
1862
2066
  };
1863
2067
  await (isReadOnly ? sql.begin("read only", body) : sql.begin(body));
@@ -1865,7 +2069,7 @@ var bunConnect = (url, dialect, readOnly) => {
1865
2069
  }
1866
2070
  const connection = await sql.reserve();
1867
2071
  try {
1868
- await mysqlTransaction({ unsafe: async (statement, params) => connection.unsafe(statement, params) }, work, isReadOnly);
2072
+ await mysqlTransaction({ unsafe: async (statement, params) => connection.unsafe(statement, params) }, work, isReadOnly, timeoutMs);
1869
2073
  } finally {
1870
2074
  await connection.release();
1871
2075
  }
@@ -1875,8 +2079,8 @@ var bunConnect = (url, dialect, readOnly) => {
1875
2079
  }
1876
2080
  };
1877
2081
  };
1878
- async function mysqlTransaction(connection, work, readOnly) {
1879
- for (const timeout of MYSQL_TIMEOUTS) {
2082
+ async function mysqlTransaction(connection, work, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) {
2083
+ for (const timeout of mysqlTimeouts(timeoutMs)) {
1880
2084
  try {
1881
2085
  await connection.unsafe(timeout);
1882
2086
  } catch {}
@@ -1913,9 +2117,9 @@ ${statement.replace(TRAILING_SEMICOLONS, "")}
1913
2117
  function messageOf(error, url) {
1914
2118
  return scrub(error instanceof Error ? error.message : String(error), url);
1915
2119
  }
1916
- async function readRows(url, statement, params = [], limit, connect = bunConnect) {
2120
+ async function readRows(url, statement, params = [], limit, connect = bunConnect, timeoutMs = DEFAULT_TIMEOUT_MS) {
1917
2121
  const dialect = dialectOf(new URL(url));
1918
- const session = connect(url, dialect, true);
2122
+ const session = connect(url, dialect, true, timeoutMs);
1919
2123
  let rows = [];
1920
2124
  try {
1921
2125
  await session.transaction(async (tx) => {
@@ -1966,7 +2170,7 @@ async function closeQuietly(session, url) {
1966
2170
  try {
1967
2171
  await session.close();
1968
2172
  } catch (error) {
1969
- console.error(messageOf(error, url));
2173
+ warn(messageOf(error, url));
1970
2174
  }
1971
2175
  }
1972
2176
 
@@ -1976,13 +2180,12 @@ var usage2 = `db query "<sql>"
1976
2180
  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.
1977
2181
 
1978
2182
  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.
1979
- 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.
2183
+ Statements time out after 30 seconds (--timeout changes it) 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.
1980
2184
 
1981
2185
  ${WRITE_NOTE}
1982
2186
 
1983
2187
  ${HOSTS_NOTE}`;
1984
2188
  var options = { ...connectionOptions, ...outputOptions };
1985
- var WRITE_EXIT = 1;
1986
2189
  var NO_SQL = "no SQL given: pass it as an argument or on stdin";
1987
2190
  async function readSql(positionals) {
1988
2191
  const sql = positionals.length === 0 ? await readInput("-", { noStdin: NO_SQL }) : positionals.join(" ");
@@ -1991,9 +2194,8 @@ async function readSql(positionals) {
1991
2194
  return sql;
1992
2195
  }
1993
2196
  function handBack(sql, reasons, note = "") {
1994
- console.log(`db: not run, this statement would write or cannot be shown to only read (${reasons.join("; ")})${note}. Run it yourself:
1995
-
1996
- \`\`\`sql
2197
+ problem(`db: not run, this statement would write or cannot be shown to only read (${reasons.join("; ")})${note}. Run it yourself:`);
2198
+ console.log(`\`\`\`sql
1997
2199
  ${sql.trim()}
1998
2200
  \`\`\``);
1999
2201
  return WRITE_EXIT;
@@ -2025,39 +2227,55 @@ async function query(args) {
2025
2227
  console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
2026
2228
  else
2027
2229
  console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
2028
- ${render(shown, false)}`}`);
2230
+ ${render(shown, false, values.format)}`}`);
2029
2231
  return 0;
2030
2232
  }
2031
2233
  if (verdict.statements > 1)
2032
2234
  fail("one statement at a time");
2033
- const rows = await readRows(url, sql, [], limit);
2034
- console.log(render(shape(rows, limit, values.raw === true, false), values.json === true));
2235
+ const rows = await readRows(url, sql, [], limit, undefined, statementTimeout(values));
2236
+ console.log(render(shape(rows, limit, values.raw === true, false), values.json === true, values.format));
2035
2237
  return 0;
2036
2238
  }
2037
2239
 
2038
2240
  // src/commands/explain.ts
2039
- var usage3 = `db explain "<sql>"
2241
+ var usage3 = `db explain "<sql>" [--analyze]
2040
2242
 
2041
- 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.
2243
+ Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone. 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.
2244
+ --analyze runs the read for real to time it, inside the READ ONLY transaction that is rolled back: EXPLAIN ANALYZE on Postgres and MySQL 8.0.18 or later, ANALYZE on MariaDB, refused on an older MySQL.
2042
2245
 
2043
2246
  ${HOSTS_NOTE}`;
2044
- var options2 = { ...connectionOptions, json: jsonOption() };
2247
+ var options2 = { ...connectionOptions, json: jsonOption(), analyze: { type: "boolean", description: "run the read to time it, in the transaction that is rolled back" } };
2045
2248
  var READ_START = /^\s*(?:select|with|values|table)\b/i;
2046
2249
  var TRAILING_SEMICOLON = /;\s*$/;
2047
- function explainSql(sql, dialect) {
2250
+ var MARIADB = /mariadb/i;
2251
+ var MYSQL_VERSION = /^(\d+)\.(\d+)\.(\d+)/;
2252
+ function explainSql(sql, dialect, prefix = "EXPLAIN") {
2048
2253
  const verdict = inspect(sql, dialect);
2049
2254
  if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
2050
2255
  fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
2051
- return `EXPLAIN ${sql.trim().replace(TRAILING_SEMICOLON, "")}`;
2256
+ return `${prefix} ${sql.trim().replace(TRAILING_SEMICOLON, "")}`;
2257
+ }
2258
+ function analyzePrefix(version) {
2259
+ if (MARIADB.test(version))
2260
+ return "ANALYZE";
2261
+ const [, major = 0, minor = 0, patch = 0] = MYSQL_VERSION.exec(version)?.map(Number) ?? [];
2262
+ if (major > 8 || major === 8 && (minor > 0 || patch >= 18))
2263
+ return "EXPLAIN ANALYZE";
2264
+ return fail(`--analyze needs MySQL 8.0.18 or later or MariaDB, this server is ${version}`);
2052
2265
  }
2053
2266
  async function explain(args) {
2054
2267
  const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
2055
2268
  const sql = await readSql(positionals);
2056
2269
  const url = await connectionUrl(values);
2057
2270
  const dialect = dialectOf(new URL(url));
2058
- const rows = await readRows(url, explainSql(sql, dialect));
2059
- if (dialect === "postgres" && values.json !== true)
2060
- console.log(rows.map((row) => String(row["QUERY PLAN"])).join(`
2271
+ const timeout = statementTimeout(values);
2272
+ let prefix = "EXPLAIN";
2273
+ if (values.analyze === true)
2274
+ prefix = dialect === "postgres" ? "EXPLAIN ANALYZE" : analyzePrefix(String((await readRows(url, "select version() as version", [], undefined, undefined, timeout))[0]?.version));
2275
+ const rows = await readRows(url, explainSql(sql, dialect, prefix), [], undefined, undefined, timeout);
2276
+ const [only, ...others] = Object.keys(rows[0] ?? {});
2277
+ if (values.json !== true && only !== undefined && others.length === 0)
2278
+ console.log(rows.map((row) => String(row[only])).join(`
2061
2279
  `));
2062
2280
  else
2063
2281
  console.log(render(shape(rows, rows.length, true), values.json === true));
@@ -2158,8 +2376,8 @@ async function show(args, usage, work) {
2158
2376
  const limit = rowLimit(values);
2159
2377
  const url = await connectionUrl(values);
2160
2378
  const { sql, params } = plans[dialectOf(new URL(url))];
2161
- const rows = await readRows(url, sql, params, limit);
2162
- console.log(render(shape(rows, limit, true, false), values.json === true));
2379
+ const rows = await readRows(url, sql, params, limit, undefined, statementTimeout(values));
2380
+ console.log(render(shape(rows, limit, true, false), values.json === true, values.format));
2163
2381
  return 0;
2164
2382
  }
2165
2383
  async function tables(args) {
@@ -2222,20 +2440,20 @@ ${HOSTS_NOTE}`;
2222
2440
  const limit = rowLimit(values);
2223
2441
  const url = await connectionUrl(values);
2224
2442
  const dialect = dialectOf(new URL(url));
2225
- const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap);
2443
+ const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap, undefined, statementTimeout(values));
2226
2444
  const columns = shape(await ask(plans.columns, limit), limit, true, false);
2227
2445
  const indexes = await ask(plans.indexes);
2228
2446
  const foreignKeys = await ask(plans.foreignKeys);
2229
2447
  if (values.json === true)
2230
2448
  console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
2231
2449
  else
2232
- console.log(`${render(columns, false)}
2450
+ console.log(`${render(columns, false, values.format)}
2233
2451
 
2234
2452
  indexes
2235
- ${render(shape(indexes, indexes.length, true), false)}
2453
+ ${render(shape(indexes, indexes.length, true), false, values.format)}
2236
2454
 
2237
2455
  foreign keys
2238
- ${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
2456
+ ${render(shape(foreignKeys, foreignKeys.length, true), false, values.format)}`);
2239
2457
  return 0;
2240
2458
  }
2241
2459
 
@@ -2257,7 +2475,7 @@ function countSql(target, dialect, where) {
2257
2475
  }
2258
2476
  var where = { type: "string", short: "w", description: "only the rows matching this SQL condition" };
2259
2477
  var sampleOptions = { ...connectionOptions, ...outputOptions, where };
2260
- var countOptions = { ...connectionOptions, json: outputOptions.json, where };
2478
+ var countOptions = { ...connectionOptions, json: outputOptions.json, format: outputOptions.format, where };
2261
2479
  async function run(args, usage, options, build) {
2262
2480
  const parsed = parse(args, usage, options, { exits: EXITS });
2263
2481
  const { values, positionals } = parsed;
@@ -2271,7 +2489,7 @@ async function run(args, usage, options, build) {
2271
2489
  const verdict = inspect(sql, dialect);
2272
2490
  if (verdict.reasons.length > 0 || verdict.statements > 1)
2273
2491
  fail(`not a plain read: ${verdict.reasons.join("; ") || "one statement at a time"}`);
2274
- console.log(render(shape(await readRows(url, sql, [], limit), limit, values.raw === true, false), values.json === true));
2492
+ console.log(render(shape(await readRows(url, sql, [], limit, undefined, statementTimeout(values)), limit, values.raw === true, false), values.json === true, values.format));
2275
2493
  return 0;
2276
2494
  }
2277
2495
  async function sample(args) {
@@ -2290,17 +2508,17 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
2290
2508
  }
2291
2509
 
2292
2510
  // src/cli.ts
2293
- process16.exitCode = await runCli({
2511
+ process18.exitCode = await runCli({
2294
2512
  name: "db",
2295
2513
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
2296
2514
  replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
2297
- 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"]],
2515
+ 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"], ['db --format csv "select id, email from users"', "RFC 4180 CSV, or tsv or vertical"]],
2298
2516
  commands: {
2299
2517
  query: { run: query, summary: 'run one read-only statement (the default: db "<sql>"), a write runs on a _test database and is printed otherwise' },
2300
2518
  tables: { run: tables, summary: "list tables and views with an estimated row count" },
2301
2519
  describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
2302
2520
  search: { run: search, summary: "find the tables and columns whose name contains a text" },
2303
- explain: { run: explain, summary: "the plan of one read without running it (EXPLAIN, never ANALYZE)" },
2521
+ explain: { run: explain, summary: "the plan of one read, run and timed with --analyze (in the rolled-back read-only transaction)" },
2304
2522
  sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
2305
2523
  count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
2306
2524
  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.12.0",
4
+ "version": "0.13.1",
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.35.0"
31
+ "@kaynooo/cli-kit": "0.41.0"
32
32
  }
33
33
  }