@kaynooo/cli-db 0.12.0 → 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 +245 -106
- 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,13 +2,14 @@
|
|
|
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";
|
|
9
9
|
|
|
10
10
|
// ../kit/src/format.ts
|
|
11
11
|
import process7 from "process";
|
|
12
|
+
|
|
12
13
|
// ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
|
|
13
14
|
var N = new Map;
|
|
14
15
|
var Nt = /\s+\S*$/;
|
|
@@ -26,6 +27,7 @@ function ko(t, e, r = "...") {
|
|
|
26
27
|
}
|
|
27
28
|
var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
|
|
28
29
|
var z = new Map;
|
|
30
|
+
|
|
29
31
|
// ../kit/src/mode.ts
|
|
30
32
|
import process2 from "process";
|
|
31
33
|
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
@@ -71,7 +73,7 @@ function C(r, e = globalThis.process?.env ?? {}) {
|
|
|
71
73
|
return false;
|
|
72
74
|
return r?.isTTY === true;
|
|
73
75
|
}
|
|
74
|
-
function
|
|
76
|
+
function f(r, e = []) {
|
|
75
77
|
let l = "", n = "";
|
|
76
78
|
for (let t = 0, i = e.length;t < i; t++)
|
|
77
79
|
l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
|
|
@@ -81,7 +83,7 @@ function f2(r, e = []) {
|
|
|
81
83
|
if (Array.isArray(a)) {
|
|
82
84
|
let s = g.get(i);
|
|
83
85
|
if (s === undefined)
|
|
84
|
-
s =
|
|
86
|
+
s = f(r, [...e, a]), g.set(i, s);
|
|
85
87
|
return s;
|
|
86
88
|
}
|
|
87
89
|
if (typeof a === "function")
|
|
@@ -90,20 +92,20 @@ function f2(r, e = []) {
|
|
|
90
92
|
if (u === undefined) {
|
|
91
93
|
if (g.size >= 64)
|
|
92
94
|
g.clear();
|
|
93
|
-
u =
|
|
95
|
+
u = f(r, [...e, a(...s)]), g.set(y, u);
|
|
94
96
|
}
|
|
95
97
|
return u;
|
|
96
98
|
};
|
|
97
99
|
throw Error(`Unknown style: ${String(i)}`);
|
|
98
100
|
} });
|
|
99
101
|
}
|
|
100
|
-
function
|
|
101
|
-
return
|
|
102
|
+
function Fe(r = {}) {
|
|
103
|
+
return f(r);
|
|
102
104
|
}
|
|
103
|
-
var
|
|
105
|
+
var o = Fe();
|
|
104
106
|
|
|
105
107
|
// ../kit/src/theme.ts
|
|
106
|
-
import { existsSync as existsSync3, readFileSync, statSync } from "fs";
|
|
108
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
|
|
107
109
|
import { homedir as homedir2 } from "os";
|
|
108
110
|
import { join as join3, resolve as resolve2 } from "path";
|
|
109
111
|
import process5 from "process";
|
|
@@ -124,7 +126,7 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
|
124
126
|
}
|
|
125
127
|
|
|
126
128
|
// ../kit/src/user-config.ts
|
|
127
|
-
import { existsSync as existsSync2 } from "fs";
|
|
129
|
+
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
128
130
|
import { homedir } from "os";
|
|
129
131
|
import { join as join2 } from "path";
|
|
130
132
|
import process4 from "process";
|
|
@@ -208,7 +210,7 @@ function readThemeFile(path, warn) {
|
|
|
208
210
|
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
209
211
|
return;
|
|
210
212
|
}
|
|
211
|
-
const parsed = JSON.parse(
|
|
213
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
212
214
|
if (isRecord(parsed))
|
|
213
215
|
return parsed;
|
|
214
216
|
warn(`${path} is not a JSON object, theme ignored`);
|
|
@@ -330,7 +332,7 @@ function takesControlCodes(stream, env = process6.env) {
|
|
|
330
332
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
331
333
|
}
|
|
332
334
|
function paint(stream, env = process6.env) {
|
|
333
|
-
return
|
|
335
|
+
return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
334
336
|
}
|
|
335
337
|
function marked(mark, text, stream, detail, env = process6.env) {
|
|
336
338
|
const colors = paint(stream, env);
|
|
@@ -344,6 +346,9 @@ function marked(mark, text, stream, detail, env = process6.env) {
|
|
|
344
346
|
function warn(text, detail) {
|
|
345
347
|
console.error(marked("warn", text, process6.stderr, detail));
|
|
346
348
|
}
|
|
349
|
+
function problem(text, detail) {
|
|
350
|
+
console.error(marked("problem", text, process6.stderr, detail));
|
|
351
|
+
}
|
|
347
352
|
var STATUS_WORDS = {
|
|
348
353
|
passed: ["passed", "success", "succeeded", "ok"],
|
|
349
354
|
failed: ["failed", "failure", "error", "errored"],
|
|
@@ -354,6 +359,23 @@ var STATUS_WORDS = {
|
|
|
354
359
|
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
355
360
|
|
|
356
361
|
// ../kit/src/format.ts
|
|
362
|
+
var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
|
|
363
|
+
function formatSeconds(total) {
|
|
364
|
+
let rest = Math.max(0, Math.round(total));
|
|
365
|
+
const amounts = UNITS.map(([unit, size]) => {
|
|
366
|
+
const amount = Math.floor(rest / size);
|
|
367
|
+
rest -= amount * size;
|
|
368
|
+
return `${amount}${unit}`;
|
|
369
|
+
});
|
|
370
|
+
const first = amounts.findIndex((amount) => !amount.startsWith("0"));
|
|
371
|
+
if (first === -1)
|
|
372
|
+
return "0s";
|
|
373
|
+
const next = amounts[first + 1];
|
|
374
|
+
return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
|
|
375
|
+
}
|
|
376
|
+
function formatDuration(ms) {
|
|
377
|
+
return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
|
|
378
|
+
}
|
|
357
379
|
function upTo(text, separator) {
|
|
358
380
|
const end = text.indexOf(separator);
|
|
359
381
|
return end === -1 ? text : text.slice(0, end);
|
|
@@ -411,24 +433,20 @@ function jsonText(value, replacer, { stream = process7.stdout, env = process7.en
|
|
|
411
433
|
|
|
412
434
|
// ../kit/src/help.ts
|
|
413
435
|
import process8 from "process";
|
|
414
|
-
var OPTIONAL =
|
|
436
|
+
var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
|
|
415
437
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
416
438
|
var FULL_STOP = /\.$/;
|
|
417
439
|
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
418
440
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
419
441
|
}
|
|
420
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
421
|
-
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(`
|
|
422
444
|
`);
|
|
423
445
|
}
|
|
424
446
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
425
447
|
if (exits.length === 0)
|
|
426
448
|
return [];
|
|
427
|
-
|
|
428
|
-
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
429
|
-
}
|
|
430
|
-
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
431
|
-
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
449
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
432
450
|
}
|
|
433
451
|
function wantsHelpJson(env = process8.env) {
|
|
434
452
|
return env.KIT_HELP === "json";
|
|
@@ -454,29 +472,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
454
472
|
return [];
|
|
455
473
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
456
474
|
}
|
|
475
|
+
var MAX_INLINE_CHOICES = 24;
|
|
457
476
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
458
477
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
459
478
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
460
|
-
const
|
|
479
|
+
const choices = option.choices?.join("|");
|
|
480
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
481
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
461
482
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
462
483
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
463
|
-
|
|
484
|
+
const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
|
|
485
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
|
|
464
486
|
});
|
|
465
487
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
466
488
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
467
489
|
}
|
|
468
490
|
|
|
469
491
|
// ../kit/src/text.ts
|
|
470
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
471
492
|
function distance(a, b) {
|
|
472
|
-
|
|
473
|
-
|
|
493
|
+
const left = [...a];
|
|
494
|
+
const right = [...b];
|
|
495
|
+
let before = [];
|
|
496
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
497
|
+
for (const [i, x] of left.entries()) {
|
|
474
498
|
const current = [i + 1];
|
|
475
|
-
for (const [j,
|
|
476
|
-
|
|
499
|
+
for (const [j, y] of right.entries()) {
|
|
500
|
+
let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
|
|
501
|
+
if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
|
|
502
|
+
cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
|
|
503
|
+
current.push(cost);
|
|
504
|
+
}
|
|
505
|
+
before = previous;
|
|
477
506
|
previous = current;
|
|
478
507
|
}
|
|
479
|
-
return previous[
|
|
508
|
+
return previous[right.length] ?? 0;
|
|
480
509
|
}
|
|
481
510
|
function closest(name, names) {
|
|
482
511
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -496,6 +525,17 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
496
525
|
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
497
526
|
return number;
|
|
498
527
|
}
|
|
528
|
+
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
529
|
+
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
530
|
+
function duration(value, name, fallback, unit = "s") {
|
|
531
|
+
if (value === undefined)
|
|
532
|
+
return fallback;
|
|
533
|
+
const match = DURATION.exec(value.trim());
|
|
534
|
+
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
535
|
+
if (ms < 1)
|
|
536
|
+
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
537
|
+
return ms;
|
|
538
|
+
}
|
|
499
539
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
500
540
|
if (path === "-") {
|
|
501
541
|
if (process9.stdin.isTTY)
|
|
@@ -725,9 +765,33 @@ function nearestOption(message, options, allowNegative) {
|
|
|
725
765
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
726
766
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
727
767
|
}
|
|
768
|
+
// ../kit/src/argv.ts
|
|
769
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
770
|
+
import { resolve as resolve3 } from "path";
|
|
771
|
+
import process11 from "process";
|
|
772
|
+
function commandLine() {
|
|
773
|
+
try {
|
|
774
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
775
|
+
} catch {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
function realPath(word) {
|
|
780
|
+
try {
|
|
781
|
+
return realpathSync(resolve3(word));
|
|
782
|
+
} catch {
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
|
|
787
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
788
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
789
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
790
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
791
|
+
}
|
|
728
792
|
// ../kit/src/process.ts
|
|
729
793
|
import { constants } from "os";
|
|
730
|
-
import
|
|
794
|
+
import process12 from "process";
|
|
731
795
|
var KILL_GRACE_MS = 2000;
|
|
732
796
|
function exitCodeOf(code, signal) {
|
|
733
797
|
if (code !== null)
|
|
@@ -747,7 +811,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
747
811
|
return;
|
|
748
812
|
try {
|
|
749
813
|
if (grouped)
|
|
750
|
-
|
|
814
|
+
process12.kill(-proc.pid, killing);
|
|
751
815
|
else
|
|
752
816
|
proc.kill(killing);
|
|
753
817
|
} catch {}
|
|
@@ -821,15 +885,33 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
821
885
|
var RESET_STYLE = `${ESC}[0m`;
|
|
822
886
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
823
887
|
// ../kit/src/cli.ts
|
|
824
|
-
import { readFileSync as
|
|
888
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
825
889
|
import { dirname as dirname3, join as join5 } from "path";
|
|
890
|
+
import process15 from "process";
|
|
891
|
+
|
|
892
|
+
// ../kit/src/notify.ts
|
|
826
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
|
+
}
|
|
827
909
|
|
|
828
910
|
// ../kit/src/usage.ts
|
|
829
911
|
import { appendFileSync, mkdirSync } from "fs";
|
|
830
912
|
import { homedir as homedir3 } from "os";
|
|
831
913
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
832
|
-
import
|
|
914
|
+
import process14 from "process";
|
|
833
915
|
|
|
834
916
|
// ../kit/src/logs.ts
|
|
835
917
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -843,14 +925,14 @@ var usageError;
|
|
|
843
925
|
function noteUsageError(message) {
|
|
844
926
|
usageError = message;
|
|
845
927
|
}
|
|
846
|
-
function stateHome(env =
|
|
928
|
+
function stateHome(env = process14.env) {
|
|
847
929
|
const dir = env.XDG_STATE_HOME;
|
|
848
930
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
849
931
|
}
|
|
850
|
-
function usagePath(env =
|
|
932
|
+
function usagePath(env = process14.env) {
|
|
851
933
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
852
934
|
}
|
|
853
|
-
function usageRecorded(env =
|
|
935
|
+
function usageRecorded(env = process14.env) {
|
|
854
936
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
855
937
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
856
938
|
}
|
|
@@ -864,7 +946,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
864
946
|
usageError = undefined;
|
|
865
947
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
866
948
|
}
|
|
867
|
-
function recordUsage(entry, env =
|
|
949
|
+
function recordUsage(entry, env = process14.env) {
|
|
868
950
|
if (!usageRecorded(env))
|
|
869
951
|
return;
|
|
870
952
|
try {
|
|
@@ -941,7 +1023,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
941
1023
|
header(colors, summary),
|
|
942
1024
|
"",
|
|
943
1025
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
944
|
-
...replacesRows(replaces, colors),
|
|
945
1026
|
"",
|
|
946
1027
|
...await commandRows(commands, colors),
|
|
947
1028
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -955,8 +1036,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
955
1036
|
`);
|
|
956
1037
|
}
|
|
957
1038
|
function printError(prefix, message, hint, cause) {
|
|
958
|
-
const colors = paint(
|
|
959
|
-
const styled = takesControlCodes(
|
|
1039
|
+
const colors = paint(process15.stderr);
|
|
1040
|
+
const styled = takesControlCodes(process15.stderr);
|
|
960
1041
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
961
1042
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
962
1043
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -999,11 +1080,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
999
1080
|
}
|
|
1000
1081
|
}
|
|
1001
1082
|
if (name === undefined && level.path.length > 1) {
|
|
1002
|
-
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));
|
|
1003
1084
|
return 2;
|
|
1004
1085
|
}
|
|
1005
1086
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
1006
|
-
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));
|
|
1007
1088
|
return 0;
|
|
1008
1089
|
}
|
|
1009
1090
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1059,24 +1140,24 @@ function candidateLine(candidate) {
|
|
|
1059
1140
|
}
|
|
1060
1141
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
1061
1142
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1062
|
-
|
|
1143
|
+
const typed = [];
|
|
1063
1144
|
let at = 0;
|
|
1064
1145
|
while (at < before.length) {
|
|
1065
1146
|
const word = before[at];
|
|
1066
1147
|
if (word === "--") {
|
|
1067
|
-
|
|
1148
|
+
typed.push(...before.slice(at + 1));
|
|
1068
1149
|
break;
|
|
1069
1150
|
}
|
|
1070
1151
|
if (!word.startsWith("-"))
|
|
1071
|
-
|
|
1152
|
+
typed.push(word);
|
|
1072
1153
|
else if (takesValue(word))
|
|
1073
1154
|
at++;
|
|
1074
1155
|
at++;
|
|
1075
1156
|
}
|
|
1076
1157
|
const last = positionals.at(-1);
|
|
1077
|
-
if (
|
|
1078
|
-
return positionals[
|
|
1079
|
-
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 };
|
|
1080
1161
|
}
|
|
1081
1162
|
async function leafCandidates(run, words) {
|
|
1082
1163
|
const completing = await completingOf(run);
|
|
@@ -1084,12 +1165,12 @@ async function leafCandidates(run, words) {
|
|
|
1084
1165
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1085
1166
|
const flag = words.at(-2);
|
|
1086
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);
|
|
1087
1169
|
if (option?.type === "string") {
|
|
1088
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1170
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1089
1171
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1090
1172
|
}
|
|
1091
|
-
const
|
|
1092
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1173
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1093
1174
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1094
1175
|
}
|
|
1095
1176
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1120,9 +1201,13 @@ async function printCandidates(found) {
|
|
|
1120
1201
|
return 0;
|
|
1121
1202
|
}
|
|
1122
1203
|
function packageVersion(entry = Bun.main) {
|
|
1123
|
-
|
|
1204
|
+
let resolved = entry;
|
|
1205
|
+
try {
|
|
1206
|
+
resolved = realpathSync2(entry);
|
|
1207
|
+
} catch {}
|
|
1208
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1124
1209
|
try {
|
|
1125
|
-
const { version } = JSON.parse(
|
|
1210
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1126
1211
|
if (typeof version === "string")
|
|
1127
1212
|
return version;
|
|
1128
1213
|
} catch {}
|
|
@@ -1130,14 +1215,17 @@ function packageVersion(entry = Bun.main) {
|
|
|
1130
1215
|
return "0.0.0";
|
|
1131
1216
|
}
|
|
1132
1217
|
}
|
|
1133
|
-
async function runCli(cli, argv =
|
|
1218
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1134
1219
|
const version = cli.version ?? packageVersion();
|
|
1135
1220
|
if (argv[0] === COMPLETE)
|
|
1136
1221
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1222
|
+
const started = performance.now();
|
|
1137
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);
|
|
1138
1226
|
if (cli.usage !== false) {
|
|
1139
1227
|
try {
|
|
1140
|
-
recordUsage(usageEntry(cli.name,
|
|
1228
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1141
1229
|
} catch {}
|
|
1142
1230
|
}
|
|
1143
1231
|
return code;
|
|
@@ -1160,7 +1248,7 @@ function commandPath(scope, argv) {
|
|
|
1160
1248
|
// ../kit/src/compose.ts
|
|
1161
1249
|
async function captureOutput(argv, { cwd, env } = {}) {
|
|
1162
1250
|
const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
1163
|
-
const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
|
|
1251
|
+
const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]);
|
|
1164
1252
|
return { code, stdout, stderr };
|
|
1165
1253
|
}
|
|
1166
1254
|
async function compose(args, { flags = [], ...options } = {}) {
|
|
@@ -1189,7 +1277,9 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
|
1189
1277
|
// src/args.ts
|
|
1190
1278
|
var DEFAULT_ENV = "DATABASE_URL";
|
|
1191
1279
|
var DEFAULT_LIMIT = 20;
|
|
1280
|
+
var DEFAULT_TIMEOUT_MS = 30000;
|
|
1192
1281
|
var ALL_LIMIT = 100;
|
|
1282
|
+
var WRITE_EXIT = 1;
|
|
1193
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"]];
|
|
1194
1284
|
var HOSTS_NOTE = 'db connects to a local host (localhost, 127.0.0.1, ::1) or a compose service only: any other host is refused (exit 2) unless it is listed under "allowedHosts" in ~/.config/kaynooo-cli/db.json.';
|
|
1195
1285
|
var WRITE_NOTE = "A write runs only when the database actually connected to has a name ending in _test (checked on the server, and a statement that names another database, or uses USE, SET, files or server objects, is not run); any other write is printed for you to run.";
|
|
@@ -1197,23 +1287,30 @@ var connectionOptions = {
|
|
|
1197
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` },
|
|
1198
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" },
|
|
1199
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" },
|
|
1200
|
-
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)` }
|
|
1201
1292
|
};
|
|
1293
|
+
function statementTimeout(values) {
|
|
1294
|
+
return Math.ceil(duration(values.timeout, "timeout", DEFAULT_TIMEOUT_MS));
|
|
1295
|
+
}
|
|
1202
1296
|
var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
|
|
1203
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"] };
|
|
1204
1298
|
function rowLimit(values, fallback = DEFAULT_LIMIT) {
|
|
1205
1299
|
return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
|
|
1206
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"] };
|
|
1207
1302
|
var catalogOptions = {
|
|
1208
1303
|
rows,
|
|
1209
1304
|
all,
|
|
1210
|
-
json: jsonOption()
|
|
1305
|
+
json: jsonOption(),
|
|
1306
|
+
format: format2
|
|
1211
1307
|
};
|
|
1212
1308
|
var outputOptions = {
|
|
1213
1309
|
rows,
|
|
1214
1310
|
all,
|
|
1215
1311
|
raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
|
|
1216
|
-
json: jsonOption()
|
|
1312
|
+
json: jsonOption(),
|
|
1313
|
+
format: format2
|
|
1217
1314
|
};
|
|
1218
1315
|
|
|
1219
1316
|
// src/sql-tokens.ts
|
|
@@ -1550,28 +1647,57 @@ function shape(rows, limit, raw, exact = true) {
|
|
|
1550
1647
|
const { rows: masked, masked: columns } = maskRows(rows.slice(0, limit), raw);
|
|
1551
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 };
|
|
1552
1649
|
}
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
const
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
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 = [];
|
|
1562
1666
|
if (shown.truncated && !shown.exact)
|
|
1563
1667
|
lines.push("... more rows not shown (-n raises the cap)");
|
|
1564
1668
|
else if (shown.truncated)
|
|
1565
1669
|
lines.push(`... ${shown.omitted} more ${shown.omitted === 1 ? "row" : "rows"} not shown (${shown.total} in all, -n raises the cap)`);
|
|
1566
1670
|
if (shown.masked.length > 0)
|
|
1567
1671
|
lines.push(`masked: ${shown.masked.join(", ")} (--raw shows them)`);
|
|
1568
|
-
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(`
|
|
1569
1695
|
`);
|
|
1570
1696
|
}
|
|
1571
1697
|
|
|
1572
1698
|
// src/run.ts
|
|
1573
1699
|
import { isIP } from "net";
|
|
1574
|
-
import
|
|
1700
|
+
import process17 from "process";
|
|
1575
1701
|
var {SQL } = globalThis.Bun;
|
|
1576
1702
|
|
|
1577
1703
|
// src/compose.ts
|
|
@@ -1754,7 +1880,6 @@ async function loadSettings(home) {
|
|
|
1754
1880
|
}
|
|
1755
1881
|
|
|
1756
1882
|
// src/run.ts
|
|
1757
|
-
var STATEMENT_TIMEOUT = "30s";
|
|
1758
1883
|
var SESSION_SETTINGS = { lock_timeout: "5s", idle_in_transaction_session_timeout: "60s" };
|
|
1759
1884
|
var CURSOR = "db_rows";
|
|
1760
1885
|
var CURSOR_STARTS = /^\s*(?:select|with|values|table)\b/i;
|
|
@@ -1765,7 +1890,7 @@ var BRACKETS = /^\[|\]$/g;
|
|
|
1765
1890
|
var POSTGRES_SCHEMES = new Set(["postgres:", "postgresql:"]);
|
|
1766
1891
|
var MYSQL_SCHEMES = new Set(["mysql:", "mysql2:", "mariadb:"]);
|
|
1767
1892
|
var WRAP_ERRNOS = new Set([1064, 1060]);
|
|
1768
|
-
var
|
|
1893
|
+
var mysqlTimeouts = (ms) => [`SET SESSION max_execution_time = ${ms}`, `SET SESSION max_statement_time = ${ms / 1000}`];
|
|
1769
1894
|
var TEST_SUFFIX = "_test";
|
|
1770
1895
|
|
|
1771
1896
|
class Rollback extends Error {
|
|
@@ -1826,7 +1951,7 @@ async function connectionUrl({ env, service, container, database }, home) {
|
|
|
1826
1951
|
if (service !== undefined && container !== undefined)
|
|
1827
1952
|
fail("--service and --container name two databases: pick one");
|
|
1828
1953
|
const isNamed = service !== undefined || container !== undefined;
|
|
1829
|
-
const value = isNamed ? undefined :
|
|
1954
|
+
const value = isNamed ? undefined : process17.env[env ?? DEFAULT_ENV];
|
|
1830
1955
|
let url;
|
|
1831
1956
|
if (value !== undefined && value !== "")
|
|
1832
1957
|
url = await reachable(value, home);
|
|
@@ -1851,13 +1976,13 @@ function databaseOfUrl(url) {
|
|
|
1851
1976
|
function toResult(rows) {
|
|
1852
1977
|
return Object.assign([...rows], { affected: rows.count ?? rows.affectedRows ?? rows.length });
|
|
1853
1978
|
}
|
|
1854
|
-
var bunConnect = (url, dialect, readOnly) => {
|
|
1979
|
+
var bunConnect = (url, dialect, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) => {
|
|
1855
1980
|
const sql = new SQL({ url, max: 1, connectionTimeout: 10, ...dialect === "postgres" ? { connection: { ...SESSION_SETTINGS, ...readOnly ? { default_transaction_read_only: "on" } : {} } } : { allowPublicKeyRetrieval: allowsKeyRetrieval(url) } });
|
|
1856
1981
|
return {
|
|
1857
1982
|
async transaction(work, isReadOnly) {
|
|
1858
1983
|
if (dialect === "postgres") {
|
|
1859
1984
|
const body = async (tx) => {
|
|
1860
|
-
await tx.unsafe(`SET LOCAL statement_timeout = '${
|
|
1985
|
+
await tx.unsafe(`SET LOCAL statement_timeout = '${timeoutMs}ms'`);
|
|
1861
1986
|
await work({ unsafe: async (statement, params) => toResult(await tx.unsafe(statement, params)) });
|
|
1862
1987
|
};
|
|
1863
1988
|
await (isReadOnly ? sql.begin("read only", body) : sql.begin(body));
|
|
@@ -1865,7 +1990,7 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1865
1990
|
}
|
|
1866
1991
|
const connection = await sql.reserve();
|
|
1867
1992
|
try {
|
|
1868
|
-
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);
|
|
1869
1994
|
} finally {
|
|
1870
1995
|
await connection.release();
|
|
1871
1996
|
}
|
|
@@ -1875,8 +2000,8 @@ var bunConnect = (url, dialect, readOnly) => {
|
|
|
1875
2000
|
}
|
|
1876
2001
|
};
|
|
1877
2002
|
};
|
|
1878
|
-
async function mysqlTransaction(connection, work, readOnly) {
|
|
1879
|
-
for (const timeout of
|
|
2003
|
+
async function mysqlTransaction(connection, work, readOnly, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
2004
|
+
for (const timeout of mysqlTimeouts(timeoutMs)) {
|
|
1880
2005
|
try {
|
|
1881
2006
|
await connection.unsafe(timeout);
|
|
1882
2007
|
} catch {}
|
|
@@ -1913,9 +2038,9 @@ ${statement.replace(TRAILING_SEMICOLONS, "")}
|
|
|
1913
2038
|
function messageOf(error, url) {
|
|
1914
2039
|
return scrub(error instanceof Error ? error.message : String(error), url);
|
|
1915
2040
|
}
|
|
1916
|
-
async function readRows(url, statement, params = [], limit, connect = bunConnect) {
|
|
2041
|
+
async function readRows(url, statement, params = [], limit, connect = bunConnect, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
1917
2042
|
const dialect = dialectOf(new URL(url));
|
|
1918
|
-
const session = connect(url, dialect, true);
|
|
2043
|
+
const session = connect(url, dialect, true, timeoutMs);
|
|
1919
2044
|
let rows = [];
|
|
1920
2045
|
try {
|
|
1921
2046
|
await session.transaction(async (tx) => {
|
|
@@ -1966,7 +2091,7 @@ async function closeQuietly(session, url) {
|
|
|
1966
2091
|
try {
|
|
1967
2092
|
await session.close();
|
|
1968
2093
|
} catch (error) {
|
|
1969
|
-
|
|
2094
|
+
warn(messageOf(error, url));
|
|
1970
2095
|
}
|
|
1971
2096
|
}
|
|
1972
2097
|
|
|
@@ -1976,13 +2101,12 @@ var usage2 = `db query "<sql>"
|
|
|
1976
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.
|
|
1977
2102
|
|
|
1978
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.
|
|
1979
|
-
Statements time out after 30 seconds and show at most -n rows (${DEFAULT_LIMIT}, --all for 100), a Postgres select being read through a cursor that stops one row past it. Columns named like emails, phones, tokens, secrets, passwords or hashes show *** unless --raw, and every message is scrubbed of the URL and password.
|
|
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.
|
|
1980
2105
|
|
|
1981
2106
|
${WRITE_NOTE}
|
|
1982
2107
|
|
|
1983
2108
|
${HOSTS_NOTE}`;
|
|
1984
2109
|
var options = { ...connectionOptions, ...outputOptions };
|
|
1985
|
-
var WRITE_EXIT = 1;
|
|
1986
2110
|
var NO_SQL = "no SQL given: pass it as an argument or on stdin";
|
|
1987
2111
|
async function readSql(positionals) {
|
|
1988
2112
|
const sql = positionals.length === 0 ? await readInput("-", { noStdin: NO_SQL }) : positionals.join(" ");
|
|
@@ -1991,9 +2115,8 @@ async function readSql(positionals) {
|
|
|
1991
2115
|
return sql;
|
|
1992
2116
|
}
|
|
1993
2117
|
function handBack(sql, reasons, note = "") {
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
\`\`\`sql
|
|
2118
|
+
problem(`db: not run, this statement would write or cannot be shown to only read (${reasons.join("; ")})${note}. Run it yourself:`);
|
|
2119
|
+
console.log(`\`\`\`sql
|
|
1997
2120
|
${sql.trim()}
|
|
1998
2121
|
\`\`\``);
|
|
1999
2122
|
return WRITE_EXIT;
|
|
@@ -2025,39 +2148,55 @@ async function query(args) {
|
|
|
2025
2148
|
console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
|
|
2026
2149
|
else
|
|
2027
2150
|
console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
|
|
2028
|
-
${render(shown, false)}`}`);
|
|
2151
|
+
${render(shown, false, values.format)}`}`);
|
|
2029
2152
|
return 0;
|
|
2030
2153
|
}
|
|
2031
2154
|
if (verdict.statements > 1)
|
|
2032
2155
|
fail("one statement at a time");
|
|
2033
|
-
const rows = await readRows(url, sql, [], limit);
|
|
2034
|
-
console.log(render(shape(rows, limit, values.raw === true, false), values.json === true));
|
|
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));
|
|
2035
2158
|
return 0;
|
|
2036
2159
|
}
|
|
2037
2160
|
|
|
2038
2161
|
// src/commands/explain.ts
|
|
2039
|
-
var usage3 = `db explain "<sql>"
|
|
2162
|
+
var usage3 = `db explain "<sql>" [--analyze]
|
|
2040
2163
|
|
|
2041
|
-
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.
|
|
2042
2166
|
|
|
2043
2167
|
${HOSTS_NOTE}`;
|
|
2044
|
-
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" } };
|
|
2045
2169
|
var READ_START = /^\s*(?:select|with|values|table)\b/i;
|
|
2046
2170
|
var TRAILING_SEMICOLON = /;\s*$/;
|
|
2047
|
-
|
|
2171
|
+
var MARIADB = /mariadb/i;
|
|
2172
|
+
var MYSQL_VERSION = /^(\d+)\.(\d+)\.(\d+)/;
|
|
2173
|
+
function explainSql(sql, dialect, prefix = "EXPLAIN") {
|
|
2048
2174
|
const verdict = inspect(sql, dialect);
|
|
2049
2175
|
if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2050
2176
|
fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
|
|
2051
|
-
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}`);
|
|
2052
2186
|
}
|
|
2053
2187
|
async function explain(args) {
|
|
2054
2188
|
const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
|
|
2055
2189
|
const sql = await readSql(positionals);
|
|
2056
2190
|
const url = await connectionUrl(values);
|
|
2057
2191
|
const dialect = dialectOf(new URL(url));
|
|
2058
|
-
const
|
|
2059
|
-
|
|
2060
|
-
|
|
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(`
|
|
2061
2200
|
`));
|
|
2062
2201
|
else
|
|
2063
2202
|
console.log(render(shape(rows, rows.length, true), values.json === true));
|
|
@@ -2158,8 +2297,8 @@ async function show(args, usage, work) {
|
|
|
2158
2297
|
const limit = rowLimit(values);
|
|
2159
2298
|
const url = await connectionUrl(values);
|
|
2160
2299
|
const { sql, params } = plans[dialectOf(new URL(url))];
|
|
2161
|
-
const rows = await readRows(url, sql, params, limit);
|
|
2162
|
-
console.log(render(shape(rows, limit, true, false), values.json === true));
|
|
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));
|
|
2163
2302
|
return 0;
|
|
2164
2303
|
}
|
|
2165
2304
|
async function tables(args) {
|
|
@@ -2222,20 +2361,20 @@ ${HOSTS_NOTE}`;
|
|
|
2222
2361
|
const limit = rowLimit(values);
|
|
2223
2362
|
const url = await connectionUrl(values);
|
|
2224
2363
|
const dialect = dialectOf(new URL(url));
|
|
2225
|
-
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));
|
|
2226
2365
|
const columns = shape(await ask(plans.columns, limit), limit, true, false);
|
|
2227
2366
|
const indexes = await ask(plans.indexes);
|
|
2228
2367
|
const foreignKeys = await ask(plans.foreignKeys);
|
|
2229
2368
|
if (values.json === true)
|
|
2230
2369
|
console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
|
|
2231
2370
|
else
|
|
2232
|
-
console.log(`${render(columns, false)}
|
|
2371
|
+
console.log(`${render(columns, false, values.format)}
|
|
2233
2372
|
|
|
2234
2373
|
indexes
|
|
2235
|
-
${render(shape(indexes, indexes.length, true), false)}
|
|
2374
|
+
${render(shape(indexes, indexes.length, true), false, values.format)}
|
|
2236
2375
|
|
|
2237
2376
|
foreign keys
|
|
2238
|
-
${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
|
|
2377
|
+
${render(shape(foreignKeys, foreignKeys.length, true), false, values.format)}`);
|
|
2239
2378
|
return 0;
|
|
2240
2379
|
}
|
|
2241
2380
|
|
|
@@ -2257,7 +2396,7 @@ function countSql(target, dialect, where) {
|
|
|
2257
2396
|
}
|
|
2258
2397
|
var where = { type: "string", short: "w", description: "only the rows matching this SQL condition" };
|
|
2259
2398
|
var sampleOptions = { ...connectionOptions, ...outputOptions, where };
|
|
2260
|
-
var countOptions = { ...connectionOptions, json: outputOptions.json, where };
|
|
2399
|
+
var countOptions = { ...connectionOptions, json: outputOptions.json, format: outputOptions.format, where };
|
|
2261
2400
|
async function run(args, usage, options, build) {
|
|
2262
2401
|
const parsed = parse(args, usage, options, { exits: EXITS });
|
|
2263
2402
|
const { values, positionals } = parsed;
|
|
@@ -2271,7 +2410,7 @@ async function run(args, usage, options, build) {
|
|
|
2271
2410
|
const verdict = inspect(sql, dialect);
|
|
2272
2411
|
if (verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2273
2412
|
fail(`not a plain read: ${verdict.reasons.join("; ") || "one statement at a time"}`);
|
|
2274
|
-
console.log(render(shape(await readRows(url, sql, [], limit), limit, values.raw === true, false), values.json === true));
|
|
2413
|
+
console.log(render(shape(await readRows(url, sql, [], limit, undefined, statementTimeout(values)), limit, values.raw === true, false), values.json === true, values.format));
|
|
2275
2414
|
return 0;
|
|
2276
2415
|
}
|
|
2277
2416
|
async function sample(args) {
|
|
@@ -2290,17 +2429,17 @@ ${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, d
|
|
|
2290
2429
|
}
|
|
2291
2430
|
|
|
2292
2431
|
// src/cli.ts
|
|
2293
|
-
|
|
2432
|
+
process18.exitCode = await runCli({
|
|
2294
2433
|
name: "db",
|
|
2295
2434
|
about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
|
|
2296
2435
|
replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
|
|
2297
|
-
examples: ['db "select count(*) from users"', ['db -c booki-db-1 "select count(*) from users"', "a container outside the compose project"], ["db describe users", "the columns, indexes and foreign keys of a table"], ["db search email", "where a field lives"], [`db explain "select * from users where email = 'a'"`, "the plan, nothing executed"]],
|
|
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"]],
|
|
2298
2437
|
commands: {
|
|
2299
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' },
|
|
2300
2439
|
tables: { run: tables, summary: "list tables and views with an estimated row count" },
|
|
2301
2440
|
describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
|
|
2302
2441
|
search: { run: search, summary: "find the tables and columns whose name contains a text" },
|
|
2303
|
-
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)" },
|
|
2304
2443
|
sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
|
|
2305
2444
|
count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
|
|
2306
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
|
}
|