@kaynooo/cli-db 0.12.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/cli.js +225 -90
- 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)
|
|
@@ -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,33 @@ 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/notify.ts
|
|
831
893
|
import process13 from "process";
|
|
894
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
895
|
+
var CANCELLED = 130;
|
|
896
|
+
function base64(text) {
|
|
897
|
+
return Buffer.from(text).toString("base64");
|
|
898
|
+
}
|
|
899
|
+
function notification(title, body, env = process13.env) {
|
|
900
|
+
const id = `kit${process13.pid}`;
|
|
901
|
+
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\\`];
|
|
902
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
903
|
+
}
|
|
904
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
905
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
906
|
+
return;
|
|
907
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
908
|
+
}
|
|
832
909
|
|
|
833
910
|
// ../kit/src/usage.ts
|
|
834
911
|
import { appendFileSync, mkdirSync } from "fs";
|
|
835
912
|
import { homedir as homedir3 } from "os";
|
|
836
913
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
837
|
-
import
|
|
914
|
+
import process14 from "process";
|
|
838
915
|
|
|
839
916
|
// ../kit/src/logs.ts
|
|
840
917
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -848,14 +925,14 @@ var usageError;
|
|
|
848
925
|
function noteUsageError(message) {
|
|
849
926
|
usageError = message;
|
|
850
927
|
}
|
|
851
|
-
function stateHome(env =
|
|
928
|
+
function stateHome(env = process14.env) {
|
|
852
929
|
const dir = env.XDG_STATE_HOME;
|
|
853
930
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
854
931
|
}
|
|
855
|
-
function usagePath(env =
|
|
932
|
+
function usagePath(env = process14.env) {
|
|
856
933
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
857
934
|
}
|
|
858
|
-
function usageRecorded(env =
|
|
935
|
+
function usageRecorded(env = process14.env) {
|
|
859
936
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
860
937
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
861
938
|
}
|
|
@@ -869,7 +946,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
869
946
|
usageError = undefined;
|
|
870
947
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
871
948
|
}
|
|
872
|
-
function recordUsage(entry, env =
|
|
949
|
+
function recordUsage(entry, env = process14.env) {
|
|
873
950
|
if (!usageRecorded(env))
|
|
874
951
|
return;
|
|
875
952
|
try {
|
|
@@ -946,7 +1023,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
946
1023
|
header(colors, summary),
|
|
947
1024
|
"",
|
|
948
1025
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
949
|
-
...replacesRows(replaces, colors),
|
|
950
1026
|
"",
|
|
951
1027
|
...await commandRows(commands, colors),
|
|
952
1028
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -960,8 +1036,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
960
1036
|
`);
|
|
961
1037
|
}
|
|
962
1038
|
function printError(prefix, message, hint, cause) {
|
|
963
|
-
const colors = paint(
|
|
964
|
-
const styled = takesControlCodes(
|
|
1039
|
+
const colors = paint(process15.stderr);
|
|
1040
|
+
const styled = takesControlCodes(process15.stderr);
|
|
965
1041
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
966
1042
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
967
1043
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -1004,11 +1080,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
1004
1080
|
}
|
|
1005
1081
|
}
|
|
1006
1082
|
if (name === undefined && level.path.length > 1) {
|
|
1007
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1083
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stderr));
|
|
1008
1084
|
return 2;
|
|
1009
1085
|
}
|
|
1010
1086
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1011
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1087
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process15.stdout));
|
|
1012
1088
|
return 0;
|
|
1013
1089
|
}
|
|
1014
1090
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1064,24 +1140,24 @@ function candidateLine(candidate) {
|
|
|
1064
1140
|
}
|
|
1065
1141
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1066
1142
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1067
|
-
|
|
1143
|
+
const typed = [];
|
|
1068
1144
|
let at = 0;
|
|
1069
1145
|
while (at < before.length) {
|
|
1070
1146
|
const word = before[at];
|
|
1071
1147
|
if (word === "--") {
|
|
1072
|
-
|
|
1148
|
+
typed.push(...before.slice(at + 1));
|
|
1073
1149
|
break;
|
|
1074
1150
|
}
|
|
1075
1151
|
if (!word.startsWith("-"))
|
|
1076
|
-
|
|
1152
|
+
typed.push(word);
|
|
1077
1153
|
else if (takesValue(word))
|
|
1078
1154
|
at++;
|
|
1079
1155
|
at++;
|
|
1080
1156
|
}
|
|
1081
1157
|
const last = positionals.at(-1);
|
|
1082
|
-
if (
|
|
1083
|
-
return positionals[
|
|
1084
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1158
|
+
if (typed.length < positionals.length)
|
|
1159
|
+
return { name: positionals[typed.length], typed };
|
|
1160
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1085
1161
|
}
|
|
1086
1162
|
async function leafCandidates(run, words) {
|
|
1087
1163
|
const completing = await completingOf(run);
|
|
@@ -1089,12 +1165,12 @@ async function leafCandidates(run, words) {
|
|
|
1089
1165
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1090
1166
|
const flag = words.at(-2);
|
|
1091
1167
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1168
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1092
1169
|
if (option?.type === "string") {
|
|
1093
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1170
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1094
1171
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1095
1172
|
}
|
|
1096
|
-
const
|
|
1097
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1173
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1098
1174
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1099
1175
|
}
|
|
1100
1176
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1125,9 +1201,13 @@ async function printCandidates(found) {
|
|
|
1125
1201
|
return 0;
|
|
1126
1202
|
}
|
|
1127
1203
|
function packageVersion(entry = Bun.main) {
|
|
1128
|
-
|
|
1204
|
+
let resolved = entry;
|
|
1205
|
+
try {
|
|
1206
|
+
resolved = realpathSync2(entry);
|
|
1207
|
+
} catch {}
|
|
1208
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1129
1209
|
try {
|
|
1130
|
-
const { version } = JSON.parse(
|
|
1210
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1131
1211
|
if (typeof version === "string")
|
|
1132
1212
|
return version;
|
|
1133
1213
|
} catch {}
|
|
@@ -1135,14 +1215,17 @@ function packageVersion(entry = Bun.main) {
|
|
|
1135
1215
|
return "0.0.0";
|
|
1136
1216
|
}
|
|
1137
1217
|
}
|
|
1138
|
-
async function runCli(cli, argv =
|
|
1218
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1139
1219
|
const version = cli.version ?? packageVersion();
|
|
1140
1220
|
if (argv[0] === COMPLETE)
|
|
1141
1221
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1222
|
+
const started = performance.now();
|
|
1142
1223
|
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 });
|
|
1224
|
+
const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
|
|
1225
|
+
notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
|
|
1143
1226
|
if (cli.usage !== false) {
|
|
1144
1227
|
try {
|
|
1145
|
-
recordUsage(usageEntry(cli.name,
|
|
1228
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1146
1229
|
} catch {}
|
|
1147
1230
|
}
|
|
1148
1231
|
return code;
|
|
@@ -1194,6 +1277,7 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
|
1194
1277
|
// src/args.ts
|
|
1195
1278
|
var DEFAULT_ENV = "DATABASE_URL";
|
|
1196
1279
|
var DEFAULT_LIMIT = 20;
|
|
1280
|
+
var DEFAULT_TIMEOUT_MS = 30000;
|
|
1197
1281
|
var ALL_LIMIT = 100;
|
|
1198
1282
|
var WRITE_EXIT = 1;
|
|
1199
1283
|
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 +1287,30 @@ var connectionOptions = {
|
|
|
1203
1287
|
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
1288
|
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
1289
|
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" }
|
|
1290
|
+
database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" },
|
|
1291
|
+
timeout: { type: "string", description: `stop a statement after this long, a duration such as 500ms, 30s or 2m (${DEFAULT_TIMEOUT_MS / 1000}s)` }
|
|
1207
1292
|
};
|
|
1293
|
+
function statementTimeout(values) {
|
|
1294
|
+
return Math.ceil(duration(values.timeout, "timeout", DEFAULT_TIMEOUT_MS));
|
|
1295
|
+
}
|
|
1208
1296
|
var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
|
|
1209
1297
|
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
1298
|
function rowLimit(values, fallback = DEFAULT_LIMIT) {
|
|
1211
1299
|
return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
|
|
1212
1300
|
}
|
|
1301
|
+
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
1302
|
var catalogOptions = {
|
|
1214
1303
|
rows,
|
|
1215
1304
|
all,
|
|
1216
|
-
json: jsonOption()
|
|
1305
|
+
json: jsonOption(),
|
|
1306
|
+
format: format2
|
|
1217
1307
|
};
|
|
1218
1308
|
var outputOptions = {
|
|
1219
1309
|
rows,
|
|
1220
1310
|
all,
|
|
1221
1311
|
raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
|
|
1222
|
-
json: jsonOption()
|
|
1312
|
+
json: jsonOption(),
|
|
1313
|
+
format: format2
|
|
1223
1314
|
};
|
|
1224
1315
|
|
|
1225
1316
|
// src/sql-tokens.ts
|
|
@@ -1556,28 +1647,57 @@ function shape(rows, limit, raw, exact = true) {
|
|
|
1556
1647
|
const { rows: masked, masked: columns } = maskRows(rows.slice(0, limit), raw);
|
|
1557
1648
|
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
1649
|
}
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
const
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1650
|
+
var TSV_ESCAPES = { "\\": "\\\\", "\t": "\\t", "\n": "\\n", "\r": "\\r" };
|
|
1651
|
+
var TSV_SPECIALS = /[\\\t\n\r]/g;
|
|
1652
|
+
var CSV_SPECIALS = /["\r\n,]/;
|
|
1653
|
+
var tsvCell = (value) => cell(value).replace(TSV_SPECIALS, (char) => TSV_ESCAPES[char] ?? char);
|
|
1654
|
+
function csvCell(value) {
|
|
1655
|
+
const text = cell(value);
|
|
1656
|
+
return CSV_SPECIALS.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
1657
|
+
}
|
|
1658
|
+
function vertical(shown) {
|
|
1659
|
+
const width = Math.max(...shown.columns.map((column) => column.length));
|
|
1660
|
+
return shown.rows.map((row, index) => [`-[ RECORD ${index + 1} ]`, ...shown.columns.map((column) => `${column.padEnd(width)} | ${cell(row[column])}`)].join(`
|
|
1661
|
+
`)).join(`
|
|
1662
|
+
`);
|
|
1663
|
+
}
|
|
1664
|
+
function notes(shown) {
|
|
1665
|
+
const lines = [];
|
|
1568
1666
|
if (shown.truncated && !shown.exact)
|
|
1569
1667
|
lines.push("... more rows not shown (-n raises the cap)");
|
|
1570
1668
|
else if (shown.truncated)
|
|
1571
1669
|
lines.push(`... ${shown.omitted} more ${shown.omitted === 1 ? "row" : "rows"} not shown (${shown.total} in all, -n raises the cap)`);
|
|
1572
1670
|
if (shown.masked.length > 0)
|
|
1573
1671
|
lines.push(`masked: ${shown.masked.join(", ")} (--raw shows them)`);
|
|
1574
|
-
return lines
|
|
1672
|
+
return lines;
|
|
1673
|
+
}
|
|
1674
|
+
function delimited(shown, format) {
|
|
1675
|
+
const [separator, escape] = format === "tsv" ? ["\t", tsvCell] : [",", csvCell];
|
|
1676
|
+
for (const note of notes(shown))
|
|
1677
|
+
warn(note);
|
|
1678
|
+
return [shown.columns, ...shown.rows.map((row) => shown.columns.map((column) => row[column]))].map((line) => line.map(escape).join(separator)).join(`
|
|
1679
|
+
`);
|
|
1680
|
+
}
|
|
1681
|
+
function render(shown, json, format) {
|
|
1682
|
+
if (json)
|
|
1683
|
+
return jsonText({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue);
|
|
1684
|
+
if (shown.total === 0)
|
|
1685
|
+
return format === "tsv" || format === "csv" ? "" : "no rows";
|
|
1686
|
+
if (format === "tsv" || format === "csv")
|
|
1687
|
+
return delimited(shown, format);
|
|
1688
|
+
if (format === "vertical")
|
|
1689
|
+
return [vertical(shown), ...notes(shown)].join(`
|
|
1690
|
+
`);
|
|
1691
|
+
return [table([
|
|
1692
|
+
shown.columns,
|
|
1693
|
+
...shown.rows.map((row) => shown.columns.map((column) => cell(row[column])))
|
|
1694
|
+
], { cellWidth: CELL_WIDTH }), ...notes(shown)].join(`
|
|
1575
1695
|
`);
|
|
1576
1696
|
}
|
|
1577
1697
|
|
|
1578
1698
|
// src/run.ts
|
|
1579
1699
|
import { isIP } from "net";
|
|
1580
|
-
import
|
|
1700
|
+
import process17 from "process";
|
|
1581
1701
|
var {SQL } = globalThis.Bun;
|
|
1582
1702
|
|
|
1583
1703
|
// src/compose.ts
|
|
@@ -1760,7 +1880,6 @@ async function loadSettings(home) {
|
|
|
1760
1880
|
}
|
|
1761
1881
|
|
|
1762
1882
|
// src/run.ts
|
|
1763
|
-
var STATEMENT_TIMEOUT = "30s";
|
|
1764
1883
|
var SESSION_SETTINGS = { lock_timeout: "5s", idle_in_transaction_session_timeout: "60s" };
|
|
1765
1884
|
var CURSOR = "db_rows";
|
|
1766
1885
|
var CURSOR_STARTS = /^\s*(?:select|with|values|table)\b/i;
|
|
@@ -1771,7 +1890,7 @@ var BRACKETS = /^\[|\]$/g;
|
|
|
1771
1890
|
var POSTGRES_SCHEMES = new Set(["postgres:", "postgresql:"]);
|
|
1772
1891
|
var MYSQL_SCHEMES = new Set(["mysql:", "mysql2:", "mariadb:"]);
|
|
1773
1892
|
var WRAP_ERRNOS = new Set([1064, 1060]);
|
|
1774
|
-
var
|
|
1893
|
+
var mysqlTimeouts = (ms) => [`SET SESSION max_execution_time = ${ms}`, `SET SESSION max_statement_time = ${ms / 1000}`];
|
|
1775
1894
|
var TEST_SUFFIX = "_test";
|
|
1776
1895
|
|
|
1777
1896
|
class Rollback extends Error {
|
|
@@ -1832,7 +1951,7 @@ async function connectionUrl({ env, service, container, database }, home) {
|
|
|
1832
1951
|
if (service !== undefined && container !== undefined)
|
|
1833
1952
|
fail("--service and --container name two databases: pick one");
|
|
1834
1953
|
const isNamed = service !== undefined || container !== undefined;
|
|
1835
|
-
const value = isNamed ? undefined :
|
|
1954
|
+
const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
|
|
1836
1955
|
let url;
|
|
1837
1956
|
if (value !== undefined && value !== "")
|
|
1838
1957
|
url = await reachable(value, home);
|
|
@@ -1857,13 +1976,13 @@ function databaseOfUrl(url) {
|
|
|
1857
1976
|
function toResult(rows) {
|
|
1858
1977
|
return Object.assign([...rows], { affected: rows.count ?? rows.affectedRows ?? rows.length });
|
|
1859
1978
|
}
|
|
1860
|
-
var bunConnect = (url, dialect, readOnly) => {
|
|
1979
|
+
var bunConnect = (url, dialect, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) => {
|
|
1861
1980
|
const sql = new SQL({ url, max: 1, connectionTimeout: 10, ...dialect === "postgres" ? { connection: { ...SESSION_SETTINGS, ...readOnly ? { default_transaction_read_only: "on" } : {} } } : { allowPublicKeyRetrieval: allowsKeyRetrieval(url) } });
|
|
1862
1981
|
return {
|
|
1863
1982
|
async transaction(work, isReadOnly) {
|
|
1864
1983
|
if (dialect === "postgres") {
|
|
1865
1984
|
const body = async (tx) => {
|
|
1866
|
-
await tx.unsafe(`SET LOCAL statement_timeout = '${
|
|
1985
|
+
await tx.unsafe(`SET LOCAL statement_timeout = '${timeoutMs}ms'`);
|
|
1867
1986
|
await work({ unsafe: async (statement, params) => toResult(await tx.unsafe(statement, params)) });
|
|
1868
1987
|
};
|
|
1869
1988
|
await (isReadOnly ? sql.begin("read only", body) : sql.begin(body));
|
|
@@ -1871,7 +1990,7 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1871
1990
|
}
|
|
1872
1991
|
const connection = await sql.reserve();
|
|
1873
1992
|
try {
|
|
1874
|
-
await mysqlTransaction({ unsafe: async (statement, params) => connection.unsafe(statement, params) }, work, isReadOnly);
|
|
1993
|
+
await mysqlTransaction({ unsafe: async (statement, params) => connection.unsafe(statement, params) }, work, isReadOnly, timeoutMs);
|
|
1875
1994
|
} finally {
|
|
1876
1995
|
await connection.release();
|
|
1877
1996
|
}
|
|
@@ -1881,8 +2000,8 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1881
2000
|
}
|
|
1882
2001
|
};
|
|
1883
2002
|
};
|
|
1884
|
-
async function mysqlTransaction(connection, work, readOnly) {
|
|
1885
|
-
for (const timeout of
|
|
2003
|
+
async function mysqlTransaction(connection, work, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
2004
|
+
for (const timeout of mysqlTimeouts(timeoutMs)) {
|
|
1886
2005
|
try {
|
|
1887
2006
|
await connection.unsafe(timeout);
|
|
1888
2007
|
} catch {}
|
|
@@ -1919,9 +2038,9 @@ ${statement.replace(TRAILING_SEMICOLONS, "")}
|
|
|
1919
2038
|
function messageOf(error, url) {
|
|
1920
2039
|
return scrub(error instanceof Error ? error.message : String(error), url);
|
|
1921
2040
|
}
|
|
1922
|
-
async function readRows(url, statement, params = [], limit, connect = bunConnect) {
|
|
2041
|
+
async function readRows(url, statement, params = [], limit, connect = bunConnect, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
1923
2042
|
const dialect = dialectOf(new URL(url));
|
|
1924
|
-
const session = connect(url, dialect, true);
|
|
2043
|
+
const session = connect(url, dialect, true, timeoutMs);
|
|
1925
2044
|
let rows = [];
|
|
1926
2045
|
try {
|
|
1927
2046
|
await session.transaction(async (tx) => {
|
|
@@ -1982,7 +2101,7 @@ var usage2 = `db query "<sql>"
|
|
|
1982
2101
|
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
2102
|
|
|
1984
2103
|
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.
|
|
2104
|
+
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
2105
|
|
|
1987
2106
|
${WRITE_NOTE}
|
|
1988
2107
|
|
|
@@ -2029,39 +2148,55 @@ async function query(args) {
|
|
|
2029
2148
|
console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
|
|
2030
2149
|
else
|
|
2031
2150
|
console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
|
|
2032
|
-
${render(shown, false)}`}`);
|
|
2151
|
+
${render(shown, false, values.format)}`}`);
|
|
2033
2152
|
return 0;
|
|
2034
2153
|
}
|
|
2035
2154
|
if (verdict.statements > 1)
|
|
2036
2155
|
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));
|
|
2156
|
+
const rows = await readRows(url, sql, [], limit, undefined, statementTimeout(values));
|
|
2157
|
+
console.log(render(shape(rows, limit, values.raw === true, false), values.json === true, values.format));
|
|
2039
2158
|
return 0;
|
|
2040
2159
|
}
|
|
2041
2160
|
|
|
2042
2161
|
// src/commands/explain.ts
|
|
2043
|
-
var usage3 = `db explain "<sql>"
|
|
2162
|
+
var usage3 = `db explain "<sql>" [--analyze]
|
|
2044
2163
|
|
|
2045
|
-
Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone
|
|
2164
|
+
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.
|
|
2165
|
+
--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
2166
|
|
|
2047
2167
|
${HOSTS_NOTE}`;
|
|
2048
|
-
var options2 = { ...connectionOptions, json: jsonOption() };
|
|
2168
|
+
var options2 = { ...connectionOptions, json: jsonOption(), analyze: { type: "boolean", description: "run the read to time it, in the transaction that is rolled back" } };
|
|
2049
2169
|
var READ_START = /^\s*(?:select|with|values|table)\b/i;
|
|
2050
2170
|
var TRAILING_SEMICOLON = /;\s*$/;
|
|
2051
|
-
|
|
2171
|
+
var MARIADB = /mariadb/i;
|
|
2172
|
+
var MYSQL_VERSION = /^(\d+)\.(\d+)\.(\d+)/;
|
|
2173
|
+
function explainSql(sql, dialect, prefix = "EXPLAIN") {
|
|
2052
2174
|
const verdict = inspect(sql, dialect);
|
|
2053
2175
|
if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2054
2176
|
fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
|
|
2055
|
-
return
|
|
2177
|
+
return `${prefix} ${sql.trim().replace(TRAILING_SEMICOLON, "")}`;
|
|
2178
|
+
}
|
|
2179
|
+
function analyzePrefix(version) {
|
|
2180
|
+
if (MARIADB.test(version))
|
|
2181
|
+
return "ANALYZE";
|
|
2182
|
+
const [, major = 0, minor = 0, patch = 0] = MYSQL_VERSION.exec(version)?.map(Number) ?? [];
|
|
2183
|
+
if (major > 8 || major === 8 && (minor > 0 || patch >= 18))
|
|
2184
|
+
return "EXPLAIN ANALYZE";
|
|
2185
|
+
return fail(`--analyze needs MySQL 8.0.18 or later or MariaDB, this server is ${version}`);
|
|
2056
2186
|
}
|
|
2057
2187
|
async function explain(args) {
|
|
2058
2188
|
const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
|
|
2059
2189
|
const sql = await readSql(positionals);
|
|
2060
2190
|
const url = await connectionUrl(values);
|
|
2061
2191
|
const dialect = dialectOf(new URL(url));
|
|
2062
|
-
const
|
|
2063
|
-
|
|
2064
|
-
|
|
2192
|
+
const timeout = statementTimeout(values);
|
|
2193
|
+
let prefix = "EXPLAIN";
|
|
2194
|
+
if (values.analyze === true)
|
|
2195
|
+
prefix = dialect === "postgres" ? "EXPLAIN ANALYZE" : analyzePrefix(String((await readRows(url, "select version() as version", [], undefined, undefined, timeout))[0]?.version));
|
|
2196
|
+
const rows = await readRows(url, explainSql(sql, dialect, prefix), [], undefined, undefined, timeout);
|
|
2197
|
+
const [only, ...others] = Object.keys(rows[0] ?? {});
|
|
2198
|
+
if (values.json !== true && only !== undefined && others.length === 0)
|
|
2199
|
+
console.log(rows.map((row) => String(row[only])).join(`
|
|
2065
2200
|
`));
|
|
2066
2201
|
else
|
|
2067
2202
|
console.log(render(shape(rows, rows.length, true), values.json === true));
|
|
@@ -2162,8 +2297,8 @@ async function show(args, usage, work) {
|
|
|
2162
2297
|
const limit = rowLimit(values);
|
|
2163
2298
|
const url = await connectionUrl(values);
|
|
2164
2299
|
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));
|
|
2300
|
+
const rows = await readRows(url, sql, params, limit, undefined, statementTimeout(values));
|
|
2301
|
+
console.log(render(shape(rows, limit, true, false), values.json === true, values.format));
|
|
2167
2302
|
return 0;
|
|
2168
2303
|
}
|
|
2169
2304
|
async function tables(args) {
|
|
@@ -2226,20 +2361,20 @@ ${HOSTS_NOTE}`;
|
|
|
2226
2361
|
const limit = rowLimit(values);
|
|
2227
2362
|
const url = await connectionUrl(values);
|
|
2228
2363
|
const dialect = dialectOf(new URL(url));
|
|
2229
|
-
const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap);
|
|
2364
|
+
const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap, undefined, statementTimeout(values));
|
|
2230
2365
|
const columns = shape(await ask(plans.columns, limit), limit, true, false);
|
|
2231
2366
|
const indexes = await ask(plans.indexes);
|
|
2232
2367
|
const foreignKeys = await ask(plans.foreignKeys);
|
|
2233
2368
|
if (values.json === true)
|
|
2234
2369
|
console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
|
|
2235
2370
|
else
|
|
2236
|
-
console.log(`${render(columns, false)}
|
|
2371
|
+
console.log(`${render(columns, false, values.format)}
|
|
2237
2372
|
|
|
2238
2373
|
indexes
|
|
2239
|
-
${render(shape(indexes, indexes.length, true), false)}
|
|
2374
|
+
${render(shape(indexes, indexes.length, true), false, values.format)}
|
|
2240
2375
|
|
|
2241
2376
|
foreign keys
|
|
2242
|
-
${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
|
|
2377
|
+
${render(shape(foreignKeys, foreignKeys.length, true), false, values.format)}`);
|
|
2243
2378
|
return 0;
|
|
2244
2379
|
}
|
|
2245
2380
|
|
|
@@ -2261,7 +2396,7 @@ function countSql(target, dialect, where) {
|
|
|
2261
2396
|
}
|
|
2262
2397
|
var where = { type: "string", short: "w", description: "only the rows matching this SQL condition" };
|
|
2263
2398
|
var sampleOptions = { ...connectionOptions, ...outputOptions, where };
|
|
2264
|
-
var countOptions = { ...connectionOptions, json: outputOptions.json, where };
|
|
2399
|
+
var countOptions = { ...connectionOptions, json: outputOptions.json, format: outputOptions.format, where };
|
|
2265
2400
|
async function run(args, usage, options, build) {
|
|
2266
2401
|
const parsed = parse(args, usage, options, { exits: EXITS });
|
|
2267
2402
|
const { values, positionals } = parsed;
|
|
@@ -2275,7 +2410,7 @@ async function run(args, usage, options, build) {
|
|
|
2275
2410
|
const verdict = inspect(sql, dialect);
|
|
2276
2411
|
if (verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2277
2412
|
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));
|
|
2413
|
+
console.log(render(shape(await readRows(url, sql, [], limit, undefined, statementTimeout(values)), limit, values.raw === true, false), values.json === true, values.format));
|
|
2279
2414
|
return 0;
|
|
2280
2415
|
}
|
|
2281
2416
|
async function sample(args) {
|
|
@@ -2294,17 +2429,17 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
|
|
|
2294
2429
|
}
|
|
2295
2430
|
|
|
2296
2431
|
// src/cli.ts
|
|
2297
|
-
|
|
2432
|
+
process18.exitCode = await runCli({
|
|
2298
2433
|
name: "db",
|
|
2299
2434
|
about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
|
|
2300
2435
|
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"]],
|
|
2436
|
+
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
2437
|
commands: {
|
|
2303
2438
|
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
2439
|
tables: { run: tables, summary: "list tables and views with an estimated row count" },
|
|
2305
2440
|
describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
|
|
2306
2441
|
search: { run: search, summary: "find the tables and columns whose name contains a text" },
|
|
2307
|
-
explain: { run: explain, summary: "the plan of one read
|
|
2442
|
+
explain: { run: explain, summary: "the plan of one read, run and timed with --analyze (in the rolled-back read-only transaction)" },
|
|
2308
2443
|
sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
|
|
2309
2444
|
count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
|
|
2310
2445
|
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.0",
|
|
5
5
|
"description": "db: run read-only SQL against Postgres, MySQL and MariaDB from the terminal without ever showing the connection credentials.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -28,6 +28,6 @@
|
|
|
28
28
|
"db": "$npm_execpath src/cli.ts"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@kaynooo/cli-kit": "0.
|
|
31
|
+
"@kaynooo/cli-kit": "0.39.0"
|
|
32
32
|
}
|
|
33
33
|
}
|