@kaynooo/cli-db 0.0.0-stage → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/dist/cli.js +1827 -0
  4. package/package.json +31 -4
package/dist/cli.js ADDED
@@ -0,0 +1,1827 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/cli.ts
5
+ import process8 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process3 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process2 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
102
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
103
+ }
104
+ function M(s, r, t) {
105
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ var MARKS = {
280
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
281
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
282
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
+ };
285
+ function takesControlCodes(stream, env = process.env) {
286
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
+ }
288
+ function paint(stream, env = process.env) {
289
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
+ }
291
+ function marked(mark, text, stream, detail, env = process.env) {
292
+ const colors = paint(stream, env);
293
+ const { symbol, word, paint: tint } = MARKS[mark];
294
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
295
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
296
+ }
297
+ function warn(text, detail) {
298
+ console.error(marked("warn", text, process.stderr, detail));
299
+ }
300
+ var STATUSES = {
301
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
302
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
303
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
304
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
305
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
306
+ };
307
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
308
+
309
+ // ../kit/src/format.ts
310
+ function upTo(text, separator) {
311
+ const end = text.indexOf(separator);
312
+ return end === -1 ? text : text.slice(0, end);
313
+ }
314
+ function truncate(text, width) {
315
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
316
+ }
317
+ var LINE_BREAKS = /\s*\n\s*/g;
318
+ var ESCAPE = String.fromCharCode(27);
319
+ function textWidth(text) {
320
+ return Bun.stringWidth(text);
321
+ }
322
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
323
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
324
+ const widths = [];
325
+ for (const row of cells) {
326
+ for (const [index, cell] of row.entries())
327
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
328
+ }
329
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
330
+ const colors = paint(process2.stdout);
331
+ const lines = shown.map((row) => row.map((cell, index) => {
332
+ const width = widths[index] ?? 0;
333
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
334
+ if (align[index] === "right")
335
+ return `${gap}${cell}`;
336
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
337
+ }).join(" ").trimEnd());
338
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
339
+ `);
340
+ }
341
+ function narrow(rows, widths, limit) {
342
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
343
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
344
+ const floor = 8;
345
+ while (used() > limit) {
346
+ let widest = -1;
347
+ for (const [index, width] of widths.entries()) {
348
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
349
+ widest = index;
350
+ }
351
+ if (widest === -1)
352
+ break;
353
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
354
+ }
355
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
356
+ }
357
+
358
+ // ../kit/src/text.ts
359
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
360
+ function distance(a, b) {
361
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
362
+ for (const [i, left] of [...a].entries()) {
363
+ const current = [i + 1];
364
+ for (const [j, right] of [...b].entries())
365
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
366
+ previous = current;
367
+ }
368
+ return previous[b.length] ?? 0;
369
+ }
370
+ function closest(name, names) {
371
+ const started = names.find((known) => known.startsWith(name));
372
+ if (started !== undefined)
373
+ return started;
374
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
375
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
376
+ }
377
+
378
+ // ../kit/src/args.ts
379
+ function jsonOption(holds) {
380
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
381
+ }
382
+
383
+ class Exit extends Error {
384
+ code;
385
+ hint;
386
+ constructor(message, code, hint) {
387
+ super(message);
388
+ this.code = code;
389
+ this.hint = hint;
390
+ }
391
+ }
392
+ function fail(message, code = 2, hint) {
393
+ throw new Exit(message, code, hint);
394
+ }
395
+
396
+ class UsageError extends Exit {
397
+ constructor(message, hint) {
398
+ super(message, 2, hint);
399
+ }
400
+ }
401
+ function badUsage(message) {
402
+ throw new UsageError(message);
403
+ }
404
+
405
+ class HelpShown extends Exit {
406
+ constructor() {
407
+ super("help shown", 0);
408
+ }
409
+ }
410
+
411
+ class Completing {
412
+ options;
413
+ constructor(options) {
414
+ this.options = options;
415
+ }
416
+ }
417
+ var completion = { active: false };
418
+ var OPTIONAL = /\[[^\]]+\]/g;
419
+ var USAGE_PREFIX = /^usage:\s*/i;
420
+ var FULL_STOP = /\.$/;
421
+ var DASHES = /^-+/;
422
+ function usageLine(usage, colors = paint(process3.stdout)) {
423
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
424
+ }
425
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
426
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
427
+ `);
428
+ }
429
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
430
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
431
+ }
432
+ function wantsHelpJson(env = process3.env) {
433
+ return env.KIT_HELP === "json";
434
+ }
435
+ function description(usage, { examples = [], replaces } = {}) {
436
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
437
+ `);
438
+ const first = lines[0];
439
+ const colon = first.indexOf(": ");
440
+ const prose = lines[lines.indexOf("") + 1] ?? "";
441
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
442
+ return {
443
+ synopsis: colon === -1 ? first : first.slice(0, colon),
444
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
445
+ ...replaces === undefined ? {} : { replaces },
446
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
447
+ };
448
+ }
449
+ function exampleRows(examples, colors = paint(process3.stdout)) {
450
+ if (examples.length === 0)
451
+ return [];
452
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
453
+ }
454
+ function optionRows(options, colors = paint(process3.stdout)) {
455
+ const rows = Object.entries(options).map(([name, option]) => {
456
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
457
+ const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
458
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
459
+ });
460
+ const width = Math.max(0, ...rows.map((row) => row.width));
461
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
462
+ }
463
+ var OUTPUT_OPTIONS = {
464
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
465
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
466
+ };
467
+ function applyOutput(color, plain, env = process3.env) {
468
+ const when = plain === true ? "never" : color ?? "auto";
469
+ if (when === "auto")
470
+ return;
471
+ if (when !== "always" && when !== "never")
472
+ badUsage(`--color takes auto, always or never, not ${when}`);
473
+ if (when === "always") {
474
+ env.FORCE_COLOR = "1";
475
+ delete env.NO_COLOR;
476
+ } else {
477
+ env.NO_COLOR = "1";
478
+ delete env.FORCE_COLOR;
479
+ }
480
+ }
481
+ function parse(args, usage, options, settings = {}) {
482
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
483
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
484
+ if (completion.active)
485
+ throw new Completing(all);
486
+ const separator = settings.rest === true ? args.indexOf("--") : -1;
487
+ const own = separator === -1 ? args : args.slice(0, separator);
488
+ const rest = separator === -1 ? undefined : args.slice(separator + 1);
489
+ let parsed;
490
+ try {
491
+ parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
492
+ } catch (error) {
493
+ const message = parseError(error);
494
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
495
+ }
496
+ const values = parsed.values;
497
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
498
+ if (values.help === true) {
499
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, all, undefined, settings));
500
+ throw new HelpShown;
501
+ }
502
+ if (settings.positionals !== undefined)
503
+ checkPositionals(parsed.positionals, settings.positionals);
504
+ return { ...parsed, positionals: parsed.positionals, rest };
505
+ }
506
+ function checkPositionals(given, names) {
507
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
508
+ const required = names.filter((name) => !name.startsWith("[")).length;
509
+ if (given.length < required)
510
+ badUsage(`missing ${names[given.length]}`);
511
+ if (!variadic && given.length > names.length)
512
+ badUsage(`unexpected argument ${given[names.length]}`);
513
+ }
514
+ function joinDashValues(args, options) {
515
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
516
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
517
+ const joined = [];
518
+ for (let i = 0;i < args.length; i++) {
519
+ const arg = args[i] ?? "";
520
+ if (arg === "--")
521
+ return [...joined, ...args.slice(i)];
522
+ const name = longOf.get(arg);
523
+ const next = args[i + 1];
524
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
525
+ joined.push(`--${name}=${next}`);
526
+ i++;
527
+ } else {
528
+ joined.push(arg);
529
+ }
530
+ }
531
+ return joined;
532
+ }
533
+ function parseError(error) {
534
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
535
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
536
+ }
537
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
538
+ function nearestOption(message, options, allowNegative) {
539
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
540
+ if (typed === undefined)
541
+ return;
542
+ const word = typed.replace(DASHES, "");
543
+ if (word.length < 2 && !typed.startsWith("--"))
544
+ return;
545
+ const known = Object.entries(options).flatMap(([name, option]) => [
546
+ ...option.short === undefined ? [] : [`-${option.short}`],
547
+ `--${name}`,
548
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
549
+ ]);
550
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
551
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
552
+ }
553
+ var WHOLE = /^\d+$/;
554
+ function wholeNumber(value, name, fallback, min = 1) {
555
+ if (value === undefined)
556
+ return fallback;
557
+ const number = Number(value);
558
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
559
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
560
+ return number;
561
+ }
562
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
563
+ if (path === "-") {
564
+ if (process3.stdin.isTTY)
565
+ fail(noStdin);
566
+ return Bun.stdin.text();
567
+ }
568
+ const file = Bun.file(path);
569
+ if (!await file.exists())
570
+ fail(`no file ${path}`);
571
+ return file.text();
572
+ }
573
+ // ../kit/src/process.ts
574
+ import { constants } from "os";
575
+ import process4 from "process";
576
+ var KILL_GRACE_MS = 2000;
577
+ function exitCodeOf(code, signal) {
578
+ if (code !== null)
579
+ return code;
580
+ if (typeof signal === "number")
581
+ return 128 + signal;
582
+ return signal === null ? 129 : 128 + constants.signals[signal];
583
+ }
584
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
585
+ const chunks = [];
586
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
587
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
588
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
589
+ const timers = [];
590
+ const killGroup = (killing) => {
591
+ if (state.done)
592
+ return;
593
+ try {
594
+ if (grouped)
595
+ process4.kill(-proc.pid, killing);
596
+ else
597
+ proc.kill(killing);
598
+ } catch {}
599
+ };
600
+ const stop = () => {
601
+ killGroup("SIGTERM");
602
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
603
+ };
604
+ const onAbort = () => stop();
605
+ if (timeoutMs !== undefined) {
606
+ timers.push(setTimeout(() => {
607
+ state.timedOut = true;
608
+ stop();
609
+ }, timeoutMs));
610
+ }
611
+ if (signal?.aborted === true)
612
+ onAbort();
613
+ else
614
+ signal?.addEventListener("abort", onAbort, { once: true });
615
+ onStart?.({ kill: (killing) => killGroup(killing) });
616
+ const drain = async (stream, name) => {
617
+ for await (const data of stream) {
618
+ if (state.failure !== undefined)
619
+ continue;
620
+ try {
621
+ onChunk?.({ stream: name, data });
622
+ } catch (error) {
623
+ state.failure = error;
624
+ stop();
625
+ continue;
626
+ }
627
+ if (state.kept + data.length > maxBytes) {
628
+ state.truncated = true;
629
+ continue;
630
+ }
631
+ state.kept += data.length;
632
+ chunks.push({ stream: name, data });
633
+ }
634
+ };
635
+ try {
636
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
637
+ await proc.exited;
638
+ } finally {
639
+ state.done = true;
640
+ for (const timer of timers)
641
+ clearTimeout(timer);
642
+ signal?.removeEventListener("abort", onAbort);
643
+ }
644
+ if (state.failure !== undefined)
645
+ throw state.failure;
646
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
647
+ let output;
648
+ let text;
649
+ return {
650
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
651
+ chunks,
652
+ timedOut: state.timedOut,
653
+ truncated: state.truncated,
654
+ get output() {
655
+ return output ??= joined();
656
+ },
657
+ get text() {
658
+ return text ??= (output ??= joined()).toString();
659
+ }
660
+ };
661
+ }
662
+
663
+ // ../kit/src/progress.ts
664
+ var ESC = String.fromCharCode(27);
665
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
666
+ var RESET_STYLE = `${ESC}[0m`;
667
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
668
+ // ../kit/src/cli.ts
669
+ import process5 from "process";
670
+ var LEVEL_OPTIONS = {
671
+ ...OUTPUT_OPTIONS,
672
+ help: { type: "boolean", short: "h", description: "show this help" }
673
+ };
674
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
675
+ async function commandRows(commands, colors) {
676
+ const width = Math.max(...Object.keys(commands).map((name) => name.length));
677
+ const groups = new Map([["Commands:", []]]);
678
+ const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
679
+ for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
680
+ const heading = group === undefined ? "Commands:" : `${group}:`;
681
+ const rows = groups.get(heading) ?? [];
682
+ rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
683
+ groups.set(heading, rows);
684
+ }
685
+ return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
686
+ }
687
+ function takeOutputFlags(argv) {
688
+ let index = 0;
689
+ for (;index < argv.length; index++) {
690
+ const word = argv[index];
691
+ if (word === "--plain")
692
+ applyOutput(undefined, true);
693
+ else if (word.startsWith("--color="))
694
+ applyOutput(word.slice("--color=".length), undefined);
695
+ else if (word === "--color" && argv[index + 1] !== undefined)
696
+ applyOutput(argv[++index], undefined);
697
+ else
698
+ break;
699
+ }
700
+ return argv.slice(index);
701
+ }
702
+ async function resolveSummary(summary) {
703
+ return typeof summary === "string" ? summary : summary();
704
+ }
705
+ function scopeOf(commands, extra, aliases) {
706
+ return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
707
+ }
708
+ async function expand(scope, words) {
709
+ if (scope.lazy.length === 0)
710
+ return scope;
711
+ const commands = { ...scope.commands };
712
+ for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
713
+ for (const [name, command] of Object.entries(added))
714
+ commands[name] ??= command;
715
+ }
716
+ return { ...scope, commands, lazy: [] };
717
+ }
718
+ async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
719
+ const colors = paint(stream);
720
+ const prefix = path.join(" ");
721
+ const summary = await resolveSummary(lazySummary);
722
+ if (wantsHelpJson())
723
+ return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
724
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
725
+ const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
726
+ const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
727
+ return [
728
+ header(colors, summary),
729
+ "",
730
+ usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
731
+ ...replacesRows(replaces, colors),
732
+ "",
733
+ ...await commandRows(commands, colors),
734
+ ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
735
+ "",
736
+ colors.bold("Options:"),
737
+ ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
738
+ ...exampleRows(examples ?? [], colors),
739
+ "",
740
+ `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
741
+ ].join(`
742
+ `);
743
+ }
744
+ function printError(prefix, message, hint, cause) {
745
+ const colors = paint(process5.stderr);
746
+ const styled = takesControlCodes(process5.stderr);
747
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
748
+ const under = (label, text, tint) => text === undefined ? "" : `
749
+ ${styled ? tint(label) : `${label}:`} ${text}`;
750
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
751
+ }
752
+ function printJsonError(message, hint, cause) {
753
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
754
+ }
755
+ function wantsJson(argv) {
756
+ const end = argv.indexOf("--");
757
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
758
+ }
759
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
760
+ if (error instanceof HelpShown)
761
+ return 0;
762
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
763
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
764
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
765
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
766
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
767
+ return error instanceof Exit ? error.code : 1;
768
+ }
769
+ async function dispatch(level, typed, { version, redact }) {
770
+ const prefix = level.path.join(" ");
771
+ let argv;
772
+ try {
773
+ argv = takeOutputFlags(typed);
774
+ } catch (error) {
775
+ return reportThrown(prefix, error);
776
+ }
777
+ const [name, ...args] = argv;
778
+ if (name === undefined && level.path.length > 1) {
779
+ console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
780
+ return 2;
781
+ }
782
+ if (name === undefined || name === "help" || name === "--help" || name === "-h") {
783
+ console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
784
+ return 0;
785
+ }
786
+ if (level.path.length === 1 && (name === "--version" || name === "-v")) {
787
+ console.log(version);
788
+ return 0;
789
+ }
790
+ let command = level.commands[level.aliases?.[name] ?? name];
791
+ let rest = args;
792
+ if (command === undefined && level.lazy.length > 0) {
793
+ level = await expand(level, [...level.path.slice(1), ...argv]);
794
+ command = level.commands[level.aliases?.[name] ?? name];
795
+ }
796
+ if (command === undefined && level.defaultCommand !== undefined) {
797
+ command = level.commands[level.defaultCommand];
798
+ rest = argv;
799
+ }
800
+ if (command === undefined) {
801
+ const meant = closest(name, Object.keys(level.commands));
802
+ printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
803
+ return 2;
804
+ }
805
+ if ("commands" in command) {
806
+ const { summary } = command;
807
+ return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, examples: command.examples, replaces: undefined }, rest, { version, redact });
808
+ }
809
+ try {
810
+ return await command.run(rest);
811
+ } catch (error) {
812
+ return reportThrown(`${prefix} ${name}`, error, redact, wantsJson(rest));
813
+ }
814
+ }
815
+ var COMPLETE = "__complete";
816
+ var FILES = "__files__";
817
+ async function optionsOf(run) {
818
+ completion.active = true;
819
+ try {
820
+ await run([]);
821
+ } catch (error) {
822
+ if (error instanceof Completing)
823
+ return error.options;
824
+ } finally {
825
+ completion.active = false;
826
+ }
827
+ return {};
828
+ }
829
+ async function leafCandidates(run, words) {
830
+ if (!(words.at(-1) ?? "").startsWith("-"))
831
+ return [FILES];
832
+ return Object.entries(await optionsOf(run)).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
833
+ }
834
+ async function candidates(scope, defaultCommand, words, before = []) {
835
+ const [word = "", ...rest] = words;
836
+ const listing = rest.length === 0 && !word.startsWith("-");
837
+ let { commands, aliases } = scope;
838
+ let command = commands[aliases?.[word] ?? word];
839
+ if (listing || command === undefined) {
840
+ ({ commands, aliases } = await expand(scope, [...before, ...words]));
841
+ command = commands[aliases?.[word] ?? word];
842
+ }
843
+ if (listing)
844
+ return Promise.all(Object.entries(commands).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
845
+ if (command === undefined) {
846
+ const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
847
+ return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
848
+ }
849
+ return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
850
+ }
851
+ async function printCandidates(found) {
852
+ for (const line of await found)
853
+ console.log(line);
854
+ return 0;
855
+ }
856
+ async function runCli(cli, argv = process5.argv.slice(2)) {
857
+ if (argv[0] === COMPLETE)
858
+ return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
859
+ 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, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
860
+ }
861
+ // ../kit/src/logs.ts
862
+ var DAY_MS = 24 * 60 * 60 * 1000;
863
+ // ../kit/src/secrets.ts
864
+ var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
865
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
866
+ var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
867
+ function isSecretName(name) {
868
+ return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
869
+ }
870
+ // ../kit/src/sessions.ts
871
+ var {Glob } = globalThis.Bun;
872
+ var SESSION_FILES = new Glob("*.json");
873
+ var ACCOUNT_DIRS = new Glob("*/sessions");
874
+ // package.json
875
+ var version = "0.8.1";
876
+
877
+ // src/args.ts
878
+ var DEFAULT_ENV = "DATABASE_URL";
879
+ var DEFAULT_LIMIT = 100;
880
+ 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/db/config.json.';
881
+ 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.";
882
+ var connectionOptions = {
883
+ 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` },
884
+ service: { type: "string", short: "s", description: "read the running Postgres, MySQL or MariaDB service of this name in the compose project, credentials from its environment" },
885
+ 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" },
886
+ database: { type: "string", short: "d", description: "database to read instead of the URL's or the service's" }
887
+ };
888
+ var outputOptions = {
889
+ limit: { type: "string", short: "n", description: `rows shown (${DEFAULT_LIMIT})` },
890
+ raw: { type: "boolean", description: "show columns masked by default (emails, phones, tokens, password hashes, secret-named keys inside JSON values)" },
891
+ json: jsonOption()
892
+ };
893
+
894
+ // src/guard.ts
895
+ var WORD_START = /[a-z_\P{ASCII}]/iu;
896
+ var WORD_PART = /[\w$\P{ASCII}]/u;
897
+ var SPACE = /\s/;
898
+ var ESCAPE_PREFIX = /e/i;
899
+ var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
900
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
901
+ var DIGITS = /\d/;
902
+ var COMMAND_ENDS = ";";
903
+ var UNCLOSED = "unclosed";
904
+ var NUL = "\x00";
905
+ var UNICODE_IDENTIFIER = 'U&"';
906
+ var UNICODE_PREFIX = /u&$/i;
907
+ var LINE_END = /[\r\n]/;
908
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
909
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
910
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
911
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
912
+ 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)$/;
913
+ function tokenize(sql, dialect = "postgres") {
914
+ const tokens = [];
915
+ const isMysql = dialect === "mysql";
916
+ let at = 0;
917
+ while (at < sql.length) {
918
+ const char = sql.charAt(at);
919
+ const next = sql.charAt(at + 1);
920
+ if (SPACE.test(char)) {
921
+ at++;
922
+ } else if (char === NUL) {
923
+ tokens.push({ kind: "punct", text: NUL });
924
+ at++;
925
+ } else if (char === "-" && next === "-" && (!isMysql || isDashGap(sql.charAt(at + 2))) || isMysql && char === "#") {
926
+ const end = sql.slice(at).search(LINE_END);
927
+ at = end === -1 ? sql.length : at + end + 1;
928
+ } else if (char === "/" && next === "*" && (sql.charAt(at + 2) === "!" || sql.charAt(at + 2) === "M" && sql.charAt(at + 3) === "!")) {
929
+ at += sql.charAt(at + 2) === "!" ? 3 : 4;
930
+ while (DIGITS.test(sql.charAt(at)))
931
+ at++;
932
+ } else if (char === "/" && next === "*") {
933
+ at = skipComment(sql, at, !isMysql);
934
+ } else if (char === "'" || isMysql && char === '"') {
935
+ const backslashes = isMysql || ESCAPE_PREFIX.test(sql.charAt(at - 1)) && !WORD_PART.test(sql.charAt(at - 2));
936
+ const end = skipQuoted(sql, at, char, backslashes);
937
+ at = end ?? sql.length;
938
+ tokens.push({ kind: "punct", text: end === undefined ? UNCLOSED : "'" });
939
+ } else if (char === '"' || char === "`") {
940
+ const end = skipQuoted(sql, at, char, false);
941
+ if (char === '"' && UNICODE_PREFIX.test(sql.slice(Math.max(0, at - 2), at)) && !WORD_PART.test(sql.charAt(at - 3)))
942
+ tokens.push({ kind: "punct", text: UNICODE_IDENTIFIER });
943
+ tokens.push(end === undefined ? { kind: "punct", text: UNCLOSED } : { kind: "quoted", text: sql.slice(at + 1, end - 1).replaceAll(char + char, char) });
944
+ at = end ?? sql.length;
945
+ } else if (!isMysql && char === "$" && DOLLAR_TAG.test(sql.slice(at))) {
946
+ const tag = DOLLAR_TAG.exec(sql.slice(at))?.[0] ?? "$$";
947
+ const end = sql.indexOf(tag, at + tag.length);
948
+ at = end === -1 ? sql.length : end + tag.length;
949
+ tokens.push({ kind: "punct", text: end === -1 ? UNCLOSED : "$" });
950
+ } else if (WORD_START.test(char)) {
951
+ let end = at + 1;
952
+ while (end < sql.length && WORD_PART.test(sql.charAt(end)))
953
+ end++;
954
+ tokens.push({ kind: "word", text: sql.slice(at, end).toLowerCase() });
955
+ at = end;
956
+ } else {
957
+ tokens.push({ kind: "punct", text: char });
958
+ at++;
959
+ }
960
+ }
961
+ return tokens;
962
+ }
963
+ function isDashGap(char) {
964
+ return char <= " ";
965
+ }
966
+ function skipComment(sql, start, nests) {
967
+ let depth = 0;
968
+ let at = start;
969
+ while (at < sql.length) {
970
+ if (sql.startsWith("/*", at) && (nests || depth === 0)) {
971
+ depth++;
972
+ at += 2;
973
+ } else if (sql.startsWith("*/", at)) {
974
+ depth--;
975
+ at += 2;
976
+ if (depth === 0)
977
+ return at;
978
+ } else {
979
+ at++;
980
+ }
981
+ }
982
+ return sql.length;
983
+ }
984
+ function skipQuoted(sql, start, quote, backslashes) {
985
+ let at = start + 1;
986
+ while (at < sql.length) {
987
+ const char = sql.charAt(at);
988
+ if (backslashes && char === "\\") {
989
+ at += 2;
990
+ } else if (char === quote) {
991
+ if (sql.charAt(at + 1) !== quote)
992
+ return at + 1;
993
+ at += 2;
994
+ } else {
995
+ at++;
996
+ }
997
+ }
998
+ return;
999
+ }
1000
+ function splitStatements(tokens) {
1001
+ const statements = [[]];
1002
+ for (const token of tokens) {
1003
+ if (token.kind === "punct" && token.text === COMMAND_ENDS)
1004
+ statements.push([]);
1005
+ else
1006
+ statements.at(-1)?.push(token);
1007
+ }
1008
+ return statements.filter((statement) => statement.length > 0);
1009
+ }
1010
+ var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1011
+ function copyReads(statement, index) {
1012
+ let depth = 0;
1013
+ for (const [at, token] of statement.entries()) {
1014
+ if (at <= index)
1015
+ continue;
1016
+ if (isPunct(token, "("))
1017
+ depth++;
1018
+ else if (isPunct(token, ")"))
1019
+ depth--;
1020
+ else if (depth === 0 && token.kind === "word" && (token.text === "from" || token.text === "to"))
1021
+ return token.text === "to" && (statement[at + 1]?.text === "stdout" || isPunct(statement[index - 1], "\\"));
1022
+ }
1023
+ return false;
1024
+ }
1025
+ function statementWrites(statement) {
1026
+ const first = statement[0];
1027
+ const start = isPunct(first, "\\") ? 1 : 0;
1028
+ const reasons = [];
1029
+ for (const [index, token] of statement.entries()) {
1030
+ if (isPunct(token, UNCLOSED))
1031
+ reasons.push("has a quote that never closes");
1032
+ else if (isPunct(token, NUL))
1033
+ reasons.push("contains a NUL byte");
1034
+ else if (isPunct(token, UNICODE_IDENTIFIER))
1035
+ reasons.push("uses a U& escaped identifier");
1036
+ if (token.kind === "quoted" && SIDE_EFFECT_FUNCTIONS.test(token.text))
1037
+ reasons.push(`calls ${token.text}`);
1038
+ if (token.kind !== "word")
1039
+ continue;
1040
+ if (SIDE_EFFECT_FUNCTIONS.test(token.text)) {
1041
+ reasons.push(`calls ${token.text}`);
1042
+ } else if (isPunct(statement[index - 1], ".")) {
1043
+ continue;
1044
+ } else if (token.text === "set") {
1045
+ if (index !== start || PRIVILEGED_SET.has(statement[index + 1]?.text ?? "") || isPunct(statement[index + 1], "@") && isPunct(statement[index + 2], "@"))
1046
+ reasons.push("uses SET");
1047
+ } else if (index === start && WRITING_STARTS.has(token.text)) {
1048
+ reasons.push(`uses ${token.text.toUpperCase()}`);
1049
+ } else if (token.text === "copy") {
1050
+ if (!copyReads(statement, index))
1051
+ reasons.push("uses COPY");
1052
+ } else if (WRITE_WORDS.has(token.text)) {
1053
+ reasons.push(`uses ${token.text.toUpperCase()}`);
1054
+ } else if (token.text === "analyze" && first?.text !== "explain") {
1055
+ reasons.push("uses ANALYZE");
1056
+ } else if (token.text === "for" && LOCK_KIND.test(statement[index + 1]?.text ?? "")) {
1057
+ reasons.push("takes row locks with FOR UPDATE or SHARE");
1058
+ } else if (token.text === "comment" && statement[index + 1]?.text === "on") {
1059
+ reasons.push("uses COMMENT ON");
1060
+ }
1061
+ }
1062
+ return reasons;
1063
+ }
1064
+ function inspect(sql, dialect = "postgres") {
1065
+ const statements = splitStatements(tokenize(sql, dialect));
1066
+ const reasons = [];
1067
+ for (const statement of statements) {
1068
+ const first = statement[0];
1069
+ if (first?.kind !== "word" || !READ_STARTS.has(first.text))
1070
+ reasons.push(`starts with ${first?.text ?? "nothing"}, not a read`);
1071
+ reasons.push(...statementWrites(statement));
1072
+ }
1073
+ return { reasons: [...new Set(reasons)], statements: statements.length };
1074
+ }
1075
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1076
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1077
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1078
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1079
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1080
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1081
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1082
+ function foreignDatabases(statement, database) {
1083
+ const found = [];
1084
+ for (const [index, token] of statement.entries()) {
1085
+ if ((token.kind === "word" || token.kind === "quoted") && !isPunct(statement[index - 1], "@") && isPunct(statement[index + 1], ".") && !isPunct(statement[index - 1], ".") && token.text.toLowerCase() !== database.toLowerCase())
1086
+ found.push(token.text);
1087
+ }
1088
+ return found;
1089
+ }
1090
+ function definesServerObject(statement, dialect) {
1091
+ if (!DEFINITION_STARTS.has(statement[0]?.text ?? ""))
1092
+ return null;
1093
+ const kind = statement.slice(1).find((token) => !DEFINITION_MODIFIERS.has(token.text))?.text ?? "";
1094
+ if (STORED_CODE.has(kind) && statement[0]?.text !== "drop")
1095
+ return kind;
1096
+ if (statement[0]?.text !== "drop" && statement.some((token) => token.kind === "word" && token.text === "definer"))
1097
+ return "definer";
1098
+ return SERVER_OBJECTS.has(kind) || dialect === "mysql" && kind === "schema" ? kind : null;
1099
+ }
1100
+ function testWriteBlockers(sql, dialect, database) {
1101
+ const statements = splitStatements(tokenize(sql, dialect));
1102
+ const reasons = [];
1103
+ if (statements.length > 1)
1104
+ reasons.push("several statements");
1105
+ for (const statement of statements) {
1106
+ const [first] = statement;
1107
+ const serverObject = definesServerObject(statement, dialect);
1108
+ if (first?.kind !== "word" || !TEST_WRITE_STARTS.has(first.text))
1109
+ reasons.push(`starts with ${first?.text ?? "nothing"}`);
1110
+ if (serverObject !== null)
1111
+ reasons.push(`defines a ${serverObject}`);
1112
+ if (dialect === "mysql")
1113
+ reasons.push(...foreignDatabases(statement, database).map((name) => `names the database ${name}`));
1114
+ for (const [index, token] of statement.entries()) {
1115
+ if (isPunct(token, UNCLOSED) || isPunct(token, NUL) || isPunct(token, UNICODE_IDENTIFIER) || isPunct(token, "\\"))
1116
+ reasons.push("has a quote that never closes, a NUL byte, an escaped identifier or a meta-command");
1117
+ 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], "="))))
1118
+ reasons.push(`uses ${token.text}`);
1119
+ }
1120
+ }
1121
+ return [...new Set(reasons)];
1122
+ }
1123
+
1124
+ // src/mask.ts
1125
+ var MASK = "***";
1126
+ var EMAIL = /e[-_]?mail/i;
1127
+ var PHONE = /phone|mobile|msisdn|^tel(?:_|$)|_tel$/i;
1128
+ var HASH = /hash/i;
1129
+ var JSON_TEXT = /^\s*[[{]/;
1130
+ var SENSITIVE = [
1131
+ ["email", (name) => EMAIL.test(name)],
1132
+ ["phone", (name) => PHONE.test(name)],
1133
+ ["secret", (name) => name.toLowerCase() !== "key" && isSecretName(name)],
1134
+ ["password", (name) => HASH.test(name)]
1135
+ ];
1136
+ var URL_CREDENTIALS = /([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi;
1137
+ function sensitiveKind(column) {
1138
+ return SENSITIVE.find(([, matches]) => matches(column))?.[0];
1139
+ }
1140
+ function isPlainObject(value) {
1141
+ const prototype = typeof value === "object" && value !== null ? Object.getPrototypeOf(value) : undefined;
1142
+ return prototype === Object.prototype || prototype === null;
1143
+ }
1144
+ function maskNested(value, path, found) {
1145
+ if (Array.isArray(value))
1146
+ return value.map((item) => maskNested(item, path, found));
1147
+ if (!isPlainObject(value))
1148
+ return value;
1149
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => {
1150
+ if (inner === null || sensitiveKind(key) === undefined)
1151
+ return [key, maskNested(inner, `${path}.${key}`, found)];
1152
+ found.add(`${path}.${key}`);
1153
+ return [key, MASK];
1154
+ }));
1155
+ }
1156
+ function maskJson(value, column, found) {
1157
+ if (typeof value !== "string" || !JSON_TEXT.test(value))
1158
+ return maskNested(value, column, found);
1159
+ try {
1160
+ const before = found.size;
1161
+ const masked = maskNested(JSON.parse(value), column, found);
1162
+ return found.size === before ? value : JSON.stringify(masked);
1163
+ } catch {
1164
+ return value;
1165
+ }
1166
+ }
1167
+ function maskRows(rows, raw) {
1168
+ if (raw)
1169
+ return { rows, masked: [] };
1170
+ const columns = Object.keys(rows[0] ?? {}).filter((column) => sensitiveKind(column) !== undefined);
1171
+ const nested = new Set;
1172
+ const masked = rows.map((row) => Object.fromEntries(Object.entries(row).map(([column, value]) => {
1173
+ if (columns.includes(column))
1174
+ return [column, value === null ? value : MASK];
1175
+ return [column, maskJson(value, column, nested)];
1176
+ })));
1177
+ return nested.size === 0 && columns.length === 0 ? { rows, masked: [] } : { rows: masked, masked: [...columns, ...nested] };
1178
+ }
1179
+ function scrub(text, url) {
1180
+ let clean = text;
1181
+ if (url !== undefined && url !== "") {
1182
+ clean = clean.replaceAll(url, "<url>");
1183
+ for (const secret of secrets2(url))
1184
+ clean = clean.replaceAll(secret, MASK);
1185
+ }
1186
+ return clean.replace(URL_CREDENTIALS, "$1<credentials>@");
1187
+ }
1188
+ function secrets2(url) {
1189
+ try {
1190
+ const { password, username } = new URL(url);
1191
+ return [...new Set([password, decode(password), decode(username)].filter((secret) => secret.length > 3))];
1192
+ } catch {
1193
+ return [];
1194
+ }
1195
+ }
1196
+ function decode(text) {
1197
+ try {
1198
+ return decodeURIComponent(text);
1199
+ } catch {
1200
+ return text;
1201
+ }
1202
+ }
1203
+
1204
+ // src/output.ts
1205
+ var CELL_WIDTH = 80;
1206
+ function cell(value) {
1207
+ if (value === null || value === undefined)
1208
+ return "NULL";
1209
+ if (value instanceof Date)
1210
+ return Number.isNaN(value.getTime()) ? "invalid date" : value.toISOString();
1211
+ if (value instanceof Uint8Array)
1212
+ return `<${value.byteLength} bytes>`;
1213
+ return typeof value === "object" ? JSON.stringify(value, jsonValue) : String(value);
1214
+ }
1215
+ function jsonValue(_key, value) {
1216
+ if (typeof value === "bigint")
1217
+ return value.toString();
1218
+ return value instanceof Uint8Array ? `<${value.byteLength} bytes>` : value;
1219
+ }
1220
+ function shape(rows, limit, raw, exact = true) {
1221
+ const { rows: masked, masked: columns } = maskRows(rows.slice(0, limit), raw);
1222
+ return { columns: Object.keys(rows[0] ?? {}), rows: masked, total: rows.length, omitted: Math.max(0, rows.length - limit), exact, truncated: rows.length > limit, masked: columns };
1223
+ }
1224
+ function render(shown, json) {
1225
+ if (json)
1226
+ return JSON.stringify({ columns: shown.columns, rows: shown.rows, ...shown.exact ? { total: shown.total, omitted: shown.omitted } : {}, truncated: shown.truncated, masked: shown.masked }, jsonValue, 2);
1227
+ if (shown.total === 0)
1228
+ return "no rows";
1229
+ const lines = [table([
1230
+ shown.columns,
1231
+ ...shown.rows.map((row) => shown.columns.map((column) => cell(row[column])))
1232
+ ], { cellWidth: CELL_WIDTH })];
1233
+ if (shown.truncated && !shown.exact)
1234
+ lines.push("... more rows not shown (-n raises the cap)");
1235
+ else if (shown.truncated)
1236
+ lines.push(`... ${shown.omitted} more ${shown.omitted === 1 ? "row" : "rows"} not shown (${shown.total} in all, -n raises the cap)`);
1237
+ if (shown.masked.length > 0)
1238
+ lines.push(`masked: ${shown.masked.join(", ")} (--raw shows them)`);
1239
+ return lines.join(`
1240
+ `);
1241
+ }
1242
+
1243
+ // src/run.ts
1244
+ import { isIP } from "net";
1245
+ import { homedir as homedir2 } from "os";
1246
+ import process7 from "process";
1247
+ var {SQL } = globalThis.Bun;
1248
+
1249
+ // src/compose.ts
1250
+ var POSTGRES_PORT = 5432;
1251
+ var MYSQL_PORT = 3306;
1252
+ var POSTGRES_IMAGE = /(?:^|\/)(?:postgres|postgis|timescaledb)[\w.-]*(?::|$)/;
1253
+ var MYSQL_IMAGE = /(?:^|\/)(?:mysql|mariadb|percona)[\w.-]*(?::|$)/;
1254
+ var LOOPBACK = new Set(["", "0.0.0.0", "::", "127.0.0.1", "::1"]);
1255
+ var LEADING_SLASH = /^\//;
1256
+ function parsePs(text) {
1257
+ const trimmed = text.trim();
1258
+ if (trimmed === "")
1259
+ return [];
1260
+ return trimmed.startsWith("[") ? JSON.parse(trimmed) : trimmed.split(`
1261
+ `).map((line) => JSON.parse(line));
1262
+ }
1263
+ function envOf(lines) {
1264
+ return Object.fromEntries(lines.map((line) => {
1265
+ const at = line.indexOf("=");
1266
+ return at === -1 ? [line, ""] : [line.slice(0, at), line.slice(at + 1)];
1267
+ }));
1268
+ }
1269
+ function engineOf(image, env) {
1270
+ if ("PG_MAJOR" in env || "POSTGRES_PASSWORD" in env || POSTGRES_IMAGE.test(image))
1271
+ return "postgres";
1272
+ if ("MYSQL_MAJOR" in env || "MARIADB_MAJOR" in env || "MYSQL_ROOT_PASSWORD" in env || "MARIADB_ROOT_PASSWORD" in env || MYSQL_IMAGE.test(image))
1273
+ return "mysql";
1274
+ return "other";
1275
+ }
1276
+ function describeContainer(name, image, publishers, container) {
1277
+ const env = envOf(container.Config?.Env ?? []);
1278
+ const engine = engineOf(image ?? container.Config?.Image ?? "", env);
1279
+ const target = engine === "mysql" ? MYSQL_PORT : POSTGRES_PORT;
1280
+ const networks = Object.values(container.NetworkSettings?.Networks ?? {});
1281
+ const published = publishers.find((publisher) => publisher.TargetPort === target && (publisher.PublishedPort ?? 0) > 0 && LOOPBACK.has(publisher.URL ?? ""));
1282
+ const address = networks.map((network) => network.IPAddress ?? "").find((ip) => ip !== "");
1283
+ const names = [name, (container.Name ?? "").replace(LEADING_SLASH, ""), ...networks.flatMap((network) => [...network.Aliases ?? [], ...network.DNSNames ?? []])].filter((each) => each !== "");
1284
+ if (published === undefined && address === undefined)
1285
+ return [];
1286
+ return [{
1287
+ name,
1288
+ engine,
1289
+ env,
1290
+ names: [...new Set(names)],
1291
+ host: published === undefined ? address ?? "" : "127.0.0.1",
1292
+ port: published?.PublishedPort ?? target
1293
+ }];
1294
+ }
1295
+ function describeServices(rows, inspected) {
1296
+ const byId = new Map(inspected.map((container) => [container.Id ?? "", container]));
1297
+ return rows.flatMap((row) => {
1298
+ const container = [...byId.entries()].find(([id]) => row.ID !== undefined && row.ID !== "" && id.startsWith(row.ID))?.[1];
1299
+ if (container === undefined || row.Service === undefined)
1300
+ return [];
1301
+ return describeContainer(row.Service, row.Image, row.Publishers ?? [], container);
1302
+ });
1303
+ }
1304
+ function publishersOf(container) {
1305
+ return Object.entries(container.NetworkSettings?.Ports ?? {}).flatMap(([port, bindings]) => (bindings ?? []).map((binding) => ({ URL: binding.HostIp ?? "", TargetPort: Number.parseInt(port, 10), PublishedPort: Number.parseInt(binding.HostPort ?? "", 10) || 0 })));
1306
+ }
1307
+ function describeNamedContainer(wanted, inspected) {
1308
+ const [container] = inspected;
1309
+ if (container === undefined)
1310
+ fail(`no container ${wanted}`);
1311
+ if (container.State?.Running === false)
1312
+ fail(`${wanted} is not running`);
1313
+ const name = (container.Name ?? "").replace(LEADING_SLASH, "") || wanted;
1314
+ const [service] = describeContainer(name, undefined, publishersOf(container), container);
1315
+ if (service === undefined)
1316
+ fail(`${wanted} publishes no port and has no address on a network, so db cannot reach it`);
1317
+ if (service.engine === "other")
1318
+ fail(`${wanted} is no Postgres, MySQL or MariaDB container: db reads those only`);
1319
+ return service;
1320
+ }
1321
+ async function containerService(wanted) {
1322
+ let inspect;
1323
+ try {
1324
+ inspect = await runCommand(["docker", "inspect", "--type", "container", "--", wanted]);
1325
+ } catch {
1326
+ fail("docker is not installed, so db cannot look a container up");
1327
+ }
1328
+ if (inspect.code !== 0)
1329
+ fail(`no container ${wanted}`);
1330
+ try {
1331
+ return describeNamedContainer(wanted, JSON.parse(stdoutOf(inspect.chunks)));
1332
+ } catch (error) {
1333
+ if (error instanceof SyntaxError)
1334
+ fail(`docker inspect ${wanted} did not print JSON`);
1335
+ throw error;
1336
+ }
1337
+ }
1338
+ function stdoutOf(chunks) {
1339
+ return Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1340
+ }
1341
+ async function composeServices() {
1342
+ let ps;
1343
+ try {
1344
+ ps = await runCommand(["docker", "compose", "ps", "--format", "json"]);
1345
+ } catch {
1346
+ return [];
1347
+ }
1348
+ try {
1349
+ const rows = ps.code === 0 ? parsePs(stdoutOf(ps.chunks)).filter((row) => row.State === "running" && row.ID !== undefined) : [];
1350
+ if (rows.length === 0)
1351
+ return [];
1352
+ const inspect = await runCommand(["docker", "inspect", ...rows.map((row) => row.ID ?? "")]);
1353
+ return inspect.code === 0 ? describeServices(rows, JSON.parse(stdoutOf(inspect.chunks))) : [];
1354
+ } catch {
1355
+ return [];
1356
+ }
1357
+ }
1358
+ function pickService(services, wanted) {
1359
+ const databases = services.filter((service) => service.engine !== "other");
1360
+ if (wanted !== undefined) {
1361
+ const named = services.find((service) => service.name === wanted);
1362
+ if (named === undefined)
1363
+ fail(`no running service ${wanted} in this compose project${services.length === 0 ? "" : `, running: ${services.map((service) => service.name).join(", ")}`}`);
1364
+ if (named.engine === "other")
1365
+ fail(`${wanted} is no Postgres, MySQL or MariaDB service: db reads those only`);
1366
+ return named;
1367
+ }
1368
+ if (databases.length > 1)
1369
+ fail(`several database services run here (${databases.map((service) => service.name).join(", ")}): pick one with --service`);
1370
+ const [only] = databases;
1371
+ if (only !== undefined)
1372
+ return only;
1373
+ fail("no DATABASE_URL and no running Postgres, MySQL or MariaDB service in this compose project (docker compose ps, from this directory or a parent): put the URL in a .env file, name another key with --env, or ask for the stack to be started");
1374
+ }
1375
+ var PASSWORD_FILE_HINT = "reads its password from a file inside the container: give the URL with --env instead";
1376
+ function mysqlUrl(service, authority) {
1377
+ const { env } = service;
1378
+ const user = env.MYSQL_USER ?? env.MARIADB_USER;
1379
+ const url = new URL(`mysql://${authority}`);
1380
+ if (user !== undefined) {
1381
+ if ((env.MYSQL_PASSWORD_FILE ?? env.MARIADB_PASSWORD_FILE) !== undefined && (env.MYSQL_PASSWORD ?? env.MARIADB_PASSWORD) === undefined)
1382
+ fail(`${service.name} ${PASSWORD_FILE_HINT}`);
1383
+ url.username = user;
1384
+ url.password = env.MYSQL_PASSWORD ?? env.MARIADB_PASSWORD ?? "";
1385
+ } else {
1386
+ const root = env.MYSQL_ROOT_PASSWORD ?? env.MARIADB_ROOT_PASSWORD;
1387
+ const isEmptyAllowed = ["MYSQL_ALLOW_EMPTY_PASSWORD", "MARIADB_ALLOW_EMPTY_ROOT_PASSWORD"].some((key) => ["1", "yes", "true"].includes((env[key] ?? "").toLowerCase()));
1388
+ if (root === undefined && (env.MYSQL_ROOT_PASSWORD_FILE ?? env.MARIADB_ROOT_PASSWORD_FILE) !== undefined)
1389
+ fail(`${service.name} ${PASSWORD_FILE_HINT}`);
1390
+ if (root === undefined && !isEmptyAllowed)
1391
+ fail(`${service.name} has no MYSQL_USER or MYSQL_ROOT_PASSWORD (nor the MARIADB_ ones) in its environment, so db has no credentials for it: give the URL with --env instead`);
1392
+ url.username = "root";
1393
+ url.password = root ?? "";
1394
+ }
1395
+ const database = env.MYSQL_DATABASE ?? env.MARIADB_DATABASE;
1396
+ if (database !== undefined && database !== "")
1397
+ url.pathname = `/${database}`;
1398
+ return url;
1399
+ }
1400
+ function serviceUrl(service) {
1401
+ const authority = `${service.host.includes(":") ? `[${service.host}]` : service.host}:${service.port}`;
1402
+ if (service.engine === "mysql")
1403
+ return mysqlUrl(service, authority).href;
1404
+ if (service.env.POSTGRES_PASSWORD_FILE !== undefined && service.env.POSTGRES_PASSWORD === undefined)
1405
+ fail(`${service.name} ${PASSWORD_FILE_HINT}`);
1406
+ const user = service.env.POSTGRES_USER ?? "postgres";
1407
+ const url = new URL(`postgres://${authority}`);
1408
+ url.username = user;
1409
+ url.password = service.env.POSTGRES_PASSWORD ?? "";
1410
+ url.pathname = `/${service.env.POSTGRES_DB ?? user}`;
1411
+ return url.href;
1412
+ }
1413
+
1414
+ // src/settings.ts
1415
+ import { homedir } from "os";
1416
+ import { join } from "path";
1417
+ function settingsPath(home = homedir()) {
1418
+ return join(home, ".config", "db", "config.json");
1419
+ }
1420
+ async function loadSettings(home = homedir()) {
1421
+ const path = settingsPath(home);
1422
+ const file = Bun.file(path);
1423
+ if (!await file.exists())
1424
+ return {};
1425
+ let raw;
1426
+ try {
1427
+ raw = await file.json();
1428
+ } catch {
1429
+ warn(`${path} is not valid JSON, ignored: only local hosts are allowed`);
1430
+ return {};
1431
+ }
1432
+ const hosts = typeof raw === "object" && raw !== null && "allowedHosts" in raw && Array.isArray(raw.allowedHosts) ? raw.allowedHosts : [];
1433
+ const allowedHosts = hosts.filter((host) => typeof host === "string" && host !== "");
1434
+ return allowedHosts.length > 0 ? { allowedHosts } : {};
1435
+ }
1436
+
1437
+ // src/run.ts
1438
+ var STATEMENT_TIMEOUT = "30s";
1439
+ var SESSION_SETTINGS = { lock_timeout: "5s", idle_in_transaction_session_timeout: "60s" };
1440
+ var CURSOR = "db_rows";
1441
+ var CURSOR_STARTS = /^\s*(?:select|with|values|table)\b/i;
1442
+ var TRAILING_SEMICOLONS = /[;\s]+$/;
1443
+ var DOCTRINE_PARAMS = ["serverVersion", "charset"];
1444
+ var LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
1445
+ var BRACKETS = /^\[|\]$/g;
1446
+ var POSTGRES_SCHEMES = new Set(["postgres:", "postgresql:"]);
1447
+ var MYSQL_SCHEMES = new Set(["mysql:", "mysql2:", "mariadb:"]);
1448
+ var WRAP_ERRNOS = new Set([1064, 1060]);
1449
+ var MYSQL_TIMEOUTS = ["SET SESSION max_execution_time = 30000", "SET SESSION max_statement_time = 30"];
1450
+ var TEST_SUFFIX = "_test";
1451
+
1452
+ class Rollback extends Error {
1453
+ }
1454
+ function dialectOf(url) {
1455
+ if (POSTGRES_SCHEMES.has(url.protocol))
1456
+ return "postgres";
1457
+ if (MYSQL_SCHEMES.has(url.protocol))
1458
+ return "mysql";
1459
+ return fail(`the connection URL is ${url.protocol.replace(":", "")}://, but db reads Postgres (postgres://), MySQL and MariaDB (mysql://, mariadb://) only`);
1460
+ }
1461
+ function hostOf(url) {
1462
+ const host = url.hostname === "" ? url.searchParams.get("host") ?? "" : url.hostname;
1463
+ return host.replace(BRACKETS, "").toLowerCase();
1464
+ }
1465
+ var isLocal = (host) => host === "" || host.startsWith("/") || LOCAL_HOSTS.has(host);
1466
+ var DOCKER_NETWORK = /^172\.(?:1[6-9]|2\d|3[01])\./;
1467
+ function allowsKeyRetrieval(url) {
1468
+ try {
1469
+ const host = hostOf(new URL(url));
1470
+ return isLocal(host) || DOCKER_NETWORK.test(host);
1471
+ } catch {
1472
+ return false;
1473
+ }
1474
+ }
1475
+ function serviceNamed(services, host, dialect) {
1476
+ const exact = services.find((candidate) => candidate.name.toLowerCase() === host);
1477
+ if (exact !== undefined)
1478
+ return exact;
1479
+ const engine = dialect === "mysql" ? "mysql" : "postgres";
1480
+ const aliased = services.filter((candidate) => candidate.engine === engine && candidate.names.some((name) => name.toLowerCase() === host));
1481
+ if (aliased.length > 1)
1482
+ fail(`${host} names several services (${aliased.map((candidate) => candidate.name).join(", ")}): pick one with --service`);
1483
+ return aliased[0];
1484
+ }
1485
+ async function reachable(value, home = homedir2()) {
1486
+ let url;
1487
+ try {
1488
+ url = new URL(value);
1489
+ } catch {
1490
+ fail("the connection URL does not parse");
1491
+ }
1492
+ const dialect = dialectOf(url);
1493
+ const host = hostOf(url);
1494
+ if (isLocal(host))
1495
+ return url;
1496
+ const service = isIP(host) === 0 ? serviceNamed(await composeServices(), host, dialect) : undefined;
1497
+ if (service !== undefined) {
1498
+ url.hostname = service.host.includes(":") ? `[${service.host}]` : service.host;
1499
+ url.port = String(service.port);
1500
+ return url;
1501
+ }
1502
+ if (!((await loadSettings(home)).allowedHosts ?? []).some((allowed) => allowed.toLowerCase().replace(BRACKETS, "") === host))
1503
+ 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`);
1504
+ return url;
1505
+ }
1506
+ async function connectionUrl({ env, service, container, database }, home = homedir2()) {
1507
+ if (service !== undefined && container !== undefined)
1508
+ fail("--service and --container name two databases: pick one");
1509
+ const isNamed = service !== undefined || container !== undefined;
1510
+ const value = isNamed ? undefined : process7.env[env ?? DEFAULT_ENV];
1511
+ let url;
1512
+ if (value !== undefined && value !== "")
1513
+ url = await reachable(value, home);
1514
+ else if (env !== undefined && !isNamed)
1515
+ fail(`${env} is not set: put the connection URL in a .env file or the environment`);
1516
+ else
1517
+ url = new URL(serviceUrl(container === undefined ? pickService(await composeServices(), service) : await containerService(container)));
1518
+ for (const param of DOCTRINE_PARAMS)
1519
+ url.searchParams.delete(param);
1520
+ if (database !== undefined)
1521
+ url.pathname = `/${database}`;
1522
+ return url.href;
1523
+ }
1524
+ function databaseOfUrl(url) {
1525
+ const { pathname } = new URL(url);
1526
+ try {
1527
+ return decodeURIComponent(pathname.slice(1));
1528
+ } catch {
1529
+ return pathname.slice(1);
1530
+ }
1531
+ }
1532
+ function toResult(rows) {
1533
+ return Object.assign([...rows], { affected: rows.count ?? rows.affectedRows ?? rows.length });
1534
+ }
1535
+ var bunConnect = (url, dialect, readOnly) => {
1536
+ const sql = new SQL({ url, max: 1, connectionTimeout: 10, ...dialect === "postgres" ? { connection: { ...SESSION_SETTINGS, ...readOnly ? { default_transaction_read_only: "on" } : {} } } : { allowPublicKeyRetrieval: allowsKeyRetrieval(url) } });
1537
+ return {
1538
+ async transaction(work, isReadOnly) {
1539
+ if (dialect === "postgres") {
1540
+ const body = async (tx) => {
1541
+ await tx.unsafe(`SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT}'`);
1542
+ await work({ unsafe: async (statement, params) => toResult(await tx.unsafe(statement, params)) });
1543
+ };
1544
+ await (isReadOnly ? sql.begin("read only", body) : sql.begin(body));
1545
+ return;
1546
+ }
1547
+ const connection = await sql.reserve();
1548
+ try {
1549
+ await mysqlTransaction({ unsafe: async (statement, params) => connection.unsafe(statement, params) }, work, isReadOnly);
1550
+ } finally {
1551
+ await connection.release();
1552
+ }
1553
+ },
1554
+ async close() {
1555
+ await sql.close();
1556
+ }
1557
+ };
1558
+ };
1559
+ async function mysqlTransaction(connection, work, readOnly) {
1560
+ for (const timeout of MYSQL_TIMEOUTS) {
1561
+ try {
1562
+ await connection.unsafe(timeout);
1563
+ } catch {}
1564
+ }
1565
+ await connection.unsafe(readOnly ? "START TRANSACTION READ ONLY" : "START TRANSACTION");
1566
+ try {
1567
+ await work({ unsafe: async (statement, params) => toResult(await connection.unsafe(statement, params)) });
1568
+ } catch (error) {
1569
+ try {
1570
+ await connection.unsafe("ROLLBACK");
1571
+ } catch {}
1572
+ throw error;
1573
+ }
1574
+ await connection.unsafe("COMMIT");
1575
+ }
1576
+ var isWrapError = (error) => error instanceof Error && WRAP_ERRNOS.has(error.errno ?? 0);
1577
+ async function fetchRows(tx, dialect, statement, params, limit) {
1578
+ if (limit === undefined || !CURSOR_STARTS.test(statement))
1579
+ return tx.unsafe(statement, params);
1580
+ if (dialect === "postgres") {
1581
+ await tx.unsafe(`DECLARE ${CURSOR} NO SCROLL CURSOR FOR ${statement}`, params);
1582
+ return tx.unsafe(`FETCH FORWARD ${limit + 1} FROM ${CURSOR}`);
1583
+ }
1584
+ try {
1585
+ return await tx.unsafe(`select * from (
1586
+ ${statement.replace(TRAILING_SEMICOLONS, "")}
1587
+ ) as ${CURSOR} limit ${limit + 1}`, params);
1588
+ } catch (error) {
1589
+ if (!isWrapError(error))
1590
+ throw error;
1591
+ return tx.unsafe(statement, params);
1592
+ }
1593
+ }
1594
+ function messageOf(error, url) {
1595
+ return scrub(error instanceof Error ? error.message : String(error), url);
1596
+ }
1597
+ async function readRows(url, statement, params = [], limit, connect = bunConnect) {
1598
+ const dialect = dialectOf(new URL(url));
1599
+ const session = connect(url, dialect, true);
1600
+ let rows = [];
1601
+ try {
1602
+ await session.transaction(async (tx) => {
1603
+ rows = [...await fetchRows(tx, dialect, statement, params, limit)];
1604
+ throw new Rollback;
1605
+ }, true);
1606
+ } catch (error) {
1607
+ if (!(error instanceof Rollback))
1608
+ fail(messageOf(error, url), 1);
1609
+ } finally {
1610
+ await closeQuietly(session, url);
1611
+ }
1612
+ return rows;
1613
+ }
1614
+ function testWriteReasons(database, statement, dialect) {
1615
+ if (!database.endsWith(TEST_SUFFIX))
1616
+ return [`the database ${database === "" ? "is not named" : database} does not end in ${TEST_SUFFIX}`];
1617
+ return testWriteBlockers(statement, dialect, database);
1618
+ }
1619
+ async function writeRows(url, statement, connect = bunConnect) {
1620
+ const dialect = dialectOf(new URL(url));
1621
+ const declared = testWriteReasons(databaseOfUrl(url), statement, dialect);
1622
+ if (declared.length > 0)
1623
+ return { isRun: false, reasons: declared };
1624
+ const session = connect(url, dialect, false);
1625
+ let outcome = { isRun: false, reasons: ["not run"] };
1626
+ try {
1627
+ await session.transaction(async (tx) => {
1628
+ const [current] = await tx.unsafe(dialect === "postgres" ? "select current_database() as name" : "select database() as name");
1629
+ const database = String(current?.name ?? "");
1630
+ const reasons = testWriteReasons(database, statement, dialect);
1631
+ if (reasons.length > 0) {
1632
+ outcome = { isRun: false, reasons };
1633
+ throw new Rollback;
1634
+ }
1635
+ const result = await tx.unsafe(statement);
1636
+ outcome = { isRun: true, database, rows: [...result], affected: result.affected ?? 0 };
1637
+ }, false);
1638
+ } catch (error) {
1639
+ if (!(error instanceof Rollback))
1640
+ fail(messageOf(error, url), 1);
1641
+ } finally {
1642
+ await closeQuietly(session, url);
1643
+ }
1644
+ return outcome;
1645
+ }
1646
+ async function closeQuietly(session, url) {
1647
+ try {
1648
+ await session.close();
1649
+ } catch (error) {
1650
+ console.error(messageOf(error, url));
1651
+ }
1652
+ }
1653
+
1654
+ // src/commands/query.ts
1655
+ var usage = `db query "<sql>"
1656
+
1657
+ 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.
1658
+
1659
+ ${WRITE_NOTE}
1660
+
1661
+ ${HOSTS_NOTE}
1662
+
1663
+ Exits 0 when the statement ran, 1 when the database refused it, was unreachable or the statement would write and was not run, 2 on a usage error or a host that is not allowed.`;
1664
+ var options = { ...connectionOptions, ...outputOptions };
1665
+ var WRITE_EXIT = 1;
1666
+ var NO_SQL = "no SQL given: pass it as an argument or on stdin";
1667
+ async function readSql(positionals) {
1668
+ const sql = positionals.length === 0 ? await readInput("-", { noStdin: NO_SQL }) : positionals.join(" ");
1669
+ if (sql.trim() === "")
1670
+ fail(NO_SQL);
1671
+ return sql;
1672
+ }
1673
+ function handBack(sql, reasons, note = "") {
1674
+ console.log(`db: not run, this statement would write or cannot be shown to only read (${reasons.join("; ")})${note}. Run it yourself:
1675
+
1676
+ \`\`\`sql
1677
+ ${sql.trim()}
1678
+ \`\`\``);
1679
+ return WRITE_EXIT;
1680
+ }
1681
+ function isWrite(sql) {
1682
+ return inspect(sql, "postgres").reasons.length > 0 || inspect(sql, "mysql").reasons.length > 0;
1683
+ }
1684
+ async function query(args) {
1685
+ const parsed = parse(args, usage, options);
1686
+ const { values, positionals } = parsed;
1687
+ const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
1688
+ const sql = await readSql(positionals);
1689
+ let url;
1690
+ try {
1691
+ url = await connectionUrl(values);
1692
+ } catch (error) {
1693
+ if (error instanceof Exit && isWrite(sql))
1694
+ return handBack(sql, inspect(sql, "postgres").reasons.concat(inspect(sql, "mysql").reasons));
1695
+ throw error;
1696
+ }
1697
+ const dialect = dialectOf(new URL(url));
1698
+ const verdict = inspect(sql, dialect);
1699
+ if (verdict.reasons.length > 0) {
1700
+ const written = await writeRows(url, sql);
1701
+ if (!written.isRun)
1702
+ return handBack(sql, verdict.reasons, databaseOfUrl(url).endsWith(TEST_SUFFIX) ? `; not run on this ${TEST_SUFFIX} database either: ${written.reasons.join("; ")}` : "");
1703
+ const shown = shape(written.rows, limit, values.raw === true, false);
1704
+ if (values.json === true)
1705
+ console.log(JSON.stringify({ database: written.database, affected: written.affected, columns: shown.columns, rows: shown.rows, truncated: shown.truncated, masked: shown.masked }, jsonValue, 2));
1706
+ else
1707
+ console.log(`ran on ${written.database}, ${written.affected} ${written.affected === 1 ? "row" : "rows"} affected${written.rows.length === 0 ? "" : `
1708
+ ${render(shown, false)}`}`);
1709
+ return 0;
1710
+ }
1711
+ if (verdict.statements > 1)
1712
+ fail("one statement at a time");
1713
+ const rows = await readRows(url, sql, [], limit);
1714
+ console.log(render(shape(rows, limit, values.raw === true, false), values.json === true));
1715
+ return 0;
1716
+ }
1717
+
1718
+ // src/commands/schema.ts
1719
+ var options2 = { ...connectionOptions, ...outputOptions };
1720
+ 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.";
1721
+ var TABLES = `
1722
+ select n.nspname as schema, c.relname as name,
1723
+ case c.relkind when 'r' then 'table' when 'p' then 'partitioned' when 'v' then 'view' when 'm' then 'matview' else 'foreign' end as kind,
1724
+ c.reltuples::bigint as rows_estimate
1725
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
1726
+ where c.relkind in ('r', 'p', 'v', 'm', 'f') and n.nspname not in ('pg_catalog', 'information_schema') and n.nspname not like 'pg_toast%'
1727
+ order by n.nspname, c.relname`;
1728
+ var DATABASES = `
1729
+ select datname as name, datname = current_database() as current, pg_size_pretty(pg_database_size(datname)) as size
1730
+ from pg_database
1731
+ where not datistemplate and has_database_privilege(datname, 'CONNECT')
1732
+ order by datname`;
1733
+ var COLUMNS = `
1734
+ select c.table_schema as schema, c.column_name as name, c.data_type as type, c.is_nullable as nullable, c.column_default as default_value,
1735
+ exists (
1736
+ select 1 from information_schema.table_constraints t
1737
+ join information_schema.key_column_usage k on k.constraint_name = t.constraint_name and k.constraint_schema = t.constraint_schema
1738
+ where t.constraint_type = 'PRIMARY KEY' and k.table_schema = c.table_schema and k.table_name = c.table_name and k.column_name = c.column_name
1739
+ ) as primary_key
1740
+ from information_schema.columns c
1741
+ where c.table_name = $1 and ($2::text is null or c.table_schema = $2)
1742
+ and c.table_schema not in ('pg_catalog', 'information_schema')
1743
+ order by c.table_schema, c.ordinal_position`;
1744
+ var MYSQL_SYSTEM = "'mysql', 'information_schema', 'performance_schema', 'sys'";
1745
+ var MYSQL_TABLES = `
1746
+ select table_schema as \`schema\`, table_name as name,
1747
+ case table_type when 'BASE TABLE' then 'table' when 'VIEW' then 'view' else lower(table_type) end as kind,
1748
+ table_rows as rows_estimate
1749
+ from information_schema.tables
1750
+ where table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})
1751
+ order by table_schema, table_name`;
1752
+ var MYSQL_DATABASES = `
1753
+ select s.schema_name as name, s.schema_name = database() as \`current\`, concat(round(coalesce(sum(t.data_length + t.index_length), 0) / 1048576, 1), ' MB') as size
1754
+ from information_schema.schemata s
1755
+ left join information_schema.tables t on t.table_schema = s.schema_name
1756
+ where s.schema_name not in ('information_schema', 'performance_schema', 'sys')
1757
+ group by s.schema_name
1758
+ order by s.schema_name`;
1759
+ var MYSQL_COLUMNS = `
1760
+ 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
1761
+ from information_schema.columns
1762
+ where table_name = ?`;
1763
+ async function show(args, usage, work) {
1764
+ const parsed = parse(args, usage, options2);
1765
+ const { values, positionals } = parsed;
1766
+ const plans = work(positionals);
1767
+ const limit = wholeNumber(values.limit, "limit", DEFAULT_LIMIT, 0);
1768
+ const url = await connectionUrl(values);
1769
+ const { sql, params } = plans[dialectOf(new URL(url))];
1770
+ const rows = await readRows(url, sql, params, limit);
1771
+ console.log(render(shape(rows, limit, true, false), values.json === true));
1772
+ return 0;
1773
+ }
1774
+ async function tables(args) {
1775
+ return show(args, `db tables
1776
+
1777
+ Lists the tables, views and materialized views outside the system schemas, with an estimated row count.
1778
+
1779
+ ${HOSTS_NOTE}
1780
+
1781
+ ${EXITS}`, () => ({ postgres: { sql: TABLES, params: [] }, mysql: { sql: MYSQL_TABLES, params: [] } }));
1782
+ }
1783
+ async function databases(args) {
1784
+ return show(args, `db dbs
1785
+
1786
+ Lists the databases the connection may open, with their size, marking the one it reads, so --database can pick another.
1787
+
1788
+ ${HOSTS_NOTE}
1789
+
1790
+ ${EXITS}`, () => ({ postgres: { sql: DATABASES, params: [] }, mysql: { sql: MYSQL_DATABASES, params: [] } }));
1791
+ }
1792
+ async function describe(args) {
1793
+ return show(args, `db describe <table>
1794
+
1795
+ 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).
1796
+
1797
+ ${HOSTS_NOTE}
1798
+
1799
+ ${EXITS}`, ([target, ...extra]) => {
1800
+ if (target === undefined || extra.length > 0)
1801
+ fail("db describe takes one table name");
1802
+ const [first, second] = target.split(".");
1803
+ const table = second ?? first;
1804
+ const mysqlScope = second === undefined ? ` and table_schema = coalesce(database(), table_schema) and table_schema not in (${MYSQL_SYSTEM})` : " and table_schema = ?";
1805
+ return {
1806
+ postgres: { sql: COLUMNS, params: second === undefined ? [first, null] : [second, first] },
1807
+ mysql: { sql: `${MYSQL_COLUMNS}${mysqlScope}
1808
+ order by table_schema, ordinal_position`, params: second === undefined ? [table] : [table, first] }
1809
+ };
1810
+ });
1811
+ }
1812
+
1813
+ // src/cli.ts
1814
+ process8.exitCode = await runCli({
1815
+ name: "db",
1816
+ version,
1817
+ about: "read-only SQL against Postgres, MySQL and MariaDB, credentials never shown, writes only on a _test database",
1818
+ replaces: "psql or mysql with the connection string on the command line, docker exec <container> psql -U ...",
1819
+ 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"]],
1820
+ commands: {
1821
+ query: { run: query, summary: 'run one read-only statement (the default: db "<sql>"), a write runs on a _test database and is printed otherwise' },
1822
+ tables: { run: tables, summary: "list tables and views with an estimated row count" },
1823
+ describe: { run: describe, summary: "columns of a table with type, nullability, default and primary key" },
1824
+ dbs: { run: databases, summary: "databases the connection may open, with their size" }
1825
+ },
1826
+ defaultCommand: "query"
1827
+ });