@kaynooo/cli-db 0.9.2 → 0.11.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 +8 -7
- package/dist/cli.js +526 -136
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ bun install -g @kaynooo/cli-db
|
|
|
14
14
|
- `--container <name>` (`-c`) reads a running container by name or id, in any compose project or none (a worktree stack, `booki-docker--shot-igesa-db-1`), found with `docker inspect`. It picks the container over the URL, and cannot be combined with `--service`.
|
|
15
15
|
- The credentials of `--service` and `--container` come from the container's environment, never printed: `POSTGRES_USER`, `POSTGRES_PASSWORD` and `POSTGRES_DB` for Postgres; `MYSQL_USER`, `MYSQL_PASSWORD` and `MYSQL_DATABASE` for MySQL and MariaDB, else `root` with `MYSQL_ROOT_PASSWORD`, each also as `MARIADB_*`. A password kept in a `*_FILE` variable is refused with a hint to give the URL.
|
|
16
16
|
- `--database <name>` reads another database on the same server, `db dbs` lists them.
|
|
17
|
-
- Only a local host (`localhost`, `127.0.0.1`, `::1`, a local socket) or a compose service is connected to. Any other host is refused before connecting, exit 2, with the host (never the URL) and the config path in the message, unless it is listed in `~/.config/db/config.json
|
|
17
|
+
- Only a local host (`localhost`, `127.0.0.1`, `::1`, a local socket) or a compose service is connected to. Any other host is refused before connecting, exit 2, with the host (never the URL) and the config path in the message, unless it is listed in `~/.config/kaynooo-cli/db.json` (the older `~/.config/db/config.json` is read while the new file is missing): `{ "allowedHosts": ["db.example.com"] }`. A missing or empty list allows only local hosts, and a file that is not valid JSON is ignored with a warning. There is no flag to allow a host.
|
|
18
18
|
- MySQL 8 logs in without TLS by fetching the server's RSA key, which `db` allows only for a loopback host and a docker network address (`172.16.0.0/12`). A MySQL 8 elsewhere (an allowed remote host, a docker pool in `192.168.0.0/16`) needs TLS or an account on `mysql_native_password`.
|
|
19
19
|
|
|
20
20
|
## Commands
|
|
@@ -24,20 +24,21 @@ bun install -g @kaynooo/cli-db
|
|
|
24
24
|
| `db "<sql>"` / `db query` | runs one read-only statement, as an argument or on stdin |
|
|
25
25
|
| `db tables` | tables and views with an estimated row count (Postgres: outside the system schemas, MySQL: the connected database) |
|
|
26
26
|
| `db sample <table>` | a few rows of a table (`-n`, `--where`), sensitive columns masked; `db count <table>` the number of rows |
|
|
27
|
-
| `db describe <table>` | columns with type, nullability, default and primary key (`schema.table` to pick a schema, the database on MySQL) |
|
|
27
|
+
| `db describe <table>` | columns with type, nullability, default and primary key, then the indexes and foreign keys (`schema.table` to pick a schema, the database on MySQL); `--json` adds `indexes` and `foreignKeys` |
|
|
28
|
+
| `db search <text>` | tables and columns whose name contains the text, case insensitive, to find where a field lives |
|
|
29
|
+
| `db explain "<sql>"` | the plan of one read without running it: `EXPLAIN` alone through the read-only guard, never `ANALYZE` (a statement not starting with SELECT, WITH, VALUES or TABLE, and a hand-written EXPLAIN or ANALYZE, are refused) |
|
|
28
30
|
| `db dbs` | databases the connection may open, with their size, the one read marked `current` |
|
|
29
31
|
|
|
30
|
-
Options: `-n <rows>` caps the rows shown (
|
|
32
|
+
Options: `-n <rows>` (`--rows`, once `--limit`) caps the rows shown (20) and says when more were left out, `--all` shows up to 100 (the old default, so `-n` for more), `--raw` shows the columns masked by default, `--json` prints `{ columns, rows, truncated, masked }`, `-e <KEY>`, `-s <service>`, `-c <container>` and `-d <database>` pick the connection.
|
|
31
33
|
|
|
32
34
|
## Safety
|
|
33
35
|
|
|
34
36
|
- Postgres: the session opens with `default_transaction_read_only=on`, `lock_timeout=5s` and `idle_in_transaction_session_timeout=60s`, then the statement runs after `SET LOCAL statement_timeout = '30s'` in `BEGIN READ ONLY`, and the transaction is rolled back, so Postgres itself refuses a write the checks below miss. The transaction does not stop side effects outside it (`pg_terminate_backend`, `COPY ... TO PROGRAM`, `dblink`), which the checks below do.
|
|
35
37
|
- MySQL and MariaDB: the statement runs in `START TRANSACTION READ ONLY` on one reserved connection, under a 30 second statement timeout (`max_execution_time`, or `max_statement_time` on MariaDB), and the transaction is rolled back. A select is wrapped in `select * from (...) limit n + 1` to stop one row past `-n`, and read whole only when the wrapping does not parse or repeats a column name (errors 1064 and 1060); any other error is reported as is.
|
|
36
38
|
- A Postgres select is read through a cursor that stops at one row past `-n`, so a huge table is never loaded whole.
|
|
37
|
-
- Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused.
|
|
38
|
-
- Such a statement is printed as a `sql` block with the reasons and `db` exits 1 without running it. Several statements in one string are refused
|
|
39
|
-
- Columns named like emails, phones, tokens, secrets, passwords or hashes show `***` unless `--raw
|
|
40
|
-
- Every message, errors included, is scrubbed of the URL, the password (raw and decoded) and any `scheme://user:password@`.
|
|
39
|
+
- Before running, the SQL is tokenized the way its engine reads it (Postgres: nested comments, dollar-quoted bodies, `E'...'` escapes; MySQL: `#` comments, `--` only before a blank, backslash escapes, double quotes as strings, comments that do not nest, `/*! ... */` and `/*M! ... */` run). A quoted identifier is read as a name, so `"nextval"('s')` is caught, and a NUL byte or a `U&"..."` identifier is refused. The allowed starts, the refused keywords and the refused functions are in `db query --help`.
|
|
40
|
+
- Such a statement is printed as a `sql` block with the reasons and `db` exits 1 without running it. Several statements in one string are refused (exit 2) even when each reads: one statement at a time.
|
|
41
|
+
- Columns named like emails, phones, tokens, secrets, passwords or hashes show `***` unless `--raw` (`NULL` stays `NULL`), and every message, errors included, is scrubbed of the URL and the password (raw and decoded).
|
|
41
42
|
|
|
42
43
|
## Writes on a test database
|
|
43
44
|
|
package/dist/cli.js
CHANGED
|
@@ -2,17 +2,34 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
6
|
-
|
|
5
|
+
import process16 from "process";
|
|
7
6
|
// ../kit/src/args.ts
|
|
8
|
-
import
|
|
7
|
+
import process10 from "process";
|
|
9
8
|
import { parseArgs } from "util";
|
|
10
9
|
|
|
11
10
|
// ../kit/src/format.ts
|
|
11
|
+
import process7 from "process";
|
|
12
|
+
|
|
13
|
+
// ../kit/src/mode.ts
|
|
12
14
|
import process2 from "process";
|
|
15
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
16
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
17
|
+
function isSet(value) {
|
|
18
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
19
|
+
}
|
|
20
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
21
|
+
const chosen = env.KIT_MODE;
|
|
22
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
23
|
+
return chosen;
|
|
24
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
25
|
+
return "agent";
|
|
26
|
+
if (stream.isTTY === true)
|
|
27
|
+
return "terminal";
|
|
28
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
29
|
+
}
|
|
13
30
|
|
|
14
31
|
// ../kit/src/style.ts
|
|
15
|
-
import
|
|
32
|
+
import process6 from "process";
|
|
16
33
|
|
|
17
34
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
18
35
|
function x(s) {
|
|
@@ -275,36 +292,246 @@ function le(i = {}) {
|
|
|
275
292
|
}
|
|
276
293
|
var t = le();
|
|
277
294
|
|
|
278
|
-
// ../kit/src/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
295
|
+
// ../kit/src/theme.ts
|
|
296
|
+
import { existsSync as existsSync3, readFileSync, statSync } from "fs";
|
|
297
|
+
import { homedir as homedir2 } from "os";
|
|
298
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
299
|
+
import process5 from "process";
|
|
300
|
+
|
|
301
|
+
// ../kit/src/config.ts
|
|
302
|
+
import { existsSync } from "fs";
|
|
303
|
+
import { dirname, join, resolve } from "path";
|
|
304
|
+
import process3 from "process";
|
|
305
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
306
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
307
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
308
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
309
|
+
if (found !== undefined)
|
|
310
|
+
return found;
|
|
311
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ../kit/src/user-config.ts
|
|
317
|
+
import { existsSync as existsSync2 } from "fs";
|
|
318
|
+
import { homedir } from "os";
|
|
319
|
+
import { join as join2 } from "path";
|
|
320
|
+
import process4 from "process";
|
|
321
|
+
function configBase(where = {}) {
|
|
322
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
323
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
324
|
+
}
|
|
325
|
+
function userConfigPath(bin, where = {}) {
|
|
326
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
327
|
+
}
|
|
328
|
+
function userConfigReadPath(bin, legacy = [], where = {}) {
|
|
329
|
+
const current = userConfigPath(bin, where);
|
|
330
|
+
if (existsSync2(current))
|
|
331
|
+
return current;
|
|
332
|
+
const base = configBase(where);
|
|
333
|
+
return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ../kit/src/theme.ts
|
|
337
|
+
var DEFAULT = {
|
|
338
|
+
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
339
|
+
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
|
|
340
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
341
|
+
bins: {}
|
|
284
342
|
};
|
|
285
|
-
|
|
286
|
-
|
|
343
|
+
var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
344
|
+
var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
345
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
|
|
346
|
+
var PRESETS = {
|
|
347
|
+
default: {},
|
|
348
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
|
|
349
|
+
mono: { colors: MONO, accents: ["bold"] },
|
|
350
|
+
ascii: { glyphs: ASCII }
|
|
351
|
+
};
|
|
352
|
+
var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
353
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
354
|
+
var CONTROL = /\p{Cc}/u;
|
|
355
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
356
|
+
var SPACES = /\s+/;
|
|
357
|
+
function isColorSpec(spec) {
|
|
358
|
+
if (typeof spec === "number")
|
|
359
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
360
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
361
|
+
}
|
|
362
|
+
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
363
|
+
function cubeLevel(channel) {
|
|
364
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
365
|
+
}
|
|
366
|
+
function nearest256(hex) {
|
|
367
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
368
|
+
const levels = rgb.map(cubeLevel);
|
|
369
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
370
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
371
|
+
const greyValue = 8 + grey * 10;
|
|
372
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
373
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
374
|
+
}
|
|
375
|
+
function hasTrueColor(env) {
|
|
376
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
377
|
+
}
|
|
378
|
+
function tinted(colors, spec, env = process5.env) {
|
|
379
|
+
if (typeof spec === "number")
|
|
380
|
+
return colors.ansi256(spec);
|
|
381
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
382
|
+
if (HEX.test(token))
|
|
383
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
384
|
+
return chain[token] ?? chain;
|
|
385
|
+
}, colors);
|
|
386
|
+
}
|
|
387
|
+
function isRecord(value) {
|
|
388
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
389
|
+
}
|
|
390
|
+
function readThemeFile(path, warn) {
|
|
391
|
+
try {
|
|
392
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
393
|
+
if (stat === undefined)
|
|
394
|
+
return;
|
|
395
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
396
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
400
|
+
if (isRecord(parsed))
|
|
401
|
+
return parsed;
|
|
402
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
405
|
+
}
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
function applyPreset(theme, name, warn, where) {
|
|
409
|
+
if (name === undefined)
|
|
410
|
+
return;
|
|
411
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
412
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const preset = PRESETS[name];
|
|
416
|
+
Object.assign(theme.colors, preset.colors);
|
|
417
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
418
|
+
if (preset.accents !== undefined)
|
|
419
|
+
theme.accents = [...preset.accents];
|
|
420
|
+
return name;
|
|
421
|
+
}
|
|
422
|
+
function applyFile(theme, file, where, warn) {
|
|
423
|
+
if (isRecord(file.colors)) {
|
|
424
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
425
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
426
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
427
|
+
else if (!isColorSpec(value))
|
|
428
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
429
|
+
else
|
|
430
|
+
theme.colors[key] = value;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (isRecord(file.glyphs)) {
|
|
434
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
435
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
436
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
437
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
438
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
439
|
+
else
|
|
440
|
+
theme.glyphs[key] = value;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
444
|
+
theme.accents = [...file.accents];
|
|
445
|
+
else if (file.accents !== undefined)
|
|
446
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
447
|
+
if (isRecord(file.bins)) {
|
|
448
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
449
|
+
if (isColorSpec(value))
|
|
450
|
+
theme.bins[bin] = value;
|
|
451
|
+
else
|
|
452
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
function endsWalk(home) {
|
|
457
|
+
return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
|
|
458
|
+
}
|
|
459
|
+
var warned = new Set;
|
|
460
|
+
function warnOnce(message) {
|
|
461
|
+
if (warned.has(message))
|
|
462
|
+
return;
|
|
463
|
+
warned.add(message);
|
|
464
|
+
console.error(`warning: theme ${message}`);
|
|
465
|
+
}
|
|
466
|
+
function isPath(chosen) {
|
|
467
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
468
|
+
}
|
|
469
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
470
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
|
|
471
|
+
const sources = [];
|
|
472
|
+
const chosen = env.KIT_THEME ?? "";
|
|
473
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
474
|
+
if (isPath(chosen))
|
|
475
|
+
wanted.push(resolve2(from, chosen));
|
|
476
|
+
const files = [];
|
|
477
|
+
for (const path of wanted) {
|
|
478
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
479
|
+
if (path !== undefined && file !== undefined)
|
|
480
|
+
files.push({ path, file });
|
|
481
|
+
}
|
|
482
|
+
let preset = "default";
|
|
483
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
484
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
485
|
+
} else {
|
|
486
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
487
|
+
if (named !== undefined)
|
|
488
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
489
|
+
}
|
|
490
|
+
for (const { path, file } of files) {
|
|
491
|
+
applyFile(theme, file, path, warn);
|
|
492
|
+
sources.push(path);
|
|
493
|
+
}
|
|
494
|
+
return { theme, sources, preset };
|
|
287
495
|
}
|
|
288
|
-
|
|
496
|
+
var current;
|
|
497
|
+
var currentKey = "";
|
|
498
|
+
function activeTheme() {
|
|
499
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
500
|
+
if (current === undefined || key !== currentKey) {
|
|
501
|
+
current = loadTheme();
|
|
502
|
+
currentKey = key;
|
|
503
|
+
}
|
|
504
|
+
return current;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ../kit/src/style.ts
|
|
508
|
+
var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
|
|
509
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
510
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
511
|
+
}
|
|
512
|
+
function paint(stream, env = process6.env) {
|
|
289
513
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
290
514
|
}
|
|
291
|
-
function marked(mark, text, stream, detail, env =
|
|
515
|
+
function marked(mark, text, stream, detail, env = process6.env) {
|
|
292
516
|
const colors = paint(stream, env);
|
|
293
|
-
|
|
294
|
-
|
|
517
|
+
let head = MARK_WORDS[mark];
|
|
518
|
+
if (takesControlCodes(stream, env)) {
|
|
519
|
+
const { theme } = activeTheme();
|
|
520
|
+
head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
|
|
521
|
+
}
|
|
295
522
|
return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
|
|
296
523
|
}
|
|
297
524
|
function warn(text, detail) {
|
|
298
|
-
console.error(marked("warn", text,
|
|
299
|
-
}
|
|
300
|
-
var
|
|
301
|
-
passed:
|
|
302
|
-
failed:
|
|
303
|
-
running:
|
|
304
|
-
queued:
|
|
305
|
-
skipped:
|
|
525
|
+
console.error(marked("warn", text, process6.stderr, detail));
|
|
526
|
+
}
|
|
527
|
+
var STATUS_WORDS = {
|
|
528
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
529
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
530
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
531
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
532
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
306
533
|
};
|
|
307
|
-
var STATUS_OF = new Map(Object.entries(
|
|
534
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
308
535
|
|
|
309
536
|
// ../kit/src/format.ts
|
|
310
537
|
function upTo(text, separator) {
|
|
@@ -319,15 +546,18 @@ var ESCAPE = String.fromCharCode(27);
|
|
|
319
546
|
function textWidth(text) {
|
|
320
547
|
return Bun.stringWidth(text);
|
|
321
548
|
}
|
|
322
|
-
function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
549
|
+
function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
|
|
323
550
|
const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
|
|
551
|
+
if (outputMode(stream, env) === "agent")
|
|
552
|
+
return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
|
|
553
|
+
`);
|
|
324
554
|
const widths = [];
|
|
325
555
|
for (const row of cells) {
|
|
326
556
|
for (const [index, cell] of row.entries())
|
|
327
557
|
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
328
558
|
}
|
|
329
559
|
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
330
|
-
const colors = paint(
|
|
560
|
+
const colors = paint(stream);
|
|
331
561
|
const lines = shown.map((row) => row.map((cell, index) => {
|
|
332
562
|
const width = widths[index] ?? 0;
|
|
333
563
|
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
@@ -335,7 +565,8 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
|
335
565
|
return `${gap}${cell}`;
|
|
336
566
|
return index === row.length - 1 ? cell : `${cell}${gap}`;
|
|
337
567
|
}).join(" ").trimEnd());
|
|
338
|
-
|
|
568
|
+
const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
|
|
569
|
+
return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
|
|
339
570
|
`);
|
|
340
571
|
}
|
|
341
572
|
function narrow(rows, widths, limit) {
|
|
@@ -354,26 +585,35 @@ function narrow(rows, widths, limit) {
|
|
|
354
585
|
}
|
|
355
586
|
return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
|
|
356
587
|
}
|
|
588
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
589
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
590
|
+
}
|
|
357
591
|
|
|
358
592
|
// ../kit/src/help.ts
|
|
359
|
-
import
|
|
593
|
+
import process8 from "process";
|
|
360
594
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
361
595
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
362
596
|
var FULL_STOP = /\.$/;
|
|
363
|
-
function usageLine(usage, colors = paint(
|
|
597
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
364
598
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
365
599
|
}
|
|
366
|
-
function helpText(usage, options, colors = paint(
|
|
367
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
600
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
601
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
368
602
|
`);
|
|
369
603
|
}
|
|
370
|
-
function
|
|
371
|
-
|
|
604
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
605
|
+
if (exits.length === 0)
|
|
606
|
+
return [];
|
|
607
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
608
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
609
|
+
}
|
|
610
|
+
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
611
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
372
612
|
}
|
|
373
|
-
function wantsHelpJson(env =
|
|
613
|
+
function wantsHelpJson(env = process8.env) {
|
|
374
614
|
return env.KIT_HELP === "json";
|
|
375
615
|
}
|
|
376
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
616
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
377
617
|
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
378
618
|
`);
|
|
379
619
|
const first = lines[0];
|
|
@@ -384,15 +624,17 @@ function description(usage, { examples = [], replaces } = {}) {
|
|
|
384
624
|
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
385
625
|
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
386
626
|
...replaces === undefined ? {} : { replaces },
|
|
387
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
627
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
628
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
629
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
388
630
|
};
|
|
389
631
|
}
|
|
390
|
-
function exampleRows(examples, colors = paint(
|
|
391
|
-
if (examples.length === 0)
|
|
632
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
633
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
392
634
|
return [];
|
|
393
635
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
394
636
|
}
|
|
395
|
-
function optionRows(options, colors = paint(
|
|
637
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
396
638
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
397
639
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
398
640
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -424,7 +666,7 @@ function closest(name, names) {
|
|
|
424
666
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
425
667
|
}
|
|
426
668
|
// ../kit/src/input.ts
|
|
427
|
-
import
|
|
669
|
+
import process9 from "process";
|
|
428
670
|
var WHOLE = /^\d+$/;
|
|
429
671
|
function wholeNumber(value, name, fallback, min = 1) {
|
|
430
672
|
if (value === undefined)
|
|
@@ -436,7 +678,7 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
436
678
|
}
|
|
437
679
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
438
680
|
if (path === "-") {
|
|
439
|
-
if (
|
|
681
|
+
if (process9.stdin.isTTY)
|
|
440
682
|
fail(noStdin);
|
|
441
683
|
return Bun.stdin.text();
|
|
442
684
|
}
|
|
@@ -495,7 +737,7 @@ var OUTPUT_OPTIONS = {
|
|
|
495
737
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
496
738
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
497
739
|
};
|
|
498
|
-
function applyOutput(color, plain, env =
|
|
740
|
+
function applyOutput(color, plain, env = process10.env) {
|
|
499
741
|
const when = plain === true ? "never" : color ?? "auto";
|
|
500
742
|
if (when === "auto")
|
|
501
743
|
return;
|
|
@@ -518,7 +760,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
518
760
|
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
519
761
|
let parsed;
|
|
520
762
|
try {
|
|
521
|
-
parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
763
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
522
764
|
} catch (error) {
|
|
523
765
|
const message = parseError(error);
|
|
524
766
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -526,7 +768,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
526
768
|
const values = parsed.values;
|
|
527
769
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
528
770
|
if (values.help === true) {
|
|
529
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
771
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
530
772
|
throw new HelpShown;
|
|
531
773
|
}
|
|
532
774
|
checkChoices(parsed.values, all);
|
|
@@ -568,6 +810,18 @@ function listed(options, allowNegative) {
|
|
|
568
810
|
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
569
811
|
}));
|
|
570
812
|
}
|
|
813
|
+
function withAliases(args, options) {
|
|
814
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
815
|
+
if (named.size === 0)
|
|
816
|
+
return args;
|
|
817
|
+
const separator = args.indexOf("--");
|
|
818
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
819
|
+
return [...own.map((arg) => {
|
|
820
|
+
const at = arg.indexOf("=");
|
|
821
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
822
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
823
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
824
|
+
}
|
|
571
825
|
function withBare(args, options) {
|
|
572
826
|
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
573
827
|
if (bare.size === 0)
|
|
@@ -654,7 +908,7 @@ function nearestOption(message, options, allowNegative) {
|
|
|
654
908
|
}
|
|
655
909
|
// ../kit/src/process.ts
|
|
656
910
|
import { constants } from "os";
|
|
657
|
-
import
|
|
911
|
+
import process11 from "process";
|
|
658
912
|
var KILL_GRACE_MS = 2000;
|
|
659
913
|
function exitCodeOf(code, signal) {
|
|
660
914
|
if (code !== null)
|
|
@@ -674,7 +928,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
|
|
|
674
928
|
return;
|
|
675
929
|
try {
|
|
676
930
|
if (grouped)
|
|
677
|
-
|
|
931
|
+
process11.kill(-proc.pid, killing);
|
|
678
932
|
else
|
|
679
933
|
proc.kill(killing);
|
|
680
934
|
} catch {}
|
|
@@ -748,13 +1002,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
748
1002
|
var RESET_STYLE = `${ESC}[0m`;
|
|
749
1003
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
750
1004
|
// ../kit/src/cli.ts
|
|
751
|
-
import
|
|
1005
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
1006
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
1007
|
+
import process13 from "process";
|
|
752
1008
|
|
|
753
1009
|
// ../kit/src/usage.ts
|
|
754
1010
|
import { appendFileSync, mkdirSync } from "fs";
|
|
755
|
-
import { homedir } from "os";
|
|
756
|
-
import { dirname, isAbsolute, join } from "path";
|
|
757
|
-
import
|
|
1011
|
+
import { homedir as homedir3 } from "os";
|
|
1012
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
1013
|
+
import process12 from "process";
|
|
758
1014
|
|
|
759
1015
|
// ../kit/src/logs.ts
|
|
760
1016
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -768,14 +1024,14 @@ var usageError;
|
|
|
768
1024
|
function noteUsageError(message) {
|
|
769
1025
|
usageError = message;
|
|
770
1026
|
}
|
|
771
|
-
function stateHome(env =
|
|
1027
|
+
function stateHome(env = process12.env) {
|
|
772
1028
|
const dir = env.XDG_STATE_HOME;
|
|
773
|
-
return dir !== undefined && isAbsolute(dir) ? dir :
|
|
1029
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
774
1030
|
}
|
|
775
|
-
function usagePath(env =
|
|
776
|
-
return
|
|
1031
|
+
function usagePath(env = process12.env) {
|
|
1032
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
777
1033
|
}
|
|
778
|
-
function usageRecorded(env =
|
|
1034
|
+
function usageRecorded(env = process12.env) {
|
|
779
1035
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
780
1036
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
781
1037
|
}
|
|
@@ -789,12 +1045,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
789
1045
|
usageError = undefined;
|
|
790
1046
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
791
1047
|
}
|
|
792
|
-
function recordUsage(entry, env =
|
|
1048
|
+
function recordUsage(entry, env = process12.env) {
|
|
793
1049
|
if (!usageRecorded(env))
|
|
794
1050
|
return;
|
|
795
1051
|
try {
|
|
796
1052
|
const path = usagePath(env);
|
|
797
|
-
mkdirSync(
|
|
1053
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
798
1054
|
appendFileSync(path, `${JSON.stringify(entry)}
|
|
799
1055
|
`, { mode: 384 });
|
|
800
1056
|
} catch {}
|
|
@@ -880,8 +1136,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
880
1136
|
`);
|
|
881
1137
|
}
|
|
882
1138
|
function printError(prefix, message, hint, cause) {
|
|
883
|
-
const colors = paint(
|
|
884
|
-
const styled = takesControlCodes(
|
|
1139
|
+
const colors = paint(process13.stderr);
|
|
1140
|
+
const styled = takesControlCodes(process13.stderr);
|
|
885
1141
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
886
1142
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
887
1143
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -900,7 +1156,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
900
1156
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
901
1157
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
902
1158
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
903
|
-
if (error instanceof
|
|
1159
|
+
if (error instanceof Exit && error.code === 2)
|
|
904
1160
|
noteUsageError(error.message);
|
|
905
1161
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
906
1162
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
@@ -924,11 +1180,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
924
1180
|
}
|
|
925
1181
|
}
|
|
926
1182
|
if (name === undefined && level.path.length > 1) {
|
|
927
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1183
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
|
|
928
1184
|
return 2;
|
|
929
1185
|
}
|
|
930
1186
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
931
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
1187
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
|
|
932
1188
|
return 0;
|
|
933
1189
|
}
|
|
934
1190
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -1044,10 +1300,22 @@ async function printCandidates(found) {
|
|
|
1044
1300
|
console.log(line);
|
|
1045
1301
|
return 0;
|
|
1046
1302
|
}
|
|
1047
|
-
|
|
1303
|
+
function packageVersion(entry = Bun.main) {
|
|
1304
|
+
for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
|
|
1305
|
+
try {
|
|
1306
|
+
const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
|
|
1307
|
+
if (typeof version === "string")
|
|
1308
|
+
return version;
|
|
1309
|
+
} catch {}
|
|
1310
|
+
if (dirname3(dir) === dir)
|
|
1311
|
+
return "0.0.0";
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
async function runCli(cli, argv = process13.argv.slice(2)) {
|
|
1315
|
+
const version = cli.version ?? packageVersion();
|
|
1048
1316
|
if (argv[0] === COMPLETE)
|
|
1049
1317
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1050
|
-
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(
|
|
1318
|
+
const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
|
|
1051
1319
|
if (cli.usage !== false) {
|
|
1052
1320
|
try {
|
|
1053
1321
|
recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
|
|
@@ -1070,6 +1338,22 @@ function commandPath(scope, argv) {
|
|
|
1070
1338
|
}
|
|
1071
1339
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1072
1340
|
}
|
|
1341
|
+
// ../kit/src/compose.ts
|
|
1342
|
+
async function captureOutput(argv, { cwd, env } = {}) {
|
|
1343
|
+
const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
1344
|
+
const [stdout, stderr, code] = await Promise.all([run.stdout.text(), run.stderr.text(), run.exited]);
|
|
1345
|
+
return { code, stdout, stderr };
|
|
1346
|
+
}
|
|
1347
|
+
async function compose(args, { flags = [], ...options } = {}) {
|
|
1348
|
+
return captureOutput(["docker", "compose", ...flags, ...args], options);
|
|
1349
|
+
}
|
|
1350
|
+
function jsonLines(text) {
|
|
1351
|
+
const trimmed = text.trim();
|
|
1352
|
+
if (trimmed === "")
|
|
1353
|
+
return [];
|
|
1354
|
+
return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
|
|
1355
|
+
`).map((line) => JSON.parse(line));
|
|
1356
|
+
}
|
|
1073
1357
|
// ../kit/src/secrets.ts
|
|
1074
1358
|
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
1075
1359
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
@@ -1081,13 +1365,12 @@ function isSecretName(name) {
|
|
|
1081
1365
|
var {Glob } = globalThis.Bun;
|
|
1082
1366
|
var SESSION_FILES = new Glob("*.json");
|
|
1083
1367
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1084
|
-
// package.json
|
|
1085
|
-
var version = "0.9.2";
|
|
1086
|
-
|
|
1087
1368
|
// src/args.ts
|
|
1088
1369
|
var DEFAULT_ENV = "DATABASE_URL";
|
|
1089
|
-
var DEFAULT_LIMIT =
|
|
1090
|
-
var
|
|
1370
|
+
var DEFAULT_LIMIT = 20;
|
|
1371
|
+
var ALL_LIMIT = 100;
|
|
1372
|
+
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"]];
|
|
1373
|
+
var HOSTS_NOTE = 'db connects to a local host (localhost, 127.0.0.1, ::1) or a compose service only: any other host is refused (exit 2) unless it is listed under "allowedHosts" in ~/.config/kaynooo-cli/db.json.';
|
|
1091
1374
|
var WRITE_NOTE = "A write runs only when the database actually connected to has a name ending in _test (checked on the server, and a statement that names another database, or uses USE, SET, files or server objects, is not run); any other write is printed for you to run.";
|
|
1092
1375
|
var connectionOptions = {
|
|
1093
1376
|
env: { type: "string", short: "e", description: `environment key holding the connection URL (${DEFAULT_ENV}, postgres:// or mysql://), a compose service's host in it reached from here` },
|
|
@@ -1095,8 +1378,19 @@ var connectionOptions = {
|
|
|
1095
1378
|
container: { type: "string", short: "c", description: "read the running Postgres, MySQL or MariaDB container of this name, in any compose project or none, credentials from its environment" },
|
|
1096
1379
|
database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" }
|
|
1097
1380
|
};
|
|
1381
|
+
var rows = { type: "string", short: "n", aliases: ["limit"], description: `show at most this many rows, the rest counted (${DEFAULT_LIMIT}), 0 for none` };
|
|
1382
|
+
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"] };
|
|
1383
|
+
function rowLimit(values, fallback = DEFAULT_LIMIT) {
|
|
1384
|
+
return values.all === true ? ALL_LIMIT : wholeNumber(values.rows, "rows", fallback, 0);
|
|
1385
|
+
}
|
|
1386
|
+
var catalogOptions = {
|
|
1387
|
+
rows,
|
|
1388
|
+
all,
|
|
1389
|
+
json: jsonOption()
|
|
1390
|
+
};
|
|
1098
1391
|
var outputOptions = {
|
|
1099
|
-
|
|
1392
|
+
rows,
|
|
1393
|
+
all,
|
|
1100
1394
|
raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
|
|
1101
1395
|
json: jsonOption()
|
|
1102
1396
|
};
|
|
@@ -1437,7 +1731,7 @@ function shape(rows, limit, raw, exact = true) {
|
|
|
1437
1731
|
}
|
|
1438
1732
|
function render(shown, json) {
|
|
1439
1733
|
if (json)
|
|
1440
|
-
return
|
|
1734
|
+
return jsonText({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue);
|
|
1441
1735
|
if (shown.total === 0)
|
|
1442
1736
|
return "no rows";
|
|
1443
1737
|
const lines = [table([
|
|
@@ -1456,8 +1750,7 @@ function render(shown, json) {
|
|
|
1456
1750
|
|
|
1457
1751
|
// src/run.ts
|
|
1458
1752
|
import { isIP } from "net";
|
|
1459
|
-
import
|
|
1460
|
-
import process10 from "process";
|
|
1753
|
+
import process15 from "process";
|
|
1461
1754
|
var {SQL } = globalThis.Bun;
|
|
1462
1755
|
|
|
1463
1756
|
// src/compose.ts
|
|
@@ -1467,13 +1760,6 @@ var POSTGRES_IMAGE = /(?:^|\/)(?:postgres|postgis|timescaledb)[\w.-]*(?::|$)/;
|
|
|
1467
1760
|
var MYSQL_IMAGE = /(?:^|\/)(?:mysql|mariadb|percona)[\w.-]*(?::|$)/;
|
|
1468
1761
|
var LOOPBACK = new Set(["", "0.0.0.0", "::", "127.0.0.1", "::1"]);
|
|
1469
1762
|
var LEADING_SLASH = /^\//;
|
|
1470
|
-
function parsePs(text) {
|
|
1471
|
-
const trimmed = text.trim();
|
|
1472
|
-
if (trimmed === "")
|
|
1473
|
-
return [];
|
|
1474
|
-
return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
|
|
1475
|
-
`).map((line) => JSON.parse(line));
|
|
1476
|
-
}
|
|
1477
1763
|
function envOf(lines) {
|
|
1478
1764
|
return Object.fromEntries(lines.map((line) => {
|
|
1479
1765
|
const at = line.indexOf("=");
|
|
@@ -1555,12 +1841,12 @@ function stdoutOf(chunks) {
|
|
|
1555
1841
|
async function composeServices() {
|
|
1556
1842
|
let ps;
|
|
1557
1843
|
try {
|
|
1558
|
-
ps = await
|
|
1844
|
+
ps = await compose(["ps", "--format", "json"]);
|
|
1559
1845
|
} catch {
|
|
1560
1846
|
return [];
|
|
1561
1847
|
}
|
|
1562
1848
|
try {
|
|
1563
|
-
const rows = ps.code === 0 ?
|
|
1849
|
+
const rows = ps.code === 0 ? jsonLines(ps.stdout).filter((row) => row.State === "running" && row.ID !== undefined) : [];
|
|
1564
1850
|
if (rows.length === 0)
|
|
1565
1851
|
return [];
|
|
1566
1852
|
const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
|
|
@@ -1626,12 +1912,10 @@ function serviceUrl(service) {
|
|
|
1626
1912
|
}
|
|
1627
1913
|
|
|
1628
1914
|
// src/settings.ts
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
function settingsPath(home = homedir2()) {
|
|
1632
|
-
return join2(home, ".config", "db", "config.json");
|
|
1915
|
+
function settingsPath(home) {
|
|
1916
|
+
return userConfigReadPath("db", [["db", "config.json"]], { home });
|
|
1633
1917
|
}
|
|
1634
|
-
async function loadSettings(home
|
|
1918
|
+
async function loadSettings(home) {
|
|
1635
1919
|
const path = settingsPath(home);
|
|
1636
1920
|
const file = Bun.file(path);
|
|
1637
1921
|
if (!await file.exists())
|
|
@@ -1681,7 +1965,7 @@ var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
|
|
|
1681
1965
|
function allowsKeyRetrieval(url) {
|
|
1682
1966
|
try {
|
|
1683
1967
|
const host = hostOf(new URL(url));
|
|
1684
|
-
return isLocal(host) || DOCKER_NETWORK.test(host);
|
|
1968
|
+
return isLocal(host) || isIP(host) !== 0 && DOCKER_NETWORK.test(host);
|
|
1685
1969
|
} catch {
|
|
1686
1970
|
return false;
|
|
1687
1971
|
}
|
|
@@ -1696,7 +1980,7 @@ function serviceNamed(services, host, dialect) {
|
|
|
1696
1980
|
fail(`${host} names several services (${aliased.map((candidate) => candidate.name).join(", ")}): pick one with --service`);
|
|
1697
1981
|
return aliased[0];
|
|
1698
1982
|
}
|
|
1699
|
-
async function reachable(value, home
|
|
1983
|
+
async function reachable(value, home) {
|
|
1700
1984
|
let url;
|
|
1701
1985
|
try {
|
|
1702
1986
|
url = new URL(value);
|
|
@@ -1717,11 +2001,11 @@ async function reachable(value, home = homedir3()) {
|
|
|
1717
2001
|
fail(`${host} is neither local nor a compose service, so db does not connect to it: list it in "allowedHosts" in ${settingsPath(home)} to allow it`);
|
|
1718
2002
|
return url;
|
|
1719
2003
|
}
|
|
1720
|
-
async function connectionUrl({ env, service, container, database }, home
|
|
2004
|
+
async function connectionUrl({ env, service, container, database }, home) {
|
|
1721
2005
|
if (service !== undefined && container !== undefined)
|
|
1722
2006
|
fail("--service and --container name two databases: pick one");
|
|
1723
2007
|
const isNamed = service !== undefined || container !== undefined;
|
|
1724
|
-
const value = isNamed ? undefined :
|
|
2008
|
+
const value = isNamed ? undefined : process15.env[env ?? DEFAULT_ENV];
|
|
1725
2009
|
let url;
|
|
1726
2010
|
if (value !== undefined && value !== "")
|
|
1727
2011
|
url = await reachable(value, home);
|
|
@@ -1870,11 +2154,12 @@ var usage2 = `db query "<sql>"
|
|
|
1870
2154
|
|
|
1871
2155
|
Runs one read-only statement (the SQL as an argument, or on stdin) in a READ ONLY transaction that is rolled back, on Postgres, MySQL or MariaDB. A statement that would write is printed for you to run instead, and exits 1 without running.
|
|
1872
2156
|
|
|
1873
|
-
|
|
2157
|
+
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.
|
|
2158
|
+
Statements time out after 30 seconds and show at most -n rows (${DEFAULT_LIMIT}, --all for 100), a Postgres select being read through a cursor that stops one row past it. Columns named like emails, phones, tokens, secrets, passwords or hashes show *** unless --raw, and every message is scrubbed of the URL and password.
|
|
1874
2159
|
|
|
1875
|
-
${
|
|
2160
|
+
${WRITE_NOTE}
|
|
1876
2161
|
|
|
1877
|
-
|
|
2162
|
+
${HOSTS_NOTE}`;
|
|
1878
2163
|
var options = { ...connectionOptions, ...outputOptions };
|
|
1879
2164
|
var WRITE_EXIT = 1;
|
|
1880
2165
|
var NO_SQL = "no SQL given: pass it as an argument or on stdin";
|
|
@@ -1896,9 +2181,9 @@ function isWrite(sql) {
|
|
|
1896
2181
|
return inspect(sql, "postgres").reasons.length > 0 || inspect(sql, "mysql").reasons.length > 0;
|
|
1897
2182
|
}
|
|
1898
2183
|
async function query(args) {
|
|
1899
|
-
const parsed = parse(args, usage2, options);
|
|
2184
|
+
const parsed = parse(args, usage2, options, { exits: EXITS });
|
|
1900
2185
|
const { values, positionals } = parsed;
|
|
1901
|
-
const limit =
|
|
2186
|
+
const limit = rowLimit(values);
|
|
1902
2187
|
const sql = await readSql(positionals);
|
|
1903
2188
|
let url;
|
|
1904
2189
|
try {
|
|
@@ -1916,7 +2201,7 @@ async function query(args) {
|
|
|
1916
2201
|
return handBack(sql, verdict.reasons, databaseOfUrl(url).endsWith(TEST_SUFFIX) ? `; not run on this ${TEST_SUFFIX} database either: ${written.reasons.join("; ")}` : "");
|
|
1917
2202
|
const shown = shape(written.rows, limit, values.raw === true, false);
|
|
1918
2203
|
if (values.json === true)
|
|
1919
|
-
console.log(
|
|
2204
|
+
console.log(jsonText({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue));
|
|
1920
2205
|
else
|
|
1921
2206
|
console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
|
|
1922
2207
|
${render(shown, false)}`}`);
|
|
@@ -1929,9 +2214,37 @@ ${render(shown, false)}`}`);
|
|
|
1929
2214
|
return 0;
|
|
1930
2215
|
}
|
|
1931
2216
|
|
|
2217
|
+
// src/commands/explain.ts
|
|
2218
|
+
var usage3 = `db explain "<sql>"
|
|
2219
|
+
|
|
2220
|
+
Prints the plan the engine would run for one read (the SQL as an argument, or on stdin) without running it: EXPLAIN alone, never ANALYZE, which would execute the statement. The statement must start with SELECT, WITH, VALUES or TABLE and passes the same read-only guard as a query; EXPLAIN and ANALYZE written by hand are refused.
|
|
2221
|
+
|
|
2222
|
+
${HOSTS_NOTE}`;
|
|
2223
|
+
var options2 = { ...connectionOptions, json: jsonOption() };
|
|
2224
|
+
var READ_START = /^\s*(?:select|with|values|table)\b/i;
|
|
2225
|
+
var TRAILING_SEMICOLON = /;\s*$/;
|
|
2226
|
+
function explainSql(sql, dialect) {
|
|
2227
|
+
const verdict = inspect(sql, dialect);
|
|
2228
|
+
if (!READ_START.test(sql) || verdict.reasons.length > 0 || verdict.statements > 1)
|
|
2229
|
+
fail(`not a plain read to explain: ${verdict.reasons.join("; ") || "start with SELECT, WITH, VALUES or TABLE, one statement at a time"}`);
|
|
2230
|
+
return `EXPLAIN ${sql.trim().replace(TRAILING_SEMICOLON, "")}`;
|
|
2231
|
+
}
|
|
2232
|
+
async function explain(args) {
|
|
2233
|
+
const { values, positionals } = parse(args, usage3, options2, { exits: EXITS });
|
|
2234
|
+
const sql = await readSql(positionals);
|
|
2235
|
+
const url = await connectionUrl(values);
|
|
2236
|
+
const dialect = dialectOf(new URL(url));
|
|
2237
|
+
const rows = await readRows(url, explainSql(sql, dialect));
|
|
2238
|
+
if (dialect === "postgres" && values.json !== true)
|
|
2239
|
+
console.log(rows.map((row) => String(row["QUERY PLAN"])).join(`
|
|
2240
|
+
`));
|
|
2241
|
+
else
|
|
2242
|
+
console.log(render(shape(rows, rows.length, true), values.json === true));
|
|
2243
|
+
return 0;
|
|
2244
|
+
}
|
|
2245
|
+
|
|
1932
2246
|
// src/commands/schema.ts
|
|
1933
|
-
var
|
|
1934
|
-
var EXITS = "Exits 0 when it listed them, 1 when the database refused or was unreachable, 2 on a usage error or a host that is not allowed.";
|
|
2247
|
+
var options3 = { ...connectionOptions, ...catalogOptions };
|
|
1935
2248
|
var TABLES = `
|
|
1936
2249
|
select n.nspname as schema, c.relname as name,
|
|
1937
2250
|
case c.relkind when 'r' then 'table' when 'p' then 'partitioned' when 'v' then 'view' when 'm' then 'matview' else 'foreign' end as kind,
|
|
@@ -1955,6 +2268,30 @@ from information_schema.columns c
|
|
|
1955
2268
|
where c.table_name = $1 and ($2::text is null or c.table_schema = $2)
|
|
1956
2269
|
and c.table_schema not in ('pg_catalog', 'information_schema')
|
|
1957
2270
|
order by c.table_schema, c.ordinal_position`;
|
|
2271
|
+
var INDEXES = `
|
|
2272
|
+
select i.relname as name, ix.indisunique as is_unique, ix.indisprimary as primary_key, pg_get_indexdef(ix.indexrelid) as definition
|
|
2273
|
+
from pg_index ix
|
|
2274
|
+
join pg_class t on t.oid = ix.indrelid
|
|
2275
|
+
join pg_class i on i.oid = ix.indexrelid
|
|
2276
|
+
join pg_namespace n on n.oid = t.relnamespace
|
|
2277
|
+
where t.relname = $1 and ($2::text is null or n.nspname = $2) and n.nspname not in ('pg_catalog', 'information_schema')
|
|
2278
|
+
order by n.nspname, i.relname`;
|
|
2279
|
+
var FOREIGN_KEYS = `
|
|
2280
|
+
select c.conname as name, pg_get_constraintdef(c.oid) as definition
|
|
2281
|
+
from pg_constraint c
|
|
2282
|
+
join pg_class t on t.oid = c.conrelid
|
|
2283
|
+
join pg_namespace n on n.oid = t.relnamespace
|
|
2284
|
+
where c.contype = 'f' and t.relname = $1 and ($2::text is null or n.nspname = $2) and n.nspname not in ('pg_catalog', 'information_schema')
|
|
2285
|
+
order by n.nspname, c.conname`;
|
|
2286
|
+
var SEARCH = `
|
|
2287
|
+
select table_schema as schema, table_name as "table", null::text as "column", null::text as type
|
|
2288
|
+
from information_schema.tables
|
|
2289
|
+
where table_schema not in ('pg_catalog', 'information_schema') and table_name ilike $1
|
|
2290
|
+
union all
|
|
2291
|
+
select table_schema, table_name, column_name, data_type
|
|
2292
|
+
from information_schema.columns
|
|
2293
|
+
where table_schema not in ('pg_catalog', 'information_schema') and column_name ilike $1
|
|
2294
|
+
order by 1, 2, 3`;
|
|
1958
2295
|
var MYSQL_SYSTEM = "'mysql', 'information_schema', 'performance_schema', 'sys'";
|
|
1959
2296
|
var MYSQL_TABLES = `
|
|
1960
2297
|
select table_schema as \`schema\`, table_name as name,
|
|
@@ -1974,11 +2311,30 @@ var MYSQL_COLUMNS = `
|
|
|
1974
2311
|
select table_schema as \`schema\`, column_name as name, column_type as type, is_nullable as nullable, column_default as default_value, column_key = 'PRI' as primary_key
|
|
1975
2312
|
from information_schema.columns
|
|
1976
2313
|
where table_name = ?`;
|
|
2314
|
+
var MYSQL_SEARCH = `
|
|
2315
|
+
select table_schema as \`schema\`, table_name as \`table\`, null as \`column\`, null as type
|
|
2316
|
+
from information_schema.tables
|
|
2317
|
+
where table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM}) and lower(table_name) like lower(?)
|
|
2318
|
+
union all
|
|
2319
|
+
select table_schema, table_name, column_name, column_type
|
|
2320
|
+
from information_schema.columns
|
|
2321
|
+
where table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM}) and lower(column_name) like lower(?)
|
|
2322
|
+
order by 1, 2, 3`;
|
|
2323
|
+
var MYSQL_INDEXES = `
|
|
2324
|
+
select index_name as name, non_unique = 0 as is_unique, index_name = 'PRIMARY' as primary_key, group_concat(column_name order by seq_in_index) as columns, index_type as type
|
|
2325
|
+
from information_schema.statistics
|
|
2326
|
+
where table_name = ?`;
|
|
2327
|
+
var MYSQL_FOREIGN_KEYS = `
|
|
2328
|
+
select constraint_name as name, group_concat(column_name order by ordinal_position) as columns, concat(referenced_table_schema, '.', referenced_table_name) as references_table, group_concat(referenced_column_name order by ordinal_position) as referenced_columns
|
|
2329
|
+
from information_schema.key_column_usage
|
|
2330
|
+
where referenced_table_name is not null and table_name = ?`;
|
|
2331
|
+
var LIKE_SPECIALS = /[\\%_]/g;
|
|
2332
|
+
var containing = (text) => `%${text.replace(LIKE_SPECIALS, "\\$&")}%`;
|
|
1977
2333
|
async function show(args, usage, work) {
|
|
1978
|
-
const parsed = parse(args, usage,
|
|
2334
|
+
const parsed = parse(args, usage, options3, { exits: EXITS });
|
|
1979
2335
|
const { values, positionals } = parsed;
|
|
1980
2336
|
const plans = work(positionals);
|
|
1981
|
-
const limit =
|
|
2337
|
+
const limit = rowLimit(values);
|
|
1982
2338
|
const url = await connectionUrl(values);
|
|
1983
2339
|
const { sql, params } = plans[dialectOf(new URL(url))];
|
|
1984
2340
|
const rows = await readRows(url, sql, params, limit);
|
|
@@ -1990,44 +2346,81 @@ async function tables(args) {
|
|
|
1990
2346
|
|
|
1991
2347
|
Lists the tables, views and materialized views outside the system schemas, with an estimated row count.
|
|
1992
2348
|
|
|
1993
|
-
${HOSTS_NOTE}
|
|
1994
|
-
|
|
1995
|
-
${EXITS}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
|
|
2349
|
+
${HOSTS_NOTE}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
|
|
1996
2350
|
}
|
|
1997
2351
|
async function databases(args) {
|
|
1998
2352
|
return show(args, `db dbs
|
|
1999
2353
|
|
|
2000
2354
|
Lists the databases the connection may open, with their size, marking the one it reads, so --database can pick another.
|
|
2001
2355
|
|
|
2002
|
-
${HOSTS_NOTE}
|
|
2356
|
+
${HOSTS_NOTE}`, () => ({ postgres: { sql: DATABASES, params: [] }, mysql: { sql: MYSQL_DATABASES, params: [] } }));
|
|
2357
|
+
}
|
|
2358
|
+
async function search(args) {
|
|
2359
|
+
return show(args, `db search <text>
|
|
2360
|
+
|
|
2361
|
+
Finds the tables and columns whose name contains the text, case insensitive, outside the system schemas (a table match has no column). Use it to locate where a field lives before describing a table.
|
|
2003
2362
|
|
|
2004
|
-
${
|
|
2363
|
+
${HOSTS_NOTE}`, ([text, ...extra]) => {
|
|
2364
|
+
if (text === undefined || extra.length > 0)
|
|
2365
|
+
fail("db search takes one text");
|
|
2366
|
+
const pattern = containing(text);
|
|
2367
|
+
return { postgres: { sql: SEARCH, params: [pattern] }, mysql: { sql: MYSQL_SEARCH, params: [pattern, pattern] } };
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
function tableScope(target, extra) {
|
|
2371
|
+
if (target === undefined || extra.length > 0)
|
|
2372
|
+
fail("db describe takes one table name");
|
|
2373
|
+
const [first, second] = target.split(".");
|
|
2374
|
+
return second === undefined ? { table: target, schema: undefined } : { table: second, schema: first };
|
|
2375
|
+
}
|
|
2376
|
+
var MYSQL_ANY_SCHEMA = ` and table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})`;
|
|
2377
|
+
function describePlans(table, schema) {
|
|
2378
|
+
const scope = schema === undefined ? MYSQL_ANY_SCHEMA : " and table_schema = ?";
|
|
2379
|
+
const mysqlParams = schema === undefined ? [table] : [table, schema];
|
|
2380
|
+
const postgresParams = [table, schema ?? null];
|
|
2381
|
+
return {
|
|
2382
|
+
columns: { postgres: { sql: COLUMNS, params: postgresParams }, mysql: { sql: `${MYSQL_COLUMNS}${scope}
|
|
2383
|
+
order by table_schema, ordinal_position`, params: mysqlParams } },
|
|
2384
|
+
indexes: { postgres: { sql: INDEXES, params: postgresParams }, mysql: { sql: `${MYSQL_INDEXES}${scope}
|
|
2385
|
+
group by table_schema, index_name, non_unique, index_type
|
|
2386
|
+
order by table_schema, index_name`, params: mysqlParams } },
|
|
2387
|
+
foreignKeys: { postgres: { sql: FOREIGN_KEYS, params: postgresParams }, mysql: { sql: `${MYSQL_FOREIGN_KEYS}${scope}
|
|
2388
|
+
group by table_schema, constraint_name, referenced_table_schema, referenced_table_name
|
|
2389
|
+
order by table_schema, constraint_name`, params: mysqlParams } }
|
|
2390
|
+
};
|
|
2005
2391
|
}
|
|
2006
2392
|
async function describe(args) {
|
|
2007
|
-
|
|
2393
|
+
const usage = `db describe <table>
|
|
2008
2394
|
|
|
2009
|
-
Lists a table's columns with type, nullability, default and primary key. Takes \`schema.table\` to tell apart tables of the same name (the database, on MySQL).
|
|
2395
|
+
Lists a table's columns with type, nullability, default and primary key, then its indexes and foreign keys. Takes \`schema.table\` to tell apart tables of the same name (the database, on MySQL).
|
|
2010
2396
|
|
|
2011
|
-
${HOSTS_NOTE}
|
|
2397
|
+
${HOSTS_NOTE}`;
|
|
2398
|
+
const { values, positionals: [target, ...extra] } = parse(args, usage, options3, { exits: EXITS });
|
|
2399
|
+
const { table, schema } = tableScope(target, extra);
|
|
2400
|
+
const plans = describePlans(table, schema);
|
|
2401
|
+
const limit = rowLimit(values);
|
|
2402
|
+
const url = await connectionUrl(values);
|
|
2403
|
+
const dialect = dialectOf(new URL(url));
|
|
2404
|
+
const ask = async (plan, cap) => readRows(url, plan[dialect].sql, plan[dialect].params, cap);
|
|
2405
|
+
const columns = shape(await ask(plans.columns, limit), limit, true, false);
|
|
2406
|
+
const indexes = await ask(plans.indexes);
|
|
2407
|
+
const foreignKeys = await ask(plans.foreignKeys);
|
|
2408
|
+
if (values.json === true)
|
|
2409
|
+
console.log(jsonText({ columns: columns.columns, rows: columns.rows, truncated: columns.truncated, masked: columns.masked, indexes, foreignKeys }, jsonValue));
|
|
2410
|
+
else
|
|
2411
|
+
console.log(`${render(columns, false)}
|
|
2012
2412
|
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
return {
|
|
2020
|
-
postgres: { sql: COLUMNS, params: second === undefined ? [first, null] : [second, first] },
|
|
2021
|
-
mysql: { sql: `${MYSQL_COLUMNS}${mysqlScope}
|
|
2022
|
-
order by table_schema, ordinal_position`, params: second === undefined ? [table] : [table, first] }
|
|
2023
|
-
};
|
|
2024
|
-
});
|
|
2413
|
+
indexes
|
|
2414
|
+
${render(shape(indexes, indexes.length, true), false)}
|
|
2415
|
+
|
|
2416
|
+
foreign keys
|
|
2417
|
+
${render(shape(foreignKeys, foreignKeys.length, true), false)}`);
|
|
2418
|
+
return 0;
|
|
2025
2419
|
}
|
|
2026
2420
|
|
|
2027
2421
|
// src/commands/table.ts
|
|
2028
2422
|
var SAMPLE_LIMIT = 5;
|
|
2029
2423
|
var NAME = /^[A-Z_][\w$]*(?:\.[A-Z_][\w$]*)?$/i;
|
|
2030
|
-
var EXITS2 = "Exits 0 when it ran, 1 when the database refused or was unreachable, 2 on a usage error or a host that is not allowed.";
|
|
2031
2424
|
function quotedTable(target, dialect) {
|
|
2032
2425
|
if (!NAME.test(target))
|
|
2033
2426
|
fail(`${target} is not a table name: use name or schema.name`);
|
|
@@ -2045,14 +2438,14 @@ var where = { type: "string", short: "w", description: "only the rows matching t
|
|
|
2045
2438
|
var sampleOptions = { ...connectionOptions, ...outputOptions, where };
|
|
2046
2439
|
var countOptions = { ...connectionOptions, json: outputOptions.json, where };
|
|
2047
2440
|
async function run(args, usage, options, build) {
|
|
2048
|
-
const parsed = parse(args, usage, options);
|
|
2441
|
+
const parsed = parse(args, usage, options, { exits: EXITS });
|
|
2049
2442
|
const { values, positionals } = parsed;
|
|
2050
2443
|
const [target, ...extra] = positionals;
|
|
2051
2444
|
if (target === undefined || extra.length > 0)
|
|
2052
2445
|
fail("give one table name");
|
|
2053
2446
|
const url = await connectionUrl(values);
|
|
2054
2447
|
const dialect = dialectOf(new URL(url));
|
|
2055
|
-
const limit =
|
|
2448
|
+
const limit = rowLimit(values, SAMPLE_LIMIT);
|
|
2056
2449
|
const sql = build(target, dialect, { limit, where: values.where });
|
|
2057
2450
|
const verdict = inspect(sql, dialect);
|
|
2058
2451
|
if (verdict.reasons.length > 0 || verdict.statements > 1)
|
|
@@ -2061,35 +2454,32 @@ async function run(args, usage, options, build) {
|
|
|
2061
2454
|
return 0;
|
|
2062
2455
|
}
|
|
2063
2456
|
async function sample(args) {
|
|
2064
|
-
return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}] [--where <sql>]
|
|
2457
|
+
return run(args, `db sample <table> [-n ${SAMPLE_LIMIT}|--all] [--where <sql>]
|
|
2065
2458
|
|
|
2066
2459
|
Prints a few rows of a table (\`schema.table\` to pick a schema, the name is case sensitive on Postgres), sensitive columns masked as in a query.
|
|
2067
2460
|
|
|
2068
|
-
${HOSTS_NOTE}
|
|
2069
|
-
|
|
2070
|
-
${EXITS2}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
|
|
2461
|
+
${HOSTS_NOTE}`, sampleOptions, (target, dialect, { limit, where }) => sampleSql(target, dialect, limit, where));
|
|
2071
2462
|
}
|
|
2072
2463
|
async function count(args) {
|
|
2073
2464
|
return run(args, `db count <table> [--where <sql>]
|
|
2074
2465
|
|
|
2075
2466
|
Prints the number of rows of a table (the name is case sensitive on Postgres), or of those matching a condition.
|
|
2076
2467
|
|
|
2077
|
-
${HOSTS_NOTE}
|
|
2078
|
-
|
|
2079
|
-
${EXITS2}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
|
|
2468
|
+
${HOSTS_NOTE}`, countOptions, (target, dialect, { where }) => countSql(target, dialect, where));
|
|
2080
2469
|
}
|
|
2081
2470
|
|
|
2082
2471
|
// src/cli.ts
|
|
2083
|
-
|
|
2472
|
+
process16.exitCode = await runCli({
|
|
2084
2473
|
name: "db",
|
|
2085
|
-
version,
|
|
2086
2474
|
about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
|
|
2087
2475
|
replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
|
|
2088
|
-
examples: ['db "select count(*) from users"', ['db -c booki-db-1 "select count(*) from users"', "a container outside the compose project"], ["db describe users", "the columns of a table"]],
|
|
2476
|
+
examples: ['db "select count(*) from users"', ['db -c booki-db-1 "select count(*) from users"', "a container outside the compose project"], ["db describe users", "the columns, indexes and foreign keys of a table"], ["db search email", "where a field lives"], [`db explain "select * from users where email = 'a'"`, "the plan, nothing executed"]],
|
|
2089
2477
|
commands: {
|
|
2090
2478
|
query: { run: query, summary: 'run one read-only statement (the default: db "<sql>"), a write runs on a _test database and is printed otherwise' },
|
|
2091
2479
|
tables: { run: tables, summary: "list tables and views with an estimated row count" },
|
|
2092
|
-
describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key" },
|
|
2480
|
+
describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key, then its indexes and foreign keys" },
|
|
2481
|
+
search: { run: search, summary: "find the tables and columns whose name contains a text" },
|
|
2482
|
+
explain: { run: explain, summary: "the plan of one read without running it (EXPLAIN, never ANALYZE)" },
|
|
2093
2483
|
sample: { run: sample, summary: "a few rows of a table, sensitive columns masked" },
|
|
2094
2484
|
count: { run: count, summary: "the number of rows of a table, optionally matching --where" },
|
|
2095
2485
|
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.11.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.22.0"
|
|
32
32
|
}
|
|
33
33
|
}
|