@kaynooo/cli-db 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +233 -151
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,10 +2,10 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process8 from "process";
5
+ import process11 from "process";
6
6
 
7
7
  // ../kit/src/args.ts
8
- import process3 from "process";
8
+ import process5 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
@@ -355,6 +355,55 @@ function narrow(rows, widths, limit) {
355
355
  return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
356
356
  }
357
357
 
358
+ // ../kit/src/help.ts
359
+ import process3 from "process";
360
+ var OPTIONAL = /\[[^\]]+\]/g;
361
+ var USAGE_PREFIX = /^usage:\s*/i;
362
+ var FULL_STOP = /\.$/;
363
+ function usageLine(usage, colors = paint(process3.stdout)) {
364
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
365
+ }
366
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
367
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
368
+ `);
369
+ }
370
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
371
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
372
+ }
373
+ function wantsHelpJson(env = process3.env) {
374
+ return env.KIT_HELP === "json";
375
+ }
376
+ function description(usage, { examples = [], replaces } = {}) {
377
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
378
+ `);
379
+ const first = lines[0];
380
+ const colon = first.indexOf(": ");
381
+ const prose = lines[lines.indexOf("") + 1] ?? "";
382
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
383
+ return {
384
+ synopsis: colon === -1 ? first : first.slice(0, colon),
385
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
386
+ ...replaces === undefined ? {} : { replaces },
387
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
388
+ };
389
+ }
390
+ function exampleRows(examples, colors = paint(process3.stdout)) {
391
+ if (examples.length === 0)
392
+ return [];
393
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
394
+ }
395
+ function optionRows(options, colors = paint(process3.stdout)) {
396
+ const rows = Object.entries(options).map(([name, option]) => {
397
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
398
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
399
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
400
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
401
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
402
+ });
403
+ const width = Math.max(0, ...rows.map((row) => row.width));
404
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
405
+ }
406
+
358
407
  // ../kit/src/text.ts
359
408
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
360
409
  function distance(a, b) {
@@ -374,8 +423,31 @@ function closest(name, names) {
374
423
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
375
424
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
376
425
  }
426
+ // ../kit/src/input.ts
427
+ import process4 from "process";
428
+ var WHOLE = /^\d+$/;
429
+ function wholeNumber(value, name, fallback, min = 1) {
430
+ if (value === undefined)
431
+ return fallback;
432
+ const number = Number(value);
433
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
434
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
435
+ return number;
436
+ }
437
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
438
+ if (path === "-") {
439
+ if (process4.stdin.isTTY)
440
+ fail(noStdin);
441
+ return Bun.stdin.text();
442
+ }
443
+ const file = Bun.file(path);
444
+ if (!await file.exists())
445
+ fail(`no file ${path}`);
446
+ return file.text();
447
+ }
377
448
 
378
449
  // ../kit/src/args.ts
450
+ var DASHES = /^-+/;
379
451
  function jsonOption(holds) {
380
452
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
381
453
  }
@@ -419,58 +491,11 @@ class Completing {
419
491
  }
420
492
  }
421
493
  var completion = { active: false };
