@kaynooo/cli-db 0.12.1 → 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.
- package/README.md +4 -4
- package/dist/cli.js +306 -92
- 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
|
|
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,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
5
|
+
import process18 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
7
|
import process10 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
@@ -359,6 +359,23 @@ var STATUS_WORDS = {
|
|
|
359
359
|
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
360
360
|
|
|
361
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
|
+
}
|
|
362
379
|
function upTo(text, separator) {
|
|
363
380
|
const end = text.indexOf(separator);
|
|
364
381
|
return end === -1 ? text : text.slice(0, end);
|
|
@@ -416,24 +433,20 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
|
|
|
416
433
|
|
|
417
434
|
// ../kit/src/help.ts
|
|
418
435
|
import process8 from "process";
|
|
419
|
-
var OPTIONAL =
|
|
436
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
420
437
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
421
438
|
var FULL_STOP = /\.$/;
|
|
422
439
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
423
440
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
424
441
|
}
|
|
425
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
426
|
-
return [usageLine(usage, colors),
|
|
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(`
|
|
427
444
|
`);
|
|
428
445
|
}
|
|
429
446
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
430
447
|
if (exits.length === 0)
|
|
431
448
|
return [];
|
|
432
|
-
|
|
433
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
434
|
-
}
|
|
435
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
436
|
-
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(", ")}`];
|
|
437
450
|
}
|
|
438
451
|
function wantsHelpJson(env = process8.env) {
|
|
439
452
|
return env.KIT_HELP === "json";
|
|
@@ -459,29 +472,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
459
472
|
return [];
|
|
460
473
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
461
474
|
}
|
|
475
|
+
var MAX_INLINE_CHOICES = 24;
|
|
462
476
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
463
477
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
464
478
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
465
|
-
const
|
|
479
|
+
const choices = option.choices?.join("|");
|
|
480
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
481
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
466
482
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
467
483
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
468
|
-
|
|
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 };
|
|
469
486
|
});
|
|
470
487
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
471
488
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
472
489
|
}
|
|
473
490
|
|
|
474
491
|
// ../kit/src/text.ts
|
|
475
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
476
492
|
function distance(a, b) {
|
|
477
|
-
|
|
478
|
-
|
|
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()) {
|
|
479
498
|
const current = [i + 1];
|
|
480
|
-
for (const [j,
|
|
481
|
-
|
|
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;
|
|
482
506
|
previous = current;
|
|
483
507
|
}
|
|
484
|
-
return previous[
|
|
508
|
+
return previous[right.length] ?? 0;
|
|
485
509
|
}
|
|
486
510
|
function closest(name, names) {
|
|
487
511
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -501,6 +525,17 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
501
525
|
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
502
526
|
return number;
|
|
503
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
|
+
}
|
|
504
539
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
505
540
|
if (path === "-") {
|
|
506
541
|
if (process9.stdin.isTTY)
|
|
@@ -558,7 +593,7 @@ class Completing {
|
|
|
558
593
|
}
|
|
559
594
|
var completion = { active: false };
|
|
560
595
|
var OUTPUT_OPTIONS = {
|
|
561
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
596
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
562
597
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
563
598
|
};
|
|
564
599
|
function applyOutput(color, plain, env = process10.env) {
|
|
@@ -730,9 +765,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
730
765
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
731
766
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
732
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
|
+
}
|
|
733
792
|
// ../kit/src/process.ts
|
|
734
793
|
import { constants } from "os";
|
|
735
|
-
import
|
|
794
|
+
import process12 from "process";
|
|
736
795
|
var KILL_GRACE_MS = 2000;
|
|
737
796
|
function exitCodeOf(code, signal) {
|
|
738
797
|
if (code !== null)
|
|
@@ -752,7 +811,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
752
811
|
return;
|
|
753
812
|
try {
|
|
754
813
|
if (grouped)
|
|
755
|
-
|
|
814
|
+
process12.kill(-proc.pid, killing);
|
|
756
815
|
else
|
|
757
816
|
proc.kill(killing);
|
|
758
817
|
} catch {}
|
|
@@ -826,15 +885,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
826
885
|
var RESET_STYLE = `${ESC}[0m`;
|
|
827
886
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
828
887
|
// ../kit/src/cli.ts
|
|
829
|
-
import { readFileSync as
|
|
888
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
830
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
|
|
831
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
|
+
}
|
|
832
969
|
|
|
833
970
|
// ../kit/src/usage.ts
|
|
834
971
|
import { appendFileSync, mkdirSync } from "fs";
|
|
835
972
|
import { homedir as homedir3 } from "os";
|
|
836
973
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
837
|
-
import
|
|
974
|
+
import process14 from "process";
|
|
838
975
|
|
|
839
976
|
// ../kit/src/logs.ts
|
|
840
977
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -848,14 +985,14 @@ var usageError;
|
|
|
848
985
|
function noteUsageError(message) {
|
|
849
986
|
usageError = message;
|
|
850
987
|
}
|
|
851
|
-
function stateHome(env =
|
|
988
|
+
function stateHome(env = process14.env) {
|
|
852
989
|
const dir = env.XDG_STATE_HOME;
|
|
853
990
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
854
991
|
}
|
|
855
|
-
function usagePath(env =
|
|
992
|
+
function usagePath(env = process14.env) {
|
|
856
993
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
857
994
|
}
|
|
858
|
-
function usageRecorded(env =
|
|
995
|
+
function usageRecorded(env = process14.env) {
|
|
859
996
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
860
997
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
861
998
|
}
|
|
@@ -869,7 +1006,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
869
1006
|
usageError = undefined;
|
|
870
1007
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
871
1008
|
}
|
|
872
|
-
function recordUsage(entry, env =
|
|
1009
|
+
function recordUsage(entry, env = process14.env) {
|
|
873
1010
|
if (!usageRecorded(env))
|
|
874
1011
|
return;
|
|
875
1012
|
try {
|
|
@@ -885,7 +1022,11 @@ var LEVEL_OPTIONS = {
|
|
|
885
1022
|
...OUTPUT_OPTIONS,
|
|
886
1023
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
887
1024
|
};
|
|
888
|
-
var TOP_OPTIONS = {
|
|
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
|
+
};
|
|
889
1030
|
async function commandRows(all, colors) {
|
|
890
1031
|
const commands = shown(all);
|
|
891
1032
|
const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
|
|
@@ -946,7 +1087,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
946
1087
|
header(colors, summary),
|
|
947
1088
|
"",
|
|
948
1089
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
949
|
-
...replacesRows(replaces, colors),
|
|
950
1090
|
"",
|
|
951
1091
|
...await commandRows(commands, colors),
|
|
952
1092
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -960,8 +1100,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
960
1100
|
`);
|
|
961
1101
|
}
|
|
962
1102
|
function printError(prefix, message, hint, cause) {
|
|
963
|
-
const colors = paint(
|
|
964
|
-
const styled = takesControlCodes(
|
|
1103
|
+
const colors = paint(process15.stderr);
|
|
1104
|
+
const styled = takesControlCodes(process15.stderr);
|
|
965
1105
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
966
1106
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
967
1107
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1004,11 +1144,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1004
1144
|
}
|
|
1005
1145
|
}
|
|
1006
1146
|
if (name === undefined && level.path.length > 1) {
|
|
1007
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1147
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1008
1148
|
return 2;
|
|
1009
1149
|
}
|
|
1010
1150
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1011
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1151
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1012
1152
|
return 0;
|
|
1013
1153
|
}
|
|
1014
1154
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1064,24 +1204,24 @@ function candidateLine(candidate) {
|
|
|
1064
1204
|
}
|
|
1065
1205
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1066
1206
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1067
|
-
|
|
1207
|
+
const typed = [];
|
|
1068
1208
|
let at = 0;
|
|
1069
1209
|
while (at < before.length) {
|
|
1070
1210
|
const word = before[at];
|
|
1071
1211
|
if (word === "--") {
|
|
1072
|
-
|
|
1212
|
+
typed.push(...before.slice(at + 1));
|
|
1073
1213
|
break;
|
|
1074
1214
|
}
|
|
1075
1215
|
if (!word.startsWith("-"))
|
|
1076
|
-
|
|
1216
|
+
typed.push(word);
|
|
1077
1217
|
else if (takesValue(word))
|
|
1078
1218
|
at++;
|
|
1079
1219
|
at++;
|
|
1080
1220
|
}
|
|
1081
1221
|
const last = positionals.at(-1);
|
|
1082
|
-
if (
|
|
1083
|
-
return positionals[
|
|
1084
|
-
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 };
|
|
1085
1225
|
}
|
|
1086
1226
|
async function leafCandidates(run, words) {
|
|
1087
1227
|
const completing = await completingOf(run);
|
|
@@ -1089,12 +1229,12 @@ async function leafCandidates(run, words) {
|
|
|
1089
1229
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1090
1230
|
const flag = words.at(-2);
|
|
1091
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);
|
|
1092
1233
|
if (option?.type === "string") {
|
|
1093
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1234
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1094
1235
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1095
1236
|
}
|
|
1096
|
-
const
|
|
1097
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1237
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1098
1238
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1099
1239
|
}
|
|
1100
1240
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1119,15 +1259,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
|
|
|
1119
1259
|
}
|
|
1120
1260
|
return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
|
|
1121
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
|
+
}
|
|
1122
1275
|
async function printCandidates(found) {
|
|
1123
1276
|
for (const line of await found)
|
|
1124
1277
|
console.log(line);
|
|
1125
1278
|
return 0;
|
|
1126
1279
|
}
|
|
1127
1280
|
function packageVersion(entry = Bun.main) {
|
|
1128
|
-
|
|
1281
|
+
let resolved = entry;
|
|
1282
|
+
try {
|
|
1283
|
+
resolved = realpathSync2(entry);
|
|
1284
|
+
} catch {}
|
|
1285
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1129
1286
|
try {
|
|
1130
|
-
const { version } = JSON.parse(
|
|
1287
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1131
1288
|
if (typeof version === "string")
|
|
1132
1289
|
return version;
|
|
1133
1290
|
} catch {}
|
|
@@ -1135,14 +1292,19 @@ function packageVersion(entry = Bun.main) {
|
|
|
1135
1292
|
return "0.0.0";
|
|
1136
1293
|
}
|
|
1137
1294
|
}
|
|
1138
|
-
async function runCli(cli, argv =
|
|
1295
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1139
1296
|
const version = cli.version ?? packageVersion();
|
|
1140
1297
|
if (argv[0] === COMPLETE)
|
|
1141
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();
|
|
1142
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);
|
|
1143
1305
|
if (cli.usage !== false) {
|
|
1144
1306
|
try {
|
|
1145
|
-
recordUsage(usageEntry(cli.name,
|
|
1307
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1146
1308
|
} catch {}
|
|
1147
1309
|
}
|
|
1148
1310
|
return code;
|
|
@@ -1194,6 +1356,7 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
|
1194
1356
|
// src/args.ts
|
|
1195
1357
|
var DEFAULT_ENV = "DATABASE_URL";
|
|
1196
1358
|
var DEFAULT_LIMIT = 20;
|
|
1359
|
+
var DEFAULT_TIMEOUT_MS = 30000;
|
|
1197
1360
|
var ALL_LIMIT = 100;
|
|
1198
1361
|
var WRITE_EXIT = 1;
|
|
1199
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"]];
|
|
@@ -1203,23 +1366,30 @@ var connectionOptions = {
|
|
|
1203
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` },
|
|
1204
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" },
|
|
1205
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" },
|
|
1206
|
-
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)` }
|
|
1207
1371
|
};
|
|
1372
|
+
function statementTimeout(values) {
|
|
1373
|
+
return Math.ceil(duration(values.timeout, "timeout", DEFAULT_TIMEOUT_MS));
|
|
1374
|
+
}
|
|
1208
1375
|
var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
|
|
1209
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"] };
|
|
1210
1377
|
function rowLimit(values, fallback = DEFAULT_LIMIT) {
|
|
1211
1378
|
return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
|
|
1212
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"] };
|
|
1213
1381
|
var catalogOptions = {
|
|
1214
1382
|
rows,
|
|
1215
1383
|
all,
|
|
1216
|
-
json: jsonOption()
|
|
1384
|
+
json: jsonOption(),
|
|
1385
|
+
format: format2
|
|
1217
1386
|
};
|
|
1218
1387
|
var outputOptions = {
|
|
1219
1388
|
rows,
|
|
1220
1389
|
all,
|
|
1221
1390
|
raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
|
|
1222
|
-
json: jsonOption()
|
|
1391
|
+
json: jsonOption(),
|
|
1392
|
+
format: format2
|
|
1223
1393
|
};
|
|
1224
1394
|
|
|
1225
1395
|
// src/sql-tokens.ts
|
|
@@ -1556,28 +1726,57 @@ function shape(rows, limit, raw, exact = true) {
|
|
|
1556
1726
|
const { rows: masked, masked: columns } = maskRows(rows.slice(0, limit), raw);
|
|
1557
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 };
|
|
1558
1728
|
}
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
const
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
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 = [];
|
|
1568
1745
|
if (shown.truncated && !shown.exact)
|
|
1569
1746
|
lines.push("... more rows not shown (-n raises the cap)");
|
|
1570
1747
|
else if (shown.truncated)
|
|
1571
1748
|
lines.push(`... ${shown.omitted} more ${shown.omitted === 1 ? "row" : "rows"} not shown (${shown.total} in all, -n raises the cap)`);
|
|
1572
1749
|
if (shown.masked.length > 0)
|
|
1573
1750
|
lines.push(`masked: ${shown.masked.join(", ")} (--raw shows them)`);
|
|
1574
|
-
return lines
|
|
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(`
|
|
1575
1774
|
`);
|
|
1576
1775
|
}
|
|
1577
1776
|
|
|
1578
1777
|
// src/run.ts
|
|
1579
1778
|
import { isIP } from "net";
|
|
1580
|
-
import
|
|
1779
|
+
import process17 from "process";
|
|
1581
1780
|
var {SQL } = globalThis.Bun;
|
|
1582
1781
|
|
|
1583
1782
|
// src/compose.ts
|
|
@@ -1760,7 +1959,6 @@ async function loadSettings(home) {
|
|
|
1760
1959
|
}
|
|
1761
1960
|
|
|
1762
1961
|
// src/run.ts
|
|
1763
|
-
var STATEMENT_TIMEOUT = "30s";
|
|
1764
1962
|
var SESSION_SETTINGS = { lock_timeout: "5s", idle_in_transaction_session_timeout: "60s" };
|
|
1765
1963
|
var CURSOR = "db_rows";
|
|
1766
1964
|
var CURSOR_STARTS = /^\s*(?:select|with|values|table)\b/i;
|
|
@@ -1771,7 +1969,7 @@ var BRACKETS = /^\[|\]$/g;
|
|
|
1771
1969
|
var POSTGRES_SCHEMES = new Set(["postgres:", "postgresql:"]);
|
|
1772
1970
|
var MYSQL_SCHEMES = new Set(["mysql:", "mysql2:", "mariadb:"]);
|
|
1773
1971
|
var WRAP_ERRNOS = new Set([1064, 1060]);
|
|
1774
|
-
var
|
|
1972
|
+
var mysqlTimeouts = (ms) => [`SET SESSION max_execution_time = ${ms}`, `SET SESSION max_statement_time = ${ms / 1000}`];
|
|
1775
1973
|
var TEST_SUFFIX = "_test";
|
|
1776
1974
|
|
|
1777
1975
|
class Rollback extends Error {
|
|
@@ -1832,7 +2030,7 @@ async function connectionUrl({ env, service, container, database }, home) {
|
|
|
1832
2030
|
if (service !== undefined && container !== undefined)
|
|
1833
2031
|
fail("--service and --container name two databases: pick one");
|
|
1834
2032
|
const isNamed = service !== undefined || container !== undefined;
|
|
1835
|
-
const value = isNamed ? undefined :
|
|
2033
|
+
const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
|
|
1836
2034
|
let url;
|
|
1837
2035
|
if (value !== undefined && value !== "")
|
|
1838
2036
|
url = await reachable(value, home);
|
|
@@ -1857,13 +2055,13 @@ function databaseOfUrl(url) {
|
|
|
1857
2055
|
function toResult(rows) {
|
|
1858
2056
|
return Object.assign([...rows], { affected: rows.count ?? rows.affectedRows ?? rows.length });
|
|
1859
2057
|
}
|
|
1860
|
-
var bunConnect = (url, dialect, readOnly) => {
|
|
2058
|
+
var bunConnect = (url, dialect, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) => {
|
|
1861
2059
|
const sql = new SQL({ url, max: 1, connectionTimeout: 10, ...dialect === "postgres" ? { connection: { ...SESSION_SETTINGS, ...readOnly ? { default_transaction_read_only: "on" } : {} } } : { allowPublicKeyRetrieval: allowsKeyRetrieval(url) } });
|
|
1862
2060
|
return {
|
|
1863
2061
|
async transaction(work, isReadOnly) {
|
|
1864
2062
|
if (dialect === "postgres") {
|
|
1865
2063
|
const body = async (tx) => {
|
|
1866
|
-
await tx.unsafe(`SET LOCAL statement_timeout = '${
|
|
2064
|
+
await tx.unsafe(`SET LOCAL statement_timeout = '${timeoutMs}ms'`);
|
|
1867
2065
|
await work({ unsafe: async (statement, params) => toResult(await tx.unsafe(statement, params)) });
|
|
1868
2066
|
};
|
|
1869
2067
|
await (isReadOnly ? sql.begin("read only", body) : sql.begin(body));
|
|
@@ -1871,7 +2069,7 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1871
2069
|
}
|
|
1872
2070
|
const connection = await sql.reserve();
|
|
1873
2071
|
try {
|
|
1874
|
-
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);
|
|
1875
2073
|
} finally {
|
|
1876
2074
|
await connection.release();
|
|
1877
2075
|
}
|
|
@@ -1881,8 +2079,8 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1881
2079
|
}
|
|
1882
2080
|
};
|
|
1883
2081
|
};
|
|
1884
|
-
async function mysqlTransaction(connection, work, readOnly) {
|
|
1885
|
-
for (const timeout of
|
|
2082
|
+
async function mysqlTransaction(connection, work, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
2083
|
+
for (const timeout of mysqlTimeouts(timeoutMs)) {
|
|
1886
2084
|
try {
|
|
1887
2085
|
await connection.unsafe(timeout);
|
|
1888
2086
|
} catch {}
|
|
@@ -1919,9 +2117,9 @@ ${statement.replace(TRAILING_SEMICOLONS, "")}
|
|
|
1919
2117
|
function messageOf(error, url) {
|
|
1920
2118
|
return scrub(error instanceof Error ? error.message : String(error), url);
|
|
1921
2119
|
}
|
|
1922
|
-
async function readRows(url, statement, params = [], limit, connect = bunConnect) {
|
|
2120
|
+
async function readRows(url, statement, params = [], limit, connect = bunConnect, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
1923
2121
|
const dialect = dialectOf(new URL(url));
|
|
1924
|
-
const session = connect(url, dialect, true);
|
|
2122
|
+
const session = connect(url, dialect, true, timeoutMs);
|
|
1925
2123
|
let rows = [];
|
|
1926
2124
|
try {
|
|
1927
2125
|
await session.transaction(async (tx) => {
|
|
@@ -1982,7 +2180,7 @@ var usage2 = `db query "<sql>"
|
|
|
1982
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.
|
|
1983
2181
|
|
|
1984
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.
|
|
1985
|
-
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.
|
|
1986
2184
|
|
|
1987
2185
|
${WRITE_NOTE}
|
|
1988
2186
|
|
|
@@ -2029,39 +2227,55 @@ async function query(args) {
|
|
|
2029
2227
|
console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
|
|
2030
2228
|
else
|
|
2031
2229
|
console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
|
|
2032
|
-
${render(shown, false)}`}`);
|
|
2230
|
+
${render(shown, false, values.format)}`}`);
|
|
2033
2231
|
return 0;
|
|
2034
2232
|
}
|
|
2035
2233
|
if (verdict.statements > 1)
|
|
2036
2234
|
fail("one statement at a time");
|
|
2037
|
-
const rows = await readRows(url, sql, [], limit);
|
|
2038
|
-
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));
|
|
2039
2237
|
return 0;
|
|
2040
2238
|
}
|
|
2041
2239
|
|
|
2042
2240
|
// src/commands/explain.ts
|
|
2043
|
-
var usage3 = `db explain "<sql>"
|
|
2241
|
+
var usage3 = `db explain "<sql>" [--analyze]
|
|
2044
2242
|
|
|
2045
|
-
Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone
|
|
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.
|
|
2046
2245
|
|
|
2047
2246
|
${HOSTS_NOTE}`;
|
|
2048
|
-
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" } };
|
|
2049
2248
|
var READ_START = /^\s*(?:select|with|values|table)\b/i;
|
|
2050
2249
|
var TRAILING_SEMICOLON = /;\s*$/;
|
|
2051
|
-
|
|
2250
|
+
var MARIADB = /mariadb/i;
|
|
2251
|
+
var MYSQL_VERSION = /^(\d+)\.(\d+)\.(\d+)/;
|
|
2252
|
+
function explainSql(sql, dialect, prefix = "EXPLAIN") {
|
|
2052
2253
|
const verdict = inspect(sql, dialect);
|
|
2053
2254
|
if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2054
2255
|
fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
|
|
2055
|
-
return
|
|
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}`);
|
|
2056
2265
|
}
|
|
2057
2266
|
async function explain(args) {
|
|
2058
2267
|
const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
|
|
2059
2268
|
const sql = await readSql(positionals);
|
|
2060
2269
|
const url = await connectionUrl(values);
|
|
2061
2270
|
const dialect = dialectOf(new URL(url));
|
|
2062
|
-
const
|
|
2063
|
-
|
|
2064
|
-
|
|
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(`
|
|
2065
2279
|
`));
|
|
2066
2280
|
else
|
|
2067
2281
|
console.log(render(shape(rows, rows.length, true), values.json === true));
|
|
@@ -2162,8 +2376,8 @@ async function show(args, usage, work) {
|
|
|
2162
2376
|
const limit = rowLimit(values);
|
|
2163
2377
|
const url = await connectionUrl(values);
|
|
2164
2378
|
const { sql, params } = plans[dialectOf(new URL(url))];
|
|
2165
|
-
const rows = await readRows(url, sql, params, limit);
|
|
2166
|
-
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));
|
|
2167
2381
|
return 0;
|
|
2168
2382
|
}
|
|
2169
2383
|
async function tables(args) {
|
|
@@ -2226,20 +2440,20 @@ ${HOSTS_NOTE}`;
|
|
|
2226
2440
|
const limit = rowLimit(values);
|
|
2227
2441
|
const url = await connectionUrl(values);
|
|
2228
2442
|
const dialect = dialectOf(new URL(url));
|
|
2229
|
-
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));
|
|
2230
2444
|
const columns = shape(await ask(plans.columns, limit), limit, true, false);
|
|
2231
2445
|
const indexes = await ask(plans.indexes);
|
|
2232
2446
|
const foreignKeys = await ask(plans.foreignKeys);
|
|
2233
2447
|
if (values.json === true)
|
|
2234
2448
|
console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
|
|
2235
2449
|
else
|
|
2236
|
-
console.log(`${render(columns, false)}
|
|
2450
|
+
console.log(`${render(columns, false, values.format)}
|
|
2237
2451
|
|
|
2238
2452
|
indexes
|
|
2239
|
-
${render(shape(indexes, indexes.length, true), false)}
|
|
2453
|
+
${render(shape(indexes, indexes.length, true), false, values.format)}
|
|
2240
2454
|
|
|
2241
2455
|
foreign keys
|
|
2242
|
-
${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
|
|
2456
|
+
${render(shape(foreignKeys, foreignKeys.length, true), false, values.format)}`);
|
|
2243
2457
|
return 0;
|
|
2244
2458
|
}
|
|
2245
2459
|
|
|
@@ -2261,7 +2475,7 @@ function countSql(target, dialect, where) {
|
|
|
2261
2475
|
}
|
|
2262
2476
|
var where = { type: "string", short: "w", description: "only the rows matching this SQL condition" };
|
|
2263
2477
|
var sampleOptions = { ...connectionOptions, ...outputOptions, where };
|
|
2264
|
-
var countOptions = { ...connectionOptions, json: outputOptions.json, where };
|
|
2478
|
+
var countOptions = { ...connectionOptions, json: outputOptions.json, format: outputOptions.format, where };
|
|
2265
2479
|
async function run(args, usage, options, build) {
|
|
2266
2480
|
const parsed = parse(args, usage, options, { exits: EXITS });
|
|
2267
2481
|
const { values, positionals } = parsed;
|
|
@@ -2275,7 +2489,7 @@ async function run(args, usage, options, build) {
|
|
|
2275
2489
|
const verdict = inspect(sql, dialect);
|
|
2276
2490
|
if (verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2277
2491
|
fail(`not a plain read: ${verdict.reasons.join("; ") || "one statement at a time"}`);
|
|
2278
|
-
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));
|
|
2279
2493
|
return 0;
|
|
2280
2494
|
}
|
|
2281
2495
|
async function sample(args) {
|
|
@@ -2294,17 +2508,17 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
|
|
|
2294
2508
|
}
|
|
2295
2509
|
|
|
2296
2510
|
// src/cli.ts
|
|
2297
|
-
|
|
2511
|
+
process18.exitCode = await runCli({
|
|
2298
2512
|
name: "db",
|
|
2299
2513
|
about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
|
|
2300
2514
|
replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
|
|
2301
|
-
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"]],
|
|
2302
2516
|
commands: {
|
|
2303
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' },
|
|
2304
2518
|
tables: { run: tables, summary: "list tables and views with an estimated row count" },
|
|
2305
2519
|
describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
|
|
2306
2520
|
search: { run: search, summary: "find the tables and columns whose name contains a text" },
|
|
2307
|
-
explain: { run: explain, summary: "the plan of one read
|
|
2521
|
+
explain: { run: explain, summary: "the plan of one read, run and timed with --analyze (in the rolled-back read-only transaction)" },
|
|
2308
2522
|
sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
|
|
2309
2523
|
count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
|
|
2310
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.
|
|
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.
|
|
31
|
+
"@kaynooo/cli-kit": "0.41.0"
|
|
32
32
|
}
|
|
33
33
|
}
|