422
- var OPTIONAL = /\[[^\]]+\]/g;
423
- var USAGE_PREFIX = /^usage:\s*/i;
424
- var FULL_STOP = /\.$/;
425
- var DASHES = /^-+/;
426
- function usageLine(usage, colors = paint(process3.stdout)) {
427
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
428
- }
429
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
430
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
431
- `);
432
- }
433
- function replacesRows(replaces, colors = paint(process3.stdout)) {
434
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
435
- }
436
- function wantsHelpJson(env = process3.env) {
437
- return env.KIT_HELP === "json";
438
- }
439
- function description(usage, { examples = [], replaces } = {}) {
440
- const lines = usage.replace(USAGE_PREFIX, "").split(`
441
- `);
442
- const first = lines[0];
443
- const colon = first.indexOf(": ");
444
- const prose = lines[lines.indexOf("") + 1] ?? "";
445
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
446
- return {
447
- synopsis: colon === -1 ? first : first.slice(0, colon),
448
- summary: colon === -1 ? fallback : first.slice(colon + 2),
449
- ...replaces === undefined ? {} : { replaces },
450
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
451
- };
452
- }
453
- function exampleRows(examples, colors = paint(process3.stdout)) {
454
- if (examples.length === 0)
455
- return [];
456
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
457
- }
458
- function optionRows(options, colors = paint(process3.stdout)) {
459
- const rows = Object.entries(options).map(([name, option]) => {
460
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
461
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
462
- const placeholder = option.optional === undefined ? named : `[${named}]`;
463
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
464
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
465
- });
466
- const width = Math.max(0, ...rows.map((row) => row.width));
467
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
468
- }
469
494
  var OUTPUT_OPTIONS = {
470
495
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
471
496
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
472
497
  };
473
- function applyOutput(color, plain, env = process3.env) {
498
+ function applyOutput(color, plain, env = process5.env) {
474
499
  const when = plain === true ? "never" : color ?? "auto";
475
500
  if (when === "auto")
476
501
  return;
@@ -627,29 +652,9 @@ function nearestOption(message, options, allowNegative) {
627
652
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
628
653
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
629
654
  }
630
- var WHOLE = /^\d+$/;
631
- function wholeNumber(value, name, fallback, min = 1) {
632
- if (value === undefined)
633
- return fallback;
634
- const number = Number(value);
635
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
636
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
637
- return number;
638
- }
639
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
640
- if (path === "-") {
641
- if (process3.stdin.isTTY)
642
- fail(noStdin);
643
- return Bun.stdin.text();
644
- }
645
- const file = Bun.file(path);
646
- if (!await file.exists())
647
- fail(`no file ${path}`);
648
- return file.text();
649
- }
650
655
  // ../kit/src/process.ts
651
656
  import { constants } from "os";
652
- import process4 from "process";
657
+ import process6 from "process";
653
658
  var KILL_GRACE_MS = 2000;
654
659
  function exitCodeOf(code, signal) {
655
660
  if (code !== null)
@@ -669,7 +674,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
669
674
  return;
670
675
  try {
671
676
  if (grouped)
672
- process4.kill(-proc.pid, killing);
677
+ process6.kill(-proc.pid, killing);
673
678
  else
674
679
  proc.kill(killing);
675
680
  } catch {}
@@ -743,7 +748,59 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
743
748
  var RESET_STYLE = `${ESC}[0m`;
744
749
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
745
750
  // ../kit/src/cli.ts
746
- import process5 from "process";
751
+ import process8 from "process";
752
+
753
+ // ../kit/src/usage.ts
754
+ import { appendFileSync, mkdirSync } from "fs";
755
+ import { homedir } from "os";
756
+ import { dirname, isAbsolute, join } from "path";
757
+ import process7 from "process";
758
+
759
+ // ../kit/src/logs.ts
760
+ var DAY_MS = 24 * 60 * 60 * 1000;
761
+ var CLI_FOLDER = "kaynooo-cli";
762
+
763
+ // ../kit/src/usage.ts
764
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
765
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
766
+ var LONGEST_NAME = 40;
767
+ var usageError;
768
+ function noteUsageError(message) {
769
+ usageError = message;
770
+ }
771
+ function stateHome(env = process7.env) {
772
+ const dir = env.XDG_STATE_HOME;
773
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
774
+ }
775
+ function usagePath(env = process7.env) {
776
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
777
+ }
778
+ function usageRecorded(env = process7.env) {
779
+ const off = env.KAYNOOO_CLI_NO_USAGE;
780
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
781
+ }
782
+ function flagNames(argv) {
783
+ const end = argv.indexOf("--");
784
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
785
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
786
+ }
787
+ function usageEntry(bin, command, argv, code, now = new Date) {
788
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
789
+ usageError = undefined;
790
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
791
+ }
792
+ function recordUsage(entry, env = process7.env) {
793
+ if (!usageRecorded(env))
794
+ return;
795
+ try {
796
+ const path = usagePath(env);
797
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
798
+ appendFileSync(path, `${JSON.stringify(entry)}
799
+ `, { mode: 384 });
800
+ } catch {}
801
+ }
802
+
803
+ // ../kit/src/cli.ts
747
804
  var LEVEL_OPTIONS = {
748
805
  ...OUTPUT_OPTIONS,
749
806
  help: { type: "boolean", short: "h", description: "show this help" }
@@ -796,7 +853,7 @@ async function expand(scope, words) {
796
853
  }
797
854
  return { ...scope, commands, lazy: [] };
798
855
  }
799
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
856
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
800
857
  const colors = paint(stream);
801
858
  const prefix = path.join(" ");
802
859
  const summary = await resolveSummary(lazySummary);
@@ -823,8 +880,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
823
880
  `);
824
881
  }
825
882
  function printError(prefix, message, hint, cause) {
826
- const colors = paint(process5.stderr);
827
- const styled = takesControlCodes(process5.stderr);
883
+ const colors = paint(process8.stderr);
884
+ const styled = takesControlCodes(process8.stderr);
828
885
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
829
886
  const under = (label, text, tint) => text === undefined ? "" : `
830
887
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -843,6 +900,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
843
900
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
844
901
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
845
902
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
903
+ if (error instanceof UsageError)
904
+ noteUsageError(error.message);
846
905
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
847
906
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
848
907
  return error instanceof Exit ? error.code : 1;
@@ -865,11 +924,11 @@ async function dispatch(level, typed, { version, redact }) {
865
924
  }
866
925
  }
867
926
  if (name === undefined && level.path.length > 1) {
868
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
927
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
869
928
  return 2;
870
929
  }
871
930
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
872
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
931
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
873
932
  return 0;
874
933
  }
875
934
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -985,13 +1044,32 @@ async function printCandidates(found) {
985
1044
  console.log(line);
986
1045
  return 0;
987
1046
  }
988
- async function runCli(cli, argv = process5.argv.slice(2)) {
1047
+ async function runCli(cli, argv = process8.argv.slice(2)) {
989
1048
  if (argv[0] === COMPLETE)
990
1049
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
991
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
1050
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
1051
+ if (cli.usage !== false) {
1052
+ try {
1053
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1054
+ } catch {}
1055
+ }
1056
+ return code;
1057
+ }
1058
+ function commandPath(scope, argv) {
1059
+ const path = [];
1060
+ let level = scope;
1061
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
1062
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1063
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1064
+ if (command === undefined)
1065
+ break;
1066
+ path.push(word);
1067
+ if (!("commands" in command))
1068
+ break;
1069
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1070
+ }
1071
+ return path.length === 0 ? undefined : path.join(" ");
992
1072
  }
993
- // ../kit/src/logs.ts
994
- var DAY_MS = 24 * 60 * 60 * 1000;
995
1073
  // ../kit/src/secrets.ts
996
1074
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
997
1075
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1004,7 +1082,7 @@ var {Glob } = globalThis.Bun;
1004
1082
  var SESSION_FILES = new Glob("*.json");
1005
1083
  var ACCOUNT_DIRS = new Glob("*/sessions");
1006
1084
  // package.json
1007
- var version = "0.9.1";
1085
+ var version = "0.9.2";
1008
1086
 
1009
1087
  // src/args.ts
1010
1088
  var DEFAULT_ENV = "DATABASE_URL";
@@ -1023,13 +1101,12 @@ var outputOptions = {
1023
1101
  json: jsonOption()
1024
1102
  };
1025
1103
 
1026
- // src/guard.ts
1104
+ // src/sql-tokens.ts
1027
1105
  var WORD_START = /[a-z_\P{ASCII}]/iu;
1028
1106
  var WORD_PART = /[\w$\P{ASCII}]/u;
1029
1107
  var SPACE = /\s/;
1030
1108
  var ESCAPE_PREFIX = /e/i;
1031
1109
  var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
1032
- var LOCK_KIND = /^(?:update|share|no|key)$/;
1033
1110
  var DIGITS = /\d/;
1034
1111
  var COMMAND_ENDS = ";";
1035
1112
  var UNCLOSED = "unclosed";
@@ -1037,11 +1114,6 @@ var NUL = "\x00";
1037
1114
  var UNICODE_IDENTIFIER = 'U&"';
1038
1115
  var UNICODE_PREFIX = /u&$/i;
1039
1116
  var LINE_END = /[\r\n]/;
1040
- var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1041
- var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1042
- var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1043
- var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1044
- var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1045
1117
  function tokenize(sql, dialect = "postgres") {
1046
1118
  const tokens = [];
1047
1119
  const isMysql = dialect === "mysql";
@@ -1139,6 +1211,64 @@ function splitStatements(tokens) {
1139
1211
  }
1140
1212
  return statements.filter((statement) => statement.length > 0);
1141
1213
  }
1214
+
1215
+ // src/guard-test.ts
1216
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1217
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1218
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1219
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1220
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1221
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1222
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1223
+ function foreignDatabases(statement, database) {
1224
+ const found = [];
1225
+ for (const [index, token] of statement.entries()) {
1226
+ if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
1227
+ found.push(token.text);
1228
+ }
1229
+ return found;
1230
+ }
1231
+ function definesServerObject(statement, dialect) {
1232
+ if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1233
+ return null;
1234
+ const kind = statement.slice(1).find((token) => !DEFINITION_MODIFIERS.has(token.text))?.text ?? "";
1235
+ if (STORED_CODE.has(kind) && statement[0]?.text !== "drop")
1236
+ return kind;
1237
+ if (statement[0]?.text !== "drop" && statement.some((token) => token.kind === "word" && token.text === "definer"))
1238
+ return "definer";
1239
+ return SERVER_OBJECTS.has(kind) || dialect === "mysql" && kind === "schema" ? kind : null;
1240
+ }
1241
+ function testWriteBlockers(sql, dialect, database) {
1242
+ const statements = splitStatements(tokenize(sql, dialect));
1243
+ const reasons = [];
1244
+ if (statements.length > 1)
1245
+ reasons.push("several statements");
1246
+ for (const statement of statements) {
1247
+ const [first] = statement;
1248
+ const serverObject = definesServerObject(statement, dialect);
1249
+ if (first?.kind !== "word" || !TEST_WRITE_STARTS.has(first.text))
1250
+ reasons.push(`starts with ${first?.text ?? "nothing"}`);
1251
+ if (serverObject !== null)
1252
+ reasons.push(`defines a ${serverObject}`);
1253
+ if (dialect === "mysql")
1254
+ reasons.push(...foreignDatabases(statement, database).map((name) => `names the database ${name}`));
1255
+ for (const [index, token] of statement.entries()) {
1256
+ if (isPunct(token, UNCLOSED) || isPunct(token, NUL) || isPunct(token, UNICODE_IDENTIFIER) || isPunct(token, "\\"))
1257
+ reasons.push("has a quote that never closes, a NUL byte, an escaped identifier or a meta-command");
1258
+ else if (token.kind !== "punct" && (SIDE_EFFECT_FUNCTIONS.test(token.text) && !SEQUENCE_FUNCTIONS.has(token.text) || token.kind === "word" && (FILE_WORDS.has(token.text) || token.text === "federated" || token.text === "connection" && isPunct(statement[index + 1], "="))))
1259
+ reasons.push(`uses ${token.text}`);
1260
+ }
1261
+ }
1262
+ return [...new Set(reasons)];
1263
+ }
1264
+
1265
+ // src/guard.ts
1266
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
1267
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1268
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1269
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1270
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1271
+ var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1142
1272
  var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1143
1273
  function copyReads(statement, index) {
1144
1274
  let depth = 0;
@@ -1204,54 +1334,6 @@ function inspect(sql, dialect = "postgres") {
1204
1334
  }
1205
1335
  return { reasons: [...new Set(reasons)], statements: statements.length };
1206
1336
  }
1207
- var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1208
- var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1209
- var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1210
- var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1211
- var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1212
- var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1213
- var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1214
- function foreignDatabases(statement, database) {
1215
- const found = [];
1216
- for (const [index, token] of statement.entries()) {
1217
- if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
1218
- found.push(token.text);
1219
- }
1220
- return found;
1221
- }
1222
- function definesServerObject(statement, dialect) {
1223
- if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1224
- return null;
1225
- const kind = statement.slice(1).find((token) => !DEFINITION_MODIFIERS.has(token.text))?.text ?? "";
1226
- if (STORED_CODE.has(kind) && statement[0]?.text !== "drop")
1227
- return kind;
1228
- if (statement[0]?.text !== "drop" && statement.some((token) => token.kind === "word" && token.text === "definer"))
1229
- return "definer";
1230
- return SERVER_OBJECTS.has(kind) || dialect === "mysql" && kind === "schema" ? kind : null;
1231
- }
1232
- function testWriteBlockers(sql, dialect, database) {
1233
- const statements = splitStatements(tokenize(sql, dialect));
1234
- const reasons = [];
1235
- if (statements.length > 1)
1236
- reasons.push("several statements");
1237
- for (const statement of statements) {
1238
- const [first] = statement;
1239
- const serverObject = definesServerObject(statement, dialect);
1240
- if (first?.kind !== "word" || !TEST_WRITE_STARTS.has(first.text))
1241
- reasons.push(`starts with ${first?.text ?? "nothing"}`);
1242
- if (serverObject !== null)
1243
- reasons.push(`defines a ${serverObject}`);
1244
- if (dialect === "mysql")
1245
- reasons.push(...foreignDatabases(statement, database).map((name) => `names the database ${name}`));
1246
- for (const [index, token] of statement.entries()) {
1247
- if (isPunct(token, UNCLOSED) || isPunct(token, NUL) || isPunct(token, UNICODE_IDENTIFIER) || isPunct(token, "\\"))
1248
- reasons.push("has a quote that never closes, a NUL byte, an escaped identifier or a meta-command");
1249
- else if (token.kind !== "punct" && (SIDE_EFFECT_FUNCTIONS.test(token.text) && !SEQUENCE_FUNCTIONS.has(token.text) || token.kind === "word" && (FILE_WORDS.has(token.text) || token.text === "federated" || token.text === "connection" && isPunct(statement[index + 1], "="))))
1250
- reasons.push(`uses ${token.text}`);
1251
- }
1252
- }
1253
- return [...new Set(reasons)];
1254
- }
1255
1337
 
1256
1338
  // src/mask.ts
1257
1339
  var MASK = "***";
@@ -1374,8 +1456,8 @@ function render(shown, json) {
1374
1456
 
1375
1457
  // src/run.ts
1376
1458
  import { isIP } from "net";
1377
- import { homedir as homedir2 } from "os";
1378
- import process7 from "process";
1459
+ import { homedir as homedir3 } from "os";
1460
+ import process10 from "process";
1379
1461
  var {SQL } = globalThis.Bun;
1380
1462
 
1381
1463
  // src/compose.ts
@@ -1544,12 +1626,12 @@ function serviceUrl(service) {
1544
1626
  }
1545
1627
 
1546
1628
  // src/settings.ts
1547
- import { homedir } from "os";
1548
- import { join } from "path";
1549
- function settingsPath(home = homedir()) {
1550
- return join(home, ".config", "db", "config.json");
1629
+ import { homedir as homedir2 } from "os";
1630
+ import { join as join2 } from "path";
1631
+ function settingsPath(home = homedir2()) {
1632
+ return join2(home, ".config", "db", "config.json");
1551
1633
  }
1552
- async function loadSettings(home = homedir()) {
1634
+ async function loadSettings(home = homedir2()) {
1553
1635
  const path = settingsPath(home);
1554
1636
  const file = Bun.file(path);
1555
1637
  if (!await file.exists())
@@ -1614,7 +1696,7 @@ function serviceNamed(services, host, dialect) {
1614
1696
  fail(`${host} names several services (${aliased.map((candidate) => candidate.name).join(", ")}): pick one with --service`);
1615
1697
  return aliased[0];
1616
1698
  }
1617
- async function reachable(value, home = homedir2()) {
1699
+ async function reachable(value, home = homedir3()) {
1618
1700
  let url;
1619
1701
  try {
1620
1702
  url = new URL(value);
@@ -1635,11 +1717,11 @@ async function reachable(value, home = homedir2()) {
1635
1717
  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`);
1636
1718
  return url;
1637
1719
  }
1638
- async function connectionUrl({ env, service, container, database }, home = homedir2()) {
1720
+ async function connectionUrl({ env, service, container, database }, home = homedir3()) {
1639
1721
  if (service !== undefined && container !== undefined)
1640
1722
  fail("--service and --container name two databases: pick one");
1641
1723
  const isNamed = service !== undefined || container !== undefined;
1642
- const value = isNamed ? undefined : process7.env[env ?? DEFAULT_ENV];
1724
+ const value = isNamed ? undefined : process10.env[env ?? DEFAULT_ENV];
1643
1725
  let url;
1644
1726
  if (value !== undefined && value !== "")
1645
1727
  url = await reachable(value, home);
@@ -1784,7 +1866,7 @@ async function closeQuietly(session, url) {
1784
1866
  }
1785
1867
 
1786
1868
  // src/commands/query.ts
1787
- var usage = `db query "<sql>"
1869
+ var usage2 = `db query "<sql>"
1788
1870
 
1789
1871
  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.
1790
1872
 
@@ -1814,7 +1896,7 @@ function isWrite(sql) {
1814
1896
  return inspect(sql, "postgres").reasons.length > 0 || inspect(sql, "mysql").reasons.length > 0;
1815
1897
  }
1816
1898
  async function query(args) {
1817
- const parsed = parse(args, usage, options);
1899
+ const parsed = parse(args, usage2, options);
1818
1900
  const { values, positionals } = parsed;
1819
1901
  const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
1820
1902
  const sql = await readSql(positionals);
@@ -1998,7 +2080,7 @@ ${EXITS2}`, countOptions, (target, dialect, { where }) => countSql(target, diale
1998
2080
  }
1999
2081
 
2000
2082
  // src/cli.ts
2001
- process8.exitCode = await runCli({
2083
+ process11.exitCode = await runCli({
2002
2084
  name: "db",
2003
2085
  version,
2004
2086
  about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-db",
3
3
  "type": "module",
4
- "version": "0.9.1",
4
+ "version": "0.9.2",
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.19.0"
31
+ "@kaynooo/cli-kit": "0.20.0"
32
32
  }
33
33
  }