mysqldeck 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cli.js +4661 -0
  3. package/dist/web/assets/DiagramView-bSyOAvy0.css +1 -0
  4. package/dist/web/assets/DiagramView-lCPb7W2V.js +8 -0
  5. package/dist/web/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/dist/web/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/dist/web/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/dist/web/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/dist/web/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  10. package/dist/web/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  11. package/dist/web/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  12. package/dist/web/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  13. package/dist/web/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  14. package/dist/web/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  15. package/dist/web/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  16. package/dist/web/assets/ibm-plex-mono-cyrillic-400-normal-BSMlKf0J.woff2 +0 -0
  17. package/dist/web/assets/ibm-plex-mono-cyrillic-400-normal-CEL4l2ZJ.woff +0 -0
  18. package/dist/web/assets/ibm-plex-mono-cyrillic-500-normal-Ael50iVv.woff +0 -0
  19. package/dist/web/assets/ibm-plex-mono-cyrillic-500-normal-Bq9vWWag.woff2 +0 -0
  20. package/dist/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-DMdlQ8Kv.woff +0 -0
  21. package/dist/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-xuaO2J-f.woff2 +0 -0
  22. package/dist/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-BIfNGwUT.woff +0 -0
  23. package/dist/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-BqneJy0T.woff2 +0 -0
  24. package/dist/web/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  25. package/dist/web/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  26. package/dist/web/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  27. package/dist/web/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  28. package/dist/web/assets/ibm-plex-mono-latin-ext-400-normal-BmRBH3aV.woff2 +0 -0
  29. package/dist/web/assets/ibm-plex-mono-latin-ext-400-normal-D3D2R8hC.woff +0 -0
  30. package/dist/web/assets/ibm-plex-mono-latin-ext-500-normal-CAhNIIs5.woff2 +0 -0
  31. package/dist/web/assets/ibm-plex-mono-latin-ext-500-normal-CZ70TYgx.woff +0 -0
  32. package/dist/web/assets/ibm-plex-mono-vietnamese-400-normal-BulugwFq.woff2 +0 -0
  33. package/dist/web/assets/ibm-plex-mono-vietnamese-400-normal-DDuiU_S-.woff +0 -0
  34. package/dist/web/assets/ibm-plex-mono-vietnamese-500-normal-C8zxqsMH.woff +0 -0
  35. package/dist/web/assets/ibm-plex-mono-vietnamese-500-normal-DZ4AoWbu.woff2 +0 -0
  36. package/dist/web/assets/ibm-plex-sans-cyrillic-ext-wght-normal-d45eAU9y.woff2 +0 -0
  37. package/dist/web/assets/ibm-plex-sans-cyrillic-wght-normal-BAAhND-U.woff2 +0 -0
  38. package/dist/web/assets/ibm-plex-sans-greek-wght-normal-CmyJS8uq.woff2 +0 -0
  39. package/dist/web/assets/ibm-plex-sans-latin-ext-wght-normal-CIII54If.woff2 +0 -0
  40. package/dist/web/assets/ibm-plex-sans-latin-wght-normal-IvpUvPa2.woff2 +0 -0
  41. package/dist/web/assets/ibm-plex-sans-vietnamese-wght-normal-Dg1JeJN0.woff2 +0 -0
  42. package/dist/web/assets/index-BzL05xNS.js +112 -0
  43. package/dist/web/assets/index-CJurLK-A.css +2 -0
  44. package/dist/web/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  45. package/dist/web/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  46. package/dist/web/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  47. package/dist/web/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  48. package/dist/web/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  49. package/dist/web/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  50. package/dist/web/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  51. package/dist/web/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  52. package/dist/web/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  53. package/dist/web/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  54. package/dist/web/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  55. package/dist/web/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  56. package/dist/web/index.html +18 -0
  57. package/package.json +105 -4
  58. package/README.md +0 -3
package/dist/cli.js ADDED
@@ -0,0 +1,4661 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import crypto from "node:crypto";
5
+ import pc from "picocolors";
6
+ import openUrl from "open";
7
+ import { Command, InvalidArgumentError, Option } from "commander";
8
+ import mysql from "mysql2/promise";
9
+ import { Readable, Transform } from "node:stream";
10
+ import { createGunzip, createGzip } from "node:zlib";
11
+ import { Hono } from "hono";
12
+ import { HTTPException } from "hono/http-exception";
13
+ import { getConnInfo } from "@hono/node-server/conninfo";
14
+ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
15
+ import { parse as parse$1 } from "hono/utils/cookie";
16
+ import { z } from "zod";
17
+ import path from "node:path";
18
+ import { serve } from "@hono/node-server";
19
+ import { stream } from "hono/streaming";
20
+ import yazl from "yazl";
21
+ import { WebSocketServer } from "ws";
22
+ // ../../packages/security/src/csp.ts
23
+ /**
24
+ * Content-Security-Policy for a deck's built UI: everything same-origin, no
25
+ * inline scripts. Inline styles are allowed because editors such as
26
+ * CodeMirror inject <style> tags. Pass overrides to replace a directive.
27
+ */
28
+ const DEFAULT_CSP_DIRECTIVES = {
29
+ "default-src": "'self'",
30
+ "script-src": "'self'",
31
+ "style-src": "'self' 'unsafe-inline'",
32
+ "img-src": "'self' data:",
33
+ "connect-src": "'self'",
34
+ "frame-ancestors": "'self'",
35
+ "base-uri": "'none'"
36
+ };
37
+ function contentSecurityPolicy(overrides = {}) {
38
+ return Object.entries({
39
+ ...DEFAULT_CSP_DIRECTIVES,
40
+ ...overrides
41
+ }).map(([name, value]) => `${name} ${value}`).join("; ");
42
+ }
43
+ // ../../packages/security/src/secrets.ts
44
+ const sha256 = (s) => crypto.createHash("sha256").update(s).digest();
45
+ /** Constant-time string comparison (hashing first equalizes lengths). */
46
+ const safeEqual = (a, b) => crypto.timingSafeEqual(sha256(a), sha256(b));
47
+ /** A random, URL-safe password: 9 bytes → 12 characters. */
48
+ const generatePassword = (bytes = 9) => crypto.randomBytes(bytes).toString("base64url");
49
+ /**
50
+ * Hide the password in a connection string before printing it. Handles URLs
51
+ * (scheme://user:pass@host) and keyword/value strings (password=...).
52
+ */
53
+ function redactCredentials(connectionString) {
54
+ try {
55
+ const url = new URL(connectionString);
56
+ if (url.password) url.password = "****";
57
+ return url.toString();
58
+ } catch {
59
+ return connectionString.replace(/password=\S+/i, "password=****");
60
+ }
61
+ }
62
+ // ../../packages/security/src/sessions.ts
63
+ const IDLE_TIMEOUT_MS = 432e5;
64
+ const ABSOLUTE_TIMEOUT_MS = 6048e5;
65
+ /**
66
+ * In-memory login sessions. A deck is a single process started on demand, so
67
+ * restarting it logging everyone out is the desired behaviour.
68
+ */
69
+ var SessionStore = class {
70
+ sessions = /* @__PURE__ */ new Map();
71
+ create(username) {
72
+ this.sweep();
73
+ const token = crypto.randomBytes(32).toString("base64url");
74
+ const now = Date.now();
75
+ this.sessions.set(token, {
76
+ username,
77
+ createdAt: now,
78
+ lastSeen: now
79
+ });
80
+ return token;
81
+ }
82
+ /** Returns the username for a valid token and extends its idle window. */
83
+ touch(token) {
84
+ if (!token) return null;
85
+ const s = this.sessions.get(token);
86
+ if (!s) return null;
87
+ const now = Date.now();
88
+ if (now - s.lastSeen > IDLE_TIMEOUT_MS || now - s.createdAt > ABSOLUTE_TIMEOUT_MS) {
89
+ this.sessions.delete(token);
90
+ return null;
91
+ }
92
+ s.lastSeen = now;
93
+ return s.username;
94
+ }
95
+ revoke(token) {
96
+ if (token) this.sessions.delete(token);
97
+ }
98
+ sweep() {
99
+ const now = Date.now();
100
+ for (const [token, s] of this.sessions) if (now - s.lastSeen > IDLE_TIMEOUT_MS || now - s.createdAt > ABSOLUTE_TIMEOUT_MS) this.sessions.delete(token);
101
+ }
102
+ };
103
+ /** Fixed-window limiter for failed logins, keyed by client address. */
104
+ var LoginLimiter = class {
105
+ maxFailures;
106
+ windowMs;
107
+ failures = /* @__PURE__ */ new Map();
108
+ constructor(maxFailures = 10, windowMs = 6e5) {
109
+ this.maxFailures = maxFailures;
110
+ this.windowMs = windowMs;
111
+ }
112
+ /** Seconds until the client may try again, or 0 if allowed. */
113
+ retryAfter(key) {
114
+ const f = this.failures.get(key);
115
+ if (!f || Date.now() > f.resetAt) return 0;
116
+ return f.count >= this.maxFailures ? Math.ceil((f.resetAt - Date.now()) / 1e3) : 0;
117
+ }
118
+ fail(key) {
119
+ const now = Date.now();
120
+ const f = this.failures.get(key);
121
+ if (!f || now > f.resetAt) this.failures.set(key, {
122
+ count: 1,
123
+ resetAt: now + this.windowMs
124
+ });
125
+ else f.count++;
126
+ }
127
+ succeed(key) {
128
+ this.failures.delete(key);
129
+ }
130
+ };
131
+ // ../../packages/config/src/index.ts
132
+ /** "db/" → "/db", "/" → "", "" → "". */
133
+ function normalizeBasePath(input) {
134
+ const trimmed = input.trim().replace(/\/+$/, "");
135
+ if (!trimmed) return "";
136
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
137
+ }
138
+ function isLoopback(host) {
139
+ return host === "127.0.0.1" || host === "localhost" || host === "::1";
140
+ }
141
+ /** Binds every interface (0.0.0.0 or ::). */
142
+ function isWildcardHost(host) {
143
+ return host === "0.0.0.0" || host === "::";
144
+ }
145
+ /** The URL to print and open for a server bound to host:port. */
146
+ function serverUrl(host, port, basePath) {
147
+ return `http://${isWildcardHost(host) ? "localhost" : host}:${port}${basePath}/`;
148
+ }
149
+ /**
150
+ * Login credentials: the flag wins over the environment variable, and with
151
+ * neither a random password is generated (and printed at startup).
152
+ * Returns null when auth is disabled (--no-auth).
153
+ */
154
+ function resolveAuth(opts) {
155
+ if (!opts.enabled) return null;
156
+ const password = opts.password ?? (opts.passwordEnv ? process.env[opts.passwordEnv] : void 0);
157
+ return {
158
+ username: opts.username,
159
+ password: password ?? generatePassword(),
160
+ generated: password === void 0
161
+ };
162
+ }
163
+ /**
164
+ * The first candidate directory that exists, else the first candidate.
165
+ * Tools use it to find their built UI next to the bundled CLI or in dist/
166
+ * when run from source; pass URLs relative to the caller's import.meta.url.
167
+ */
168
+ function firstExistingDir(candidates) {
169
+ const dirs = candidates.map((c) => c instanceof URL ? fileURLToPath(c) : c);
170
+ return dirs.find((dir) => fs.existsSync(dir)) ?? dirs[0];
171
+ }
172
+ // ../../packages/logger/src/index.ts
173
+ /** Terminal colors (picocolors). They turn off automatically when output isn't a TTY or NO_COLOR is set. */
174
+ const colors = pc;
175
+ /** Status glyphs used in startup and error output. */
176
+ const symbols = {
177
+ ok: pc.green("✓"),
178
+ arrow: pc.cyan("➜"),
179
+ fail: pc.red("✗"),
180
+ warn: pc.red("⚠")
181
+ };
182
+ /** A dimmed, fixed-width label so values line up in a column. */
183
+ const label = (s, width = 12) => pc.dim(s.padEnd(width));
184
+ /** Print an unrecoverable error in the CLI style ("✗ message", optional detail lines). */
185
+ function printFatal(message, detail) {
186
+ const body = detail ? `${message}\n ${detail}` : message;
187
+ console.error(`\n ${symbols.fail} ${body}\n`);
188
+ }
189
+ /** Runtime logging prefixed with the tool name, e.g. "[pgdeck] idle client error: ...". */
190
+ function createLogger(name) {
191
+ const prefix = `[${name}]`;
192
+ return {
193
+ info: (...args) => console.log(prefix, ...args),
194
+ warn: (...args) => console.warn(prefix, ...args),
195
+ error: (...args) => console.error(prefix, ...args)
196
+ };
197
+ }
198
+ // ../../packages/cli/src/banner.ts
199
+ /** The startup summary every deck prints: URL, who can reach it, how to log in. */
200
+ function formatBanner({ name, version, server, url, port, before = [], after = [], resource = "data" }) {
201
+ const lines = [
202
+ "",
203
+ ` ${colors.bold(colors.blue(name))} ${colors.dim(`v${version}`)}`,
204
+ "",
205
+ ...before,
206
+ ` ${symbols.arrow} ${label("Web UI")}${colors.bold(colors.cyan(url))}`,
207
+ isLoopback(server.host) ? ` ${label("Reachable")}from this machine only ${colors.dim(`(remote: ssh -L ${port}:127.0.0.1:${port} <server>, a reverse proxy, or --host 0.0.0.0)`)}` : ` ${label("Reachable")}from the network on ${isWildcardHost(server.host) ? "all interfaces" : server.host}, port ${port}`
208
+ ];
209
+ if (server.basePath) lines.push(` ${label("Base path")}${server.basePath}`);
210
+ if (server.auth) {
211
+ const hint = server.auth.generated ? colors.dim(" (generated: pass --password to keep it fixed)") : "";
212
+ lines.push(` ${label("Login")}${server.auth.username} / ${colors.yellow(server.auth.password)}${hint}`);
213
+ } else lines.push(` ${label("Login")}${colors.yellow("disabled (--no-auth)")}`);
214
+ lines.push(...after);
215
+ if (!server.auth && !isLoopback(server.host)) lines.push("", colors.red(` ⚠ Auth is off and ${server.host} is reachable from the network.`), colors.red(` Anyone who can reach this port can read and modify the ${resource}.`));
216
+ lines.push("", colors.dim(" Press Ctrl+C to stop."), "");
217
+ return lines.join("\n");
218
+ }
219
+ function printBanner$1(opts) {
220
+ console.log(formatBanner(opts));
221
+ }
222
+ // ../../packages/cli/src/lifecycle.ts
223
+ /** Message for a failed listen(), with a hint when the port is taken. */
224
+ function listenErrorMessage(err, port) {
225
+ const e = err;
226
+ return e.code === "EADDRINUSE" ? `Port ${port} is already in use. Try --port ${port + 1}` : e.message;
227
+ }
228
+ /** Open the UI in the default browser; failures (headless boxes, no browser) are ignored. */
229
+ function openBrowser(url) {
230
+ openUrl(url).catch(() => {});
231
+ }
232
+ /**
233
+ * Run `cleanup` on Ctrl+C / SIGTERM, then exit. A second signal while cleanup
234
+ * is still running exits immediately with status 1.
235
+ */
236
+ function onShutdown(cleanup) {
237
+ let stopping = false;
238
+ const shutdown = async () => {
239
+ if (stopping) process.exit(1);
240
+ stopping = true;
241
+ console.log(colors.dim("\n Shutting down..."));
242
+ await cleanup();
243
+ process.exit(0);
244
+ };
245
+ process.on("SIGINT", shutdown);
246
+ process.on("SIGTERM", shutdown);
247
+ }
248
+ // ../../packages/cli/src/options.ts
249
+ function parsePort(value) {
250
+ const n = Number(value);
251
+ if (!Number.isInteger(n) || n < 0 || n > 65535) throw new InvalidArgumentError("must be an integer between 0 and 65535");
252
+ return n;
253
+ }
254
+ function parsePositiveInt(value) {
255
+ const n = Number(value);
256
+ if (!Number.isInteger(n) || n < 1) throw new InvalidArgumentError("must be a positive integer");
257
+ return n;
258
+ }
259
+ /**
260
+ * The flags every deck's web UI accepts. Returned as individual Options so a
261
+ * tool can interleave its own flags and control the order shown in --help:
262
+ *
263
+ * const o = serverOptions({ defaultPort: 47615 });
264
+ * program.addOption(o.port).addOption(o.host)...addOption(o.open);
265
+ */
266
+ function serverOptions({ defaultPort }) {
267
+ return {
268
+ port: new Option("-p, --port <port>", "port for the web UI").argParser(parsePort).default(Number(process.env.PORT) || defaultPort),
269
+ host: new Option("-H, --host <host>", "interface to bind (0.0.0.0 for containers/LAN)").default("127.0.0.1"),
270
+ user: new Option("-u, --user <name>", "login username").default("admin"),
271
+ password: new Option("-P, --password <password>", "login password (default: random, printed at startup)"),
272
+ noAuth: new Option("--no-auth", "disable the login prompt (only on a trusted host)"),
273
+ basePath: new Option("--base-path <path>", "serve under a path prefix, e.g. /db, if your proxy does not strip it").default(""),
274
+ open: new Option("--open", "open the UI in your browser").default(false)
275
+ };
276
+ }
277
+ // package.json
278
+ var version = "0.1.0";
279
+ var description = "A fast, modern web UI for MySQL. Run it with npx, browse and edit data, run SQL, and watch live stats.";
280
+ // src/db/client.ts
281
+ /** Text and blob wire types: returned as Buffers, then decoded by charset. */
282
+ const BYTES = /* @__PURE__ */ new Set([
283
+ "STRING",
284
+ "VAR_STRING",
285
+ "VARCHAR",
286
+ "BLOB",
287
+ "TINY_BLOB",
288
+ "MEDIUM_BLOB",
289
+ "LONG_BLOB"
290
+ ]);
291
+ const BINARY_CHARSET = 63;
292
+ /**
293
+ * Return every value as MySQL renders it as text, so display stays faithful
294
+ * (no Date timezone shifts, no BIGINT/DECIMAL precision loss) and what the UI
295
+ * shows can be sent back. Binary data becomes 0x… hex, BIT a decimal number.
296
+ */
297
+ const typeCast = (field, next) => {
298
+ if (field.type === "BIT") {
299
+ const b = field.buffer();
300
+ return b === null ? null : BigInt(`0x${b.toString("hex") || "0"}`).toString();
301
+ }
302
+ if (field.type === "GEOMETRY") {
303
+ const b = field.buffer();
304
+ return b === null ? null : `0x${b.toString("hex")}`;
305
+ }
306
+ if (BYTES.has(field.type)) return field.buffer();
307
+ if (field.type === "NULL") return next();
308
+ return field.string();
309
+ };
310
+ /** Which result columns hold binary data (charset 63), for toCells(). */
311
+ const binaryColumns = (fields) => (fields ?? []).map((f) => f.characterSet === BINARY_CHARSET);
312
+ const hex = (b) => `0x${b.toString("hex")}`;
313
+ /** Decode the Buffers typeCast left behind: binary columns as 0x…, text as UTF-8. */
314
+ function toCells(row, binary) {
315
+ return row.map((v, i) => {
316
+ if (v === null || v === void 0) return null;
317
+ if (Buffer.isBuffer(v)) return binary[i] ? hex(v) : v.toString("utf8");
318
+ return String(v);
319
+ });
320
+ }
321
+ function createPools(config) {
322
+ const options = {
323
+ ...config.client,
324
+ connectionLimit: 4,
325
+ maxIdle: 2,
326
+ idleTimeout: 3e4,
327
+ enableKeepAlive: true,
328
+ typeCast,
329
+ dateStrings: true,
330
+ supportBigNumbers: true,
331
+ bigNumberStrings: true,
332
+ decimalNumbers: false,
333
+ connectAttributes: { program_name: "mysqldeck" }
334
+ };
335
+ const init = (pool) => {
336
+ pool.pool.on("connection", (conn) => {
337
+ conn.query("SET SESSION information_schema_stats_expiry = 0", () => {});
338
+ if (config.readonly) conn.query("SET SESSION TRANSACTION READ ONLY", (err) => err && conn.destroy());
339
+ });
340
+ return pool;
341
+ };
342
+ const pool = init(mysql.createPool({
343
+ ...options,
344
+ multipleStatements: false
345
+ }));
346
+ let script = null;
347
+ const scriptPool = () => script ??= init(mysql.createPool({
348
+ ...options,
349
+ connectionLimit: 2,
350
+ multipleStatements: true
351
+ }));
352
+ return {
353
+ pool,
354
+ scriptPool,
355
+ close: async () => {
356
+ await Promise.allSettled([pool.end(), script?.end()]);
357
+ }
358
+ };
359
+ }
360
+ /** Run a statement, returning rows as arrays of raw text cells. */
361
+ async function queryRaw(conn, sql, values) {
362
+ const [rows, fields] = await conn.query({
363
+ sql,
364
+ values,
365
+ rowsAsArray: true
366
+ });
367
+ const binary = binaryColumns(fields);
368
+ return {
369
+ fields: (fields ?? []).map((f) => f.name),
370
+ rows: rows.map((r) => toCells(r, binary)),
371
+ binary
372
+ };
373
+ }
374
+ /**
375
+ * Rows as objects with plain string/null values: for catalog queries written
376
+ * by mysqldeck. Every field is also available in lower case, since MySQL 8
377
+ * names information_schema columns in upper case (DATA_TYPE) unless aliased.
378
+ */
379
+ async function queryObjects(conn, sql, values) {
380
+ const [rows, fields] = await conn.query({
381
+ sql,
382
+ values,
383
+ rowsAsArray: true
384
+ });
385
+ const names = (fields ?? []).map((f) => f.name);
386
+ const binary = binaryColumns(fields);
387
+ return rows.map((r) => {
388
+ const cells = toCells(r, binary);
389
+ const obj = {};
390
+ names.forEach((n, i) => {
391
+ obj[n] = cells[i] ?? null;
392
+ const lower = n.toLowerCase();
393
+ if (!(lower in obj)) obj[lower] = cells[i] ?? null;
394
+ });
395
+ return obj;
396
+ });
397
+ }
398
+ /** Run a statement that returns no rows. */
399
+ async function exec(conn, sql, values) {
400
+ const [res] = await conn.query({
401
+ sql,
402
+ values
403
+ });
404
+ return res;
405
+ }
406
+ async function withTransaction(pool, fn) {
407
+ const conn = await pool.getConnection();
408
+ try {
409
+ await conn.query("START TRANSACTION");
410
+ const result = await fn(conn);
411
+ await conn.query("COMMIT");
412
+ return result;
413
+ } catch (err) {
414
+ await conn.query("ROLLBACK").catch(() => {});
415
+ throw err;
416
+ } finally {
417
+ conn.release();
418
+ }
419
+ }
420
+ /**
421
+ * The callback-style connection under a promise one: its query() returns a
422
+ * Query emitter with .stream(), for reading big results row by row. (mysql2's
423
+ * typings call it a promise Connection; at runtime it is the core one.)
424
+ */
425
+ const coreConnection = (conn) => conn.connection;
426
+ // src/db/errors.ts
427
+ /** An error caused by the request, safe to show to the user. */
428
+ var UserError = class extends Error {
429
+ status;
430
+ constructor(message, status = 400) {
431
+ super(message);
432
+ this.status = status;
433
+ this.name = "UserError";
434
+ }
435
+ };
436
+ // src/shared/types.ts
437
+ const FILTER_OPS = [
438
+ "=",
439
+ "!=",
440
+ "<",
441
+ "<=",
442
+ ">",
443
+ ">=",
444
+ "contains",
445
+ "not contains",
446
+ "starts with",
447
+ "ends with",
448
+ "in",
449
+ "not in",
450
+ "like",
451
+ "not like",
452
+ "regexp",
453
+ "is null",
454
+ "is not null"
455
+ ];
456
+ /** Operators whose value is a comma-separated list. */
457
+ const LIST_OPS = ["in", "not in"];
458
+ /** Operators that take no value. */
459
+ const UNARY_OPS = ["is null", "is not null"];
460
+ const OBJECT_KINDS = [
461
+ "function",
462
+ "procedure",
463
+ "trigger",
464
+ "event"
465
+ ];
466
+ // src/db/sql.ts
467
+ const quoteIdent$3 = (name) => `\`${name.replace(/`/g, "``")}\``;
468
+ const qualified = (schema, table) => `${quoteIdent$3(schema)}.${quoteIdent$3(table)}`;
469
+ /** A string literal safe in any sql_mode (with or without NO_BACKSLASH_ESCAPES). */
470
+ function quoteLiteral$1(s) {
471
+ if (s.includes("\\") || /[\0\n\r\x1a]/.test(s)) return `0x${Buffer.from(s, "utf8").toString("hex")}`;
472
+ return `'${s.replace(/'/g, "''")}'`;
473
+ }
474
+ /**
475
+ * SQL for each filter operator. `col` is a quoted identifier, `p` a `?`
476
+ * placeholder. Text comparisons go through CAST(… AS CHAR) so they work on
477
+ * every column type, and "contains"-style ones ignore case whatever the
478
+ * column's collation.
479
+ */
480
+ const FILTER_SQL = {
481
+ "=": (c, p) => `${c} = ${p}`,
482
+ "!=": (c, p) => `${c} <> ${p}`,
483
+ "<": (c, p) => `${c} < ${p}`,
484
+ "<=": (c, p) => `${c} <= ${p}`,
485
+ ">": (c, p) => `${c} > ${p}`,
486
+ ">=": (c, p) => `${c} >= ${p}`,
487
+ contains: (c, p) => `LOWER(CAST(${c} AS CHAR)) LIKE CONCAT('%', LOWER(${p}), '%')`,
488
+ "not contains": (c, p) => `LOWER(CAST(${c} AS CHAR)) NOT LIKE CONCAT('%', LOWER(${p}), '%')`,
489
+ "starts with": (c, p) => `LOWER(CAST(${c} AS CHAR)) LIKE CONCAT(LOWER(${p}), '%')`,
490
+ "ends with": (c, p) => `LOWER(CAST(${c} AS CHAR)) LIKE CONCAT('%', LOWER(${p}))`,
491
+ in: (c, p) => `CAST(${c} AS CHAR) IN (${p})`,
492
+ "not in": (c, p) => `CAST(${c} AS CHAR) NOT IN (${p})`,
493
+ like: (c, p) => `CAST(${c} AS CHAR) LIKE ${p}`,
494
+ "not like": (c, p) => `CAST(${c} AS CHAR) NOT LIKE ${p}`,
495
+ regexp: (c, p) => `CAST(${c} AS CHAR) REGEXP ${p}`,
496
+ "is null": (c) => `${c} IS NULL`,
497
+ "is not null": (c) => `${c} IS NOT NULL`
498
+ };
499
+ const isUnaryOp = (op) => UNARY_OPS.includes(op);
500
+ const isListOp = (op) => LIST_OPS.includes(op);
501
+ /** "a, b , c" → ["a", "b", "c"] for IN / NOT IN. */
502
+ const splitList = (v) => v.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
503
+ /**
504
+ * Incremental splitter for mysql-client style scripts (mysqldump output,
505
+ * editor contents). Splits on the current delimiter outside quotes,
506
+ * backticks and comments, and honours the client-side DELIMITER command used
507
+ * around procedure and trigger bodies. `/*! … *\/` version comments are kept
508
+ * as part of their statement: the server executes them.
509
+ */
510
+ var ScriptScanner = class {
511
+ buf = "";
512
+ pos = 0;
513
+ stmtStart = 0;
514
+ line = 1;
515
+ stmtLine = 1;
516
+ mode = "normal";
517
+ blank = true;
518
+ delimiter = ";";
519
+ push(text, final) {
520
+ this.buf += text;
521
+ const out = [];
522
+ while (this.pos < this.buf.length) {
523
+ const s = this.buf;
524
+ const ch = s[this.pos];
525
+ switch (this.mode) {
526
+ case "line-comment":
527
+ if (ch === "\n") {
528
+ this.mode = "normal";
529
+ this.line++;
530
+ }
531
+ this.pos++;
532
+ continue;
533
+ case "block-comment":
534
+ if (ch === "*" && this.pos + 1 >= s.length && !final) return this.compact(out);
535
+ if (ch === "\n") this.line++;
536
+ if (ch === "*" && s[this.pos + 1] === "/") {
537
+ this.mode = "normal";
538
+ this.pos += 2;
539
+ } else this.pos++;
540
+ continue;
541
+ case "single":
542
+ case "double":
543
+ case "backtick": {
544
+ if (ch === "\n") this.line++;
545
+ const q = this.mode === "single" ? "'" : this.mode === "double" ? "\"" : "`";
546
+ if (ch === "\\" && this.mode !== "backtick") {
547
+ if (this.pos + 1 >= s.length && !final) return this.compact(out);
548
+ if (s[this.pos + 1] === "\n") this.line++;
549
+ this.pos += 2;
550
+ } else if (ch === q) {
551
+ if (this.pos + 1 >= s.length && !final) return this.compact(out);
552
+ if (s[this.pos + 1] === q) this.pos += 2;
553
+ else {
554
+ this.mode = "normal";
555
+ this.pos++;
556
+ }
557
+ } else this.pos++;
558
+ continue;
559
+ }
560
+ }
561
+ if (this.blank) {
562
+ if (/\s/.test(ch)) {
563
+ if (ch === "\n") this.line++;
564
+ this.pos++;
565
+ this.stmtStart = this.pos;
566
+ this.stmtLine = this.line;
567
+ continue;
568
+ }
569
+ if (ch === "d" || ch === "D") {
570
+ const nl = s.indexOf("\n", this.pos);
571
+ if (nl === -1 && !final) return this.compact(out);
572
+ const lineText = s.slice(this.pos, nl === -1 ? s.length : nl);
573
+ const m = /^delimiter\s+(\S+)\s*$/i.exec(lineText.replace(/\r$/, ""));
574
+ if (m) {
575
+ this.delimiter = m[1];
576
+ this.pos = nl === -1 ? s.length : nl + 1;
577
+ if (nl !== -1) this.line++;
578
+ this.stmtStart = this.pos;
579
+ this.stmtLine = this.line;
580
+ continue;
581
+ }
582
+ }
583
+ }
584
+ if ((ch === "-" || ch === "/") && this.pos + 1 >= s.length && !final) return this.compact(out);
585
+ if (ch === "#" || ch === "-" && s[this.pos + 1] === "-" && /[\s]/.test(s[this.pos + 2] ?? (final ? " " : ""))) {
586
+ if (ch === "-" && this.pos + 2 >= s.length && !final) return this.compact(out);
587
+ this.mode = "line-comment";
588
+ this.pos += ch === "#" ? 1 : 2;
589
+ continue;
590
+ }
591
+ if (ch === "-" && s[this.pos + 1] === "-" && this.pos + 2 >= s.length && !final) return this.compact(out);
592
+ if (ch === "/" && s[this.pos + 1] === "*" && s[this.pos + 2] !== "!" && s[this.pos + 2] !== "+") {
593
+ if (this.pos + 2 >= s.length && !final) return this.compact(out);
594
+ this.mode = "block-comment";
595
+ this.pos += 2;
596
+ continue;
597
+ }
598
+ if (s.startsWith(this.delimiter, this.pos)) {
599
+ const sql = s.slice(this.stmtStart, this.pos).trim();
600
+ this.pos += this.delimiter.length;
601
+ if (sql && !isOnlyComments(sql)) out.push({
602
+ sql,
603
+ line: this.stmtLine
604
+ });
605
+ this.stmtStart = this.pos;
606
+ this.stmtLine = this.line;
607
+ this.blank = true;
608
+ continue;
609
+ }
610
+ if (this.delimiter.length > 1 && this.delimiter.startsWith(ch) && s.length - this.pos < this.delimiter.length) {
611
+ if (!final) return this.compact(out);
612
+ }
613
+ if (ch === "\n") this.line++;
614
+ if (ch === "'") this.mode = "single";
615
+ else if (ch === "\"") this.mode = "double";
616
+ else if (ch === "`") this.mode = "backtick";
617
+ this.blank = false;
618
+ this.pos++;
619
+ }
620
+ if (final) {
621
+ const tail = this.buf.slice(this.stmtStart).trim();
622
+ if (tail && !isOnlyComments(tail)) out.push({
623
+ sql: tail,
624
+ line: this.stmtLine
625
+ });
626
+ this.buf = "";
627
+ this.pos = this.stmtStart = 0;
628
+ return out;
629
+ }
630
+ return this.compact(out);
631
+ }
632
+ /** Drop consumed text so the buffer only holds the statement in progress. */
633
+ compact(out) {
634
+ if (this.stmtStart > 0) {
635
+ this.buf = this.buf.slice(this.stmtStart);
636
+ this.pos -= this.stmtStart;
637
+ this.stmtStart = 0;
638
+ }
639
+ return out;
640
+ }
641
+ };
642
+ function isOnlyComments(sql) {
643
+ return stripLeadingComments(sql) === "";
644
+ }
645
+ /**
646
+ * Statement text without leading whitespace and comments, for classifying it.
647
+ * A version comment such as `/*!40101 SET …*\/` is unwrapped, since MySQL runs it.
648
+ */
649
+ function stripLeadingComments(sql) {
650
+ let s = sql;
651
+ for (;;) {
652
+ const t = s.replace(/^\s+/, "");
653
+ if (t.startsWith("#") || /^--(\s|$)/.test(t)) {
654
+ const nl = t.indexOf("\n");
655
+ s = nl === -1 ? "" : t.slice(nl + 1);
656
+ } else if (/^\/\*[!+]/.test(t)) return t.replace(/^\/\*[!+]\d*\s*/, "").replace(/\*\/\s*$/, "");
657
+ else if (t.startsWith("/*")) {
658
+ const end = t.indexOf("*/");
659
+ s = end === -1 ? "" : t.slice(end + 2);
660
+ } else return t;
661
+ }
662
+ }
663
+ /** Split SQL into statements, honouring quotes, comments and DELIMITER. */
664
+ function splitStatements(sql) {
665
+ return new ScriptScanner().push(sql, true).map((s) => s.sql);
666
+ }
667
+ /** First keyword of a statement, upper-cased: SELECT, INSERT, CREATE… */
668
+ function statementKeyword(sql) {
669
+ const head = stripLeadingComments(sql).replace(/^\(+\s*/, "");
670
+ return (/^[A-Za-z]+/.exec(head)?.[0] ?? "").toUpperCase();
671
+ }
672
+ const READ_KEYWORDS = /* @__PURE__ */ new Set([
673
+ "SELECT",
674
+ "WITH",
675
+ "SHOW",
676
+ "DESCRIBE",
677
+ "DESC",
678
+ "EXPLAIN",
679
+ "TABLE",
680
+ "VALUES",
681
+ "HELP",
682
+ "USE"
683
+ ]);
684
+ /**
685
+ * In --readonly mode the SQL editor accepts only statements that read. The
686
+ * session is READ ONLY too, but that doesn't stop SET (which could turn it
687
+ * off), KILL, FLUSH or SELECT … INTO OUTFILE.
688
+ */
689
+ function readonlyRefusal(sql) {
690
+ for (const stmt of splitStatements(sql)) {
691
+ const kw = statementKeyword(stmt);
692
+ if (!READ_KEYWORDS.has(kw)) return `mysqldeck is running in --readonly mode: ${kw || "this"} statements are not allowed.`;
693
+ if (/\binto\s+(outfile|dumpfile)\b/i.test(stmt)) return "mysqldeck is running in --readonly mode: INTO OUTFILE is not allowed.";
694
+ if (kw === "EXPLAIN" && /^\s*explain\s+analyze\b/i.test(stripLeadingComments(stmt)) && /\b(insert|update|delete|replace)\b/i.test(stmt)) return "mysqldeck is running in --readonly mode: EXPLAIN ANALYZE of a write is not allowed.";
695
+ }
696
+ return null;
697
+ }
698
+ // src/db/introspect.ts
699
+ const SYSTEM_DATABASES = /* @__PURE__ */ new Set([
700
+ "information_schema",
701
+ "mysql",
702
+ "performance_schema",
703
+ "sys"
704
+ ]);
705
+ /** Like pg_size_pretty: 8192 → "8192 bytes", 16384 → "16 kB". */
706
+ function prettySize(bytes) {
707
+ const units = [
708
+ "bytes",
709
+ "kB",
710
+ "MB",
711
+ "GB",
712
+ "TB",
713
+ "PB"
714
+ ];
715
+ let n = bytes;
716
+ let i = 0;
717
+ while (Math.abs(n) >= 10240 && i < units.length - 1) {
718
+ n /= 1024;
719
+ i++;
720
+ }
721
+ return `${Math.round(n)} ${units[i]}`;
722
+ }
723
+ const flavors = /* @__PURE__ */ new WeakMap();
724
+ /** MySQL or MariaDB, and which version: some catalog details differ. Cached per pool. */
725
+ function serverFlavor(ctx) {
726
+ let f = flavors.get(ctx.pool);
727
+ if (!f) {
728
+ f = queryObjects(ctx.pool, "SELECT VERSION() AS v").then(([r]) => {
729
+ const v = r?.v ?? "";
730
+ const [maj = 0, min = 0, patch = 0] = (/^(\d+)\.(\d+)\.(\d+)/.exec(v) ?? []).slice(1).map(Number);
731
+ return {
732
+ mariadb: /mariadb/i.test(v),
733
+ version: maj * 1e4 + min * 100 + patch
734
+ };
735
+ });
736
+ f.catch(() => flavors.delete(ctx.pool));
737
+ flavors.set(ctx.pool, f);
738
+ }
739
+ return f;
740
+ }
741
+ async function getInfo(ctx) {
742
+ const [r] = await queryObjects(ctx.pool, `SELECT VERSION() AS version, @@version_comment AS comment, DATABASE() AS \`database\`, CURRENT_USER() AS user,
743
+ (SELECT SUM(data_length + index_length) FROM information_schema.tables WHERE table_schema = DATABASE()) AS size,
744
+ @@hostname AS host, @@port AS port`);
745
+ const flavor = /mariadb/i.test(`${r.version} ${r.comment ?? ""}`) ? "MariaDB" : "MySQL";
746
+ return {
747
+ version: r.version,
748
+ flavor,
749
+ database: r.database ?? "",
750
+ user: r.user,
751
+ size: prettySize(Number(r.size ?? 0)),
752
+ host: r.host,
753
+ port: r.port ? Number(r.port) : null,
754
+ readonly: ctx.readonly
755
+ };
756
+ }
757
+ /** Databases on this server the current user can see. */
758
+ async function listDatabases(ctx) {
759
+ return (await queryObjects(ctx.pool, `SELECT s.schema_name AS name, t.size
760
+ FROM information_schema.schemata s
761
+ LEFT JOIN (SELECT table_schema, SUM(data_length + index_length) AS size
762
+ FROM information_schema.tables GROUP BY table_schema) t ON t.table_schema = s.schema_name
763
+ ORDER BY s.schema_name`)).map((r) => ({
764
+ name: r.name,
765
+ size: prettySize(Number(r.size ?? 0)),
766
+ system: SYSTEM_DATABASES.has(r.name.toLowerCase())
767
+ }));
768
+ }
769
+ async function listTables(ctx) {
770
+ return (await queryObjects(ctx.pool, `SELECT table_name AS name, table_type AS type FROM information_schema.tables
771
+ WHERE table_schema = ? ORDER BY table_name`, [ctx.database])).map((r) => ({
772
+ schema: ctx.database,
773
+ name: r.name,
774
+ kind: relKind(r.type)
775
+ }));
776
+ }
777
+ const relKind = (tableType) => /VIEW/i.test(tableType) ? "v" : "r";
778
+ const CATEGORY = {};
779
+ for (const t of "tinyint smallint mediumint int integer bigint decimal numeric float double real bit".split(" ")) CATEGORY[t] = "N";
780
+ for (const t of "char varchar tinytext text mediumtext longtext".split(" ")) CATEGORY[t] = "S";
781
+ for (const t of "date datetime timestamp time year".split(" ")) CATEGORY[t] = "D";
782
+ for (const t of "binary varbinary tinyblob blob mediumblob longblob".split(" ")) CATEGORY[t] = "B";
783
+ for (const t of "geometry point linestring polygon multipoint multilinestring multipolygon geometrycollection geomcollection".split(" ")) CATEGORY[t] = "G";
784
+ CATEGORY.enum = "E";
785
+ CATEGORY.set = "T";
786
+ CATEGORY.json = "J";
787
+ const typeCategory = (dataType) => CATEGORY[dataType.toLowerCase()] ?? "X";
788
+ /** enum('a','it''s') → ['a', "it's"] */
789
+ function parseEnumValues(columnType) {
790
+ const m = /^(?:enum|set)\((.*)\)$/is.exec(columnType.trim());
791
+ if (!m) return null;
792
+ const out = [];
793
+ const re = /'((?:[^'\\]|''|\\.)*)'/g;
794
+ let x;
795
+ while (x = re.exec(m[1])) out.push(x[1].replace(/''/g, "'").replace(/\\(.)/g, "$1"));
796
+ return out;
797
+ }
798
+ const NUMERIC_DEFAULT = /^-?\d+(\.\d+)?([eE][-+]?\d+)?$/;
799
+ /**
800
+ * information_schema.columns.column_default as a SQL expression that
801
+ * recreates it. MySQL stores literals unquoted and marks expressions with
802
+ * DEFAULT_GENERATED; MariaDB quotes literals itself.
803
+ */
804
+ function defaultSql(raw, extra, dataType, mariadb) {
805
+ if (raw === null) return null;
806
+ if (mariadb) return raw === "NULL" ? null : raw;
807
+ if (/DEFAULT_GENERATED/i.test(extra)) return /^current_timestamp(\(\d*\))?$/i.test(raw) ? raw : `(${raw})`;
808
+ const cat = typeCategory(dataType);
809
+ if (dataType === "bit") return /^b'/i.test(raw) ? raw : `b'${raw}'`;
810
+ if (cat === "N" && NUMERIC_DEFAULT.test(raw)) return raw;
811
+ return quoteLiteral$1(raw);
812
+ }
813
+ async function getColumns(ctx, schema, table) {
814
+ const [{ mariadb }, rows] = await Promise.all([serverFlavor(ctx), queryObjects(ctx.pool, `SELECT column_name AS name, column_type, data_type, is_nullable, column_default, extra,
815
+ character_set_name AS charset, collation_name AS collation, column_comment AS comment,
816
+ generation_expression AS generation
817
+ FROM information_schema.columns
818
+ WHERE table_schema = ? AND table_name = ?
819
+ ORDER BY ordinal_position`, [schema, table])]);
820
+ return rows.map((c) => {
821
+ const extra = c.extra ?? "";
822
+ const dataType = c.data_type.toLowerCase();
823
+ const generated = /GENERATED/i.test(extra) && !/DEFAULT_GENERATED/i.test(extra);
824
+ return {
825
+ name: c.name,
826
+ type: c.column_type,
827
+ typeName: dataType,
828
+ category: typeCategory(dataType),
829
+ enumValues: dataType === "enum" || dataType === "set" ? parseEnumValues(c.column_type) : null,
830
+ nullable: c.is_nullable === "YES",
831
+ default: generated ? null : defaultSql(c.column_default, extra, dataType, mariadb),
832
+ identity: /auto_increment/i.test(extra),
833
+ generated,
834
+ generation: generated ? c.generation || null : null,
835
+ extra,
836
+ charset: c.charset,
837
+ collation: c.collation,
838
+ comment: c.comment || null
839
+ };
840
+ });
841
+ }
842
+ async function getIndexes(ctx, schema, table) {
843
+ const { mariadb, version } = await serverFlavor(ctx);
844
+ const expr = !mariadb && version >= 80013 ? "expression" : "NULL";
845
+ const rows = await queryObjects(ctx.pool, `SELECT index_name AS name, non_unique, seq_in_index AS seq, column_name, sub_part, collation, index_type,
846
+ ${expr} AS expression
847
+ FROM information_schema.statistics
848
+ WHERE table_schema = ? AND table_name = ?
849
+ ORDER BY index_name = 'PRIMARY' DESC, index_name, seq_in_index`, [schema, table]);
850
+ const byName = /* @__PURE__ */ new Map();
851
+ for (const r of rows) (byName.get(r.name) ?? byName.set(r.name, []).get(r.name)).push(r);
852
+ return [...byName.entries()].map(([name, parts]) => {
853
+ const first = parts[0];
854
+ const primary = name === "PRIMARY";
855
+ const unique = first.non_unique === "0";
856
+ const method = first.index_type.toUpperCase();
857
+ const keyParts = parts.map((p) => {
858
+ return `${p.column_name ? quoteIdent$3(p.column_name) : `(${p.expression ?? "?"})`}${p.sub_part ? `(${p.sub_part})` : ""}${p.collation === "D" ? " DESC" : ""}`;
859
+ });
860
+ return {
861
+ name,
862
+ definition: primary ? `ALTER TABLE ${qualified(schema, table)} ADD PRIMARY KEY (${keyParts.join(", ")})` : `CREATE ${method === "FULLTEXT" ? "FULLTEXT " : method === "SPATIAL" ? "SPATIAL " : unique ? "UNIQUE " : ""}INDEX ${quoteIdent$3(name)} ON ${qualified(schema, table)} (${keyParts.join(", ")})${method === "HASH" ? " USING HASH" : ""}`,
863
+ unique,
864
+ primary,
865
+ method,
866
+ columns: parts.map((p) => p.column_name ?? `(${p.expression ?? "?"})`)
867
+ };
868
+ });
869
+ }
870
+ const FK_SELECT = `
871
+ SELECT k.constraint_name AS name, k.table_schema AS \`schema\`, k.table_name AS \`table\`, k.column_name AS \`column\`,
872
+ k.referenced_table_schema AS ref_schema, k.referenced_table_name AS ref_table, k.referenced_column_name AS ref_column,
873
+ r.delete_rule AS on_delete, r.update_rule AS on_update
874
+ FROM information_schema.key_column_usage k
875
+ LEFT JOIN information_schema.referential_constraints r
876
+ ON r.constraint_schema = k.constraint_schema AND r.constraint_name = k.constraint_name AND r.table_name = k.table_name
877
+ WHERE k.referenced_table_name IS NOT NULL`;
878
+ /** Group key_column_usage rows (one per column) into one entry per constraint. */
879
+ function groupFks(rows) {
880
+ const map = /* @__PURE__ */ new Map();
881
+ for (const r of rows) {
882
+ const key = `${r.schema}.${r.table}.${r.name}`;
883
+ let fk = map.get(key);
884
+ if (!fk) map.set(key, fk = {
885
+ ...r,
886
+ columns: [],
887
+ refColumns: []
888
+ });
889
+ fk.columns.push(r.column);
890
+ fk.refColumns.push(r.ref_column);
891
+ }
892
+ return [...map.values()];
893
+ }
894
+ async function getForeignKeys(ctx, schema, table) {
895
+ return groupFks(await queryObjects(ctx.pool, `${FK_SELECT} AND k.table_schema = ? AND k.table_name = ? ORDER BY k.constraint_name, k.ordinal_position`, [schema, table])).map((f) => ({
896
+ name: f.name,
897
+ columns: f.columns,
898
+ refSchema: f.ref_schema,
899
+ refTable: f.ref_table,
900
+ refColumns: f.refColumns,
901
+ onDelete: f.on_delete ?? "NO ACTION",
902
+ onUpdate: f.on_update ?? "NO ACTION"
903
+ }));
904
+ }
905
+ async function getTableMeta(ctx, schema, table) {
906
+ const [rel] = await queryObjects(ctx.pool, `SELECT table_type AS type, table_rows AS \`rows\`, data_length + index_length AS size, engine,
907
+ table_collation AS collation, table_comment AS comment
908
+ FROM information_schema.tables WHERE table_schema = ? AND table_name = ?`, [schema, table]);
909
+ if (!rel) throw new UserError(`Table ${schema}.${table} not found`, 404);
910
+ const kind = relKind(rel.type);
911
+ const { mariadb, version } = await serverFlavor(ctx);
912
+ const hasChecks = mariadb || version >= 80016;
913
+ const [columns, indexes, foreignKeys, incoming, tableCons, checks] = await Promise.all([
914
+ getColumns(ctx, schema, table),
915
+ kind === "r" ? getIndexes(ctx, schema, table) : Promise.resolve([]),
916
+ kind === "r" ? getForeignKeys(ctx, schema, table) : Promise.resolve([]),
917
+ queryObjects(ctx.pool, `${FK_SELECT} AND k.referenced_table_schema = ? AND k.referenced_table_name = ?
918
+ ORDER BY k.table_schema, k.table_name, k.constraint_name, k.ordinal_position`, [schema, table]),
919
+ queryObjects(ctx.pool, `SELECT constraint_name AS name, constraint_type AS type FROM information_schema.table_constraints
920
+ WHERE table_schema = ? AND table_name = ?`, [schema, table]),
921
+ hasChecks ? queryObjects(ctx.pool, `SELECT c.constraint_name AS name, c.check_clause AS clause
922
+ FROM information_schema.check_constraints c
923
+ JOIN information_schema.table_constraints t
924
+ ON t.constraint_schema = c.constraint_schema AND t.constraint_name = c.constraint_name
925
+ WHERE t.table_schema = ? AND t.table_name = ? AND t.constraint_type = 'CHECK'`, [schema, table]).catch(() => []) : Promise.resolve([])
926
+ ]);
927
+ const referencedBy = groupFks(incoming).map((f) => ({
928
+ name: f.name,
929
+ schema: f.schema,
930
+ table: f.table,
931
+ columns: f.columns,
932
+ refColumns: f.refColumns
933
+ }));
934
+ const cols = (names) => names.map(quoteIdent$3).join(", ");
935
+ const constraints = [];
936
+ const order = {
937
+ "PRIMARY KEY": 0,
938
+ UNIQUE: 1,
939
+ "FOREIGN KEY": 2,
940
+ CHECK: 3
941
+ };
942
+ for (const c of [...tableCons].sort((a, b) => (order[a.type] ?? 9) - (order[b.type] ?? 9) || a.name.localeCompare(b.name))) if (c.type === "PRIMARY KEY" || c.type === "UNIQUE") {
943
+ const idx = indexes.find((i) => i.name === c.name);
944
+ constraints.push({
945
+ name: c.name,
946
+ type: c.type === "UNIQUE" ? "u" : "p",
947
+ definition: `${c.type} (${cols(idx?.columns ?? [])})`
948
+ });
949
+ } else if (c.type === "FOREIGN KEY") {
950
+ const fk = foreignKeys.find((f) => f.name === c.name);
951
+ if (!fk) continue;
952
+ let def = `FOREIGN KEY (${cols(fk.columns)}) REFERENCES ${fk.refSchema === schema ? "" : `${quoteIdent$3(fk.refSchema)}.`}${quoteIdent$3(fk.refTable)} (${cols(fk.refColumns)})`;
953
+ if (fk.onDelete !== "NO ACTION" && fk.onDelete !== "RESTRICT") def += ` ON DELETE ${fk.onDelete}`;
954
+ if (fk.onUpdate !== "NO ACTION" && fk.onUpdate !== "RESTRICT") def += ` ON UPDATE ${fk.onUpdate}`;
955
+ constraints.push({
956
+ name: c.name,
957
+ type: "f",
958
+ definition: def
959
+ });
960
+ } else if (c.type === "CHECK") {
961
+ const ch = checks.find((x) => x.name === c.name);
962
+ constraints.push({
963
+ name: c.name,
964
+ type: "c",
965
+ definition: `CHECK (${ch?.clause ?? "?"})`
966
+ });
967
+ }
968
+ const primaryKey = indexes.find((i) => i.primary)?.columns ?? [];
969
+ const notNull = new Set(columns.filter((c) => !c.nullable).map((c) => c.name));
970
+ const uniqueKey = primaryKey.length ? null : indexes.find((i) => i.unique && i.method !== "FULLTEXT" && i.columns.every((c) => notNull.has(c)) && !/`\(\d+\)/.test(i.definition));
971
+ const keyMode = kind !== "r" ? null : primaryKey.length ? "pk" : uniqueKey ? "unique" : null;
972
+ const keyColumns = keyMode === "pk" ? primaryKey : uniqueKey?.columns ?? [];
973
+ return {
974
+ schema,
975
+ table,
976
+ kind,
977
+ estimate: rel.rows === null ? -1 : Number(rel.rows),
978
+ size: prettySize(Number(rel.size ?? 0)),
979
+ engine: rel.engine,
980
+ collation: rel.collation,
981
+ comment: rel.comment || null,
982
+ columns,
983
+ primaryKey,
984
+ keyMode,
985
+ keyColumns,
986
+ editable: !ctx.readonly && kind === "r" && keyMode !== null,
987
+ indexes,
988
+ constraints,
989
+ foreignKeys,
990
+ referencedBy
991
+ };
992
+ }
993
+ // src/db/values.ts
994
+ const HEX = /^0x([0-9a-f]*)$/i;
995
+ /**
996
+ * How a value from the UI goes into a statement for a given column: the
997
+ * placeholder SQL and its parameter. Values arrive as MySQL's own text
998
+ * rendering, so most go in as strings and MySQL converts them; binary data
999
+ * (shown as 0x…) and BIT (shown as a number) need a little help.
1000
+ */
1001
+ function valueSql(col, v) {
1002
+ if (v === null || !col) return {
1003
+ sql: "?",
1004
+ param: v
1005
+ };
1006
+ if (col.typeName === "bit") return {
1007
+ sql: "CAST(? AS UNSIGNED)",
1008
+ param: v.trim()
1009
+ };
1010
+ if (col.category === "B") {
1011
+ const m = HEX.exec(v.trim());
1012
+ return {
1013
+ sql: "?",
1014
+ param: m ? Buffer.from(m[1].length % 2 ? `0${m[1]}` : m[1], "hex") : v
1015
+ };
1016
+ }
1017
+ if (col.category === "G") {
1018
+ const m = HEX.exec(v.trim());
1019
+ return m ? {
1020
+ sql: "?",
1021
+ param: Buffer.from(m[1], "hex")
1022
+ } : {
1023
+ sql: "ST_GeomFromText(?)",
1024
+ param: v
1025
+ };
1026
+ }
1027
+ return {
1028
+ sql: "?",
1029
+ param: v
1030
+ };
1031
+ }
1032
+ // src/db/rows.ts
1033
+ /** Above this row estimate an unfiltered COUNT(*) is skipped as too slow. */
1034
+ const EXACT_COUNT_THRESHOLD = 5e4;
1035
+ const READONLY_MESSAGE = "mysqldeck is running in --readonly mode";
1036
+ function assertColumns(meta, names) {
1037
+ const known = new Set(meta.columns.map((c) => c.name));
1038
+ for (const name of names) if (!known.has(name)) throw new UserError(`Unknown column "${name}" on ${meta.schema}.${meta.table}`);
1039
+ }
1040
+ function assertWritable(ctx, meta) {
1041
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
1042
+ if (!meta.editable) throw new UserError(`${meta.schema}.${meta.table} has no primary key (or unique NOT NULL key) or is a view, so it cannot be edited here`);
1043
+ }
1044
+ function buildWhere(meta, filters, match, values) {
1045
+ assertColumns(meta, filters.map((f) => f.col));
1046
+ const parts = filters.map((f) => {
1047
+ const toSql = FILTER_SQL[f.op];
1048
+ const col = quoteIdent$3(f.col);
1049
+ if (isUnaryOp(f.op)) return toSql(col, "");
1050
+ if (isListOp(f.op)) {
1051
+ const list = splitList(f.val ?? "");
1052
+ if (!list.length) return f.op === "in" ? "FALSE" : "TRUE";
1053
+ values.push(list);
1054
+ return toSql(col, "?");
1055
+ }
1056
+ values.push(f.val ?? "");
1057
+ return toSql(col, "?");
1058
+ });
1059
+ if (!parts.length) return "";
1060
+ return ` WHERE ${parts.map((p) => `(${p})`).join(match === "or" ? " OR " : " AND ")}`;
1061
+ }
1062
+ function buildKeyWhere(meta, key, values) {
1063
+ if (!meta.keyMode) throw new UserError("This table has no key; rows cannot be addressed");
1064
+ const byName = new Map(meta.columns.map((c) => [c.name, c]));
1065
+ return meta.keyColumns.map((col) => {
1066
+ if (!(col in key)) throw new UserError(`Missing key column "${col}"`);
1067
+ const v = valueSql(byName.get(col), key[col] ?? null);
1068
+ values.push(v.param);
1069
+ return `${quoteIdent$3(col)} <=> ${v.sql}`;
1070
+ }).join(" AND ");
1071
+ }
1072
+ /** WHERE (with its parameters) and ORDER BY for a filtered/sorted read of a table. */
1073
+ function buildQueryParts(meta, req) {
1074
+ const values = [];
1075
+ const where = buildWhere(meta, req.filters ?? [], req.match ?? "and", values);
1076
+ let orderBy = "";
1077
+ if (req.sort) {
1078
+ assertColumns(meta, [req.sort]);
1079
+ const col = quoteIdent$3(req.sort);
1080
+ orderBy = ` ORDER BY ${col} IS NULL, ${col} ${req.dir === "desc" ? "DESC" : "ASC"}`;
1081
+ } else if (meta.keyColumns.length) orderBy = ` ORDER BY ${meta.keyColumns.map(quoteIdent$3).join(", ")}`;
1082
+ return {
1083
+ where,
1084
+ values,
1085
+ orderBy
1086
+ };
1087
+ }
1088
+ async function selectRows(ctx, req) {
1089
+ const meta = await getTableMeta(ctx, req.schema, req.table);
1090
+ const limit = Math.min(Math.max(req.limit, 1), ctx.maxRows);
1091
+ const offset = Math.max(req.offset, 0);
1092
+ const rel = qualified(req.schema, req.table);
1093
+ const { where, values, orderBy } = buildQueryParts(meta, req);
1094
+ const select = `SELECT * FROM ${rel}${where}${orderBy} LIMIT ${limit} OFFSET ${offset}`;
1095
+ const countPromise = !where && meta.kind === "r" && meta.estimate > EXACT_COUNT_THRESHOLD ? Promise.resolve({
1096
+ total: meta.estimate,
1097
+ totalExact: false
1098
+ }) : queryRaw(ctx.pool, `SELECT COUNT(*) FROM ${rel}${where}`, values).then((r) => ({
1099
+ total: Number(r.rows[0][0]),
1100
+ totalExact: true
1101
+ }));
1102
+ const [result, count] = await Promise.all([queryRaw(ctx.pool, select, values), countPromise]);
1103
+ return {
1104
+ fields: result.fields,
1105
+ rows: result.rows,
1106
+ ...count,
1107
+ limit,
1108
+ offset
1109
+ };
1110
+ }
1111
+ async function insertRow(ctx, schema, table, row) {
1112
+ const meta = await getTableMeta(ctx, schema, table);
1113
+ assertWritable(ctx, meta);
1114
+ const names = Object.keys(row);
1115
+ assertColumns(meta, names);
1116
+ const byName = new Map(meta.columns.map((c) => [c.name, c]));
1117
+ const parts = names.map((n) => valueSql(byName.get(n), row[n] ?? null));
1118
+ const rel = qualified(schema, table);
1119
+ const sql = names.length ? `INSERT INTO ${rel} (${names.map(quoteIdent$3).join(", ")}) VALUES (${parts.map((p) => p.sql).join(", ")})` : `INSERT INTO ${rel} () VALUES ()`;
1120
+ return { rowCount: (await exec(ctx.pool, sql, parts.map((p) => p.param))).affectedRows };
1121
+ }
1122
+ async function updateRow(ctx, schema, table, key, changes) {
1123
+ const meta = await getTableMeta(ctx, schema, table);
1124
+ assertWritable(ctx, meta);
1125
+ const names = Object.keys(changes);
1126
+ if (!names.length) return { rowCount: 0 };
1127
+ assertColumns(meta, names);
1128
+ const byName = new Map(meta.columns.map((c) => [c.name, c]));
1129
+ const values = [];
1130
+ const set = names.map((n) => {
1131
+ const v = valueSql(byName.get(n), changes[n] ?? null);
1132
+ values.push(v.param);
1133
+ return `${quoteIdent$3(n)} = ${v.sql}`;
1134
+ }).join(", ");
1135
+ const where = buildKeyWhere(meta, key, values);
1136
+ return withTransaction(ctx.pool, async (conn) => {
1137
+ const result = await exec(conn, `UPDATE ${qualified(schema, table)} SET ${set} WHERE ${where}`, values);
1138
+ if (result.affectedRows !== 1) throw new UserError(`Expected to update 1 row but matched ${result.affectedRows}. Nothing was changed.`, 409);
1139
+ return { rowCount: 1 };
1140
+ });
1141
+ }
1142
+ async function deleteRows(ctx, schema, table, keys) {
1143
+ const meta = await getTableMeta(ctx, schema, table);
1144
+ assertWritable(ctx, meta);
1145
+ const rel = qualified(schema, table);
1146
+ return withTransaction(ctx.pool, async (conn) => {
1147
+ let rowCount = 0;
1148
+ for (const key of keys) {
1149
+ const values = [];
1150
+ const where = buildKeyWhere(meta, key, values);
1151
+ const result = await exec(conn, `DELETE FROM ${rel} WHERE ${where} LIMIT 2`, values);
1152
+ if (result.affectedRows > 1) throw new UserError(`A key matched ${result.affectedRows} rows. Nothing was deleted.`, 409);
1153
+ rowCount += result.affectedRows;
1154
+ }
1155
+ return { rowCount };
1156
+ });
1157
+ }
1158
+ // src/shared/create-table.ts
1159
+ /**
1160
+ * Builds CREATE TABLE statements from a structured spec. Shared so the UI can
1161
+ * preview exactly the SQL the server will run.
1162
+ */
1163
+ /** InnoDB doesn't support SET DEFAULT. */
1164
+ const FK_ACTIONS = [
1165
+ "NO ACTION",
1166
+ "RESTRICT",
1167
+ "CASCADE",
1168
+ "SET NULL"
1169
+ ];
1170
+ const quoteIdent$2 = (name) => `\`${name.replace(/`/g, "``")}\``;
1171
+ /** A string literal for the default sql_mode (backslash escapes on). */
1172
+ const quoteLiteral = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
1173
+ const QUOTED = `'(?:[^'\\\\]|''|\\\\.)*'`;
1174
+ const ENUM_RE = new RegExp(`^(enum|set)\\s*\\(\\s*${QUOTED}(\\s*,\\s*${QUOTED})*\\s*\\)$`, "i");
1175
+ /** Words, (n[,m]) modifiers and trailing words (unsigned, zerofill, character set x): no room for injection. */
1176
+ const TYPE_RE = /^[A-Za-z_][\w ]*(\(\s*\d+\s*(,\s*\d+\s*)?\))?[\w ]*$/;
1177
+ const isValidType = (t) => {
1178
+ const s = t.trim();
1179
+ return s.length > 0 && s.length <= 4096 && (TYPE_RE.test(s) ? s.length <= 128 : ENUM_RE.test(s));
1180
+ };
1181
+ const INTEGER_RE = /^(tinyint|smallint|mediumint|int|integer|bigint)(\s*\(\s*\d+\s*\))?(\s+unsigned)?(\s+zerofill)?$/i;
1182
+ const isIntegerType = (t) => INTEGER_RE.test(t.trim());
1183
+ /** TEXT and BLOB columns can only be indexed on a prefix. */
1184
+ const needsPrefixLength = (t) => /^(tiny|medium|long)?(text|blob)\b/i.test(t.trim());
1185
+ /** Problems that would make the statement fail, in UI-friendly words. Empty when valid. */
1186
+ function validateColumn(c, label) {
1187
+ const errors = [];
1188
+ if (!c.name.trim()) errors.push(`${label}: needs a name.`);
1189
+ if (c.name.length > 64) errors.push(`${label}: names are limited to 64 characters.`);
1190
+ if (/\s$/.test(c.name)) errors.push(`${label}: names can't end with a space.`);
1191
+ if (!isValidType(c.type)) errors.push(`${label}: "${c.type}" is not a valid type.`);
1192
+ if (c.identity && !isIntegerType(c.type)) errors.push(`${label}: auto-increment needs an integer type.`);
1193
+ if (c.identity && c.default.trim()) errors.push(`${label}: auto-increment columns can't have a default.`);
1194
+ if (c.identity && !c.primaryKey && !c.unique) errors.push(`${label}: an auto-increment column must be a key (primary or unique).`);
1195
+ if ((c.primaryKey || c.unique) && needsPrefixLength(c.type)) errors.push(`${label}: TEXT and BLOB columns can't be a key; use varchar or varbinary.`);
1196
+ if (c.references && (!c.references.table || !c.references.column)) errors.push(`${label}: pick the referenced table and column.`);
1197
+ return errors;
1198
+ }
1199
+ function validateTable(t) {
1200
+ const errors = [];
1201
+ if (!t.name.trim()) errors.push("Give the table a name.");
1202
+ if (t.name.length > 64) errors.push("Table names are limited to 64 characters.");
1203
+ if (!t.columns.length) errors.push("Add at least one column.");
1204
+ if (t.columns.filter((c) => c.identity).length > 1) errors.push("A table can have only one auto-increment column.");
1205
+ const seen = /* @__PURE__ */ new Set();
1206
+ t.columns.forEach((c, i) => {
1207
+ const label = c.name.trim() || `Column ${i + 1}`;
1208
+ if (c.name.trim() && seen.has(c.name.toLowerCase())) errors.push(`${label}: duplicate column name.`);
1209
+ seen.add(c.name.toLowerCase());
1210
+ errors.push(...validateColumn(c, label));
1211
+ });
1212
+ return errors;
1213
+ }
1214
+ /** `name type [NOT NULL] [DEFAULT …] [AUTO_INCREMENT] [PRIMARY KEY|UNIQUE] [COMMENT …]` for CREATE / ADD COLUMN. */
1215
+ function columnDefinition(c, inlinePrimaryKey) {
1216
+ let line = `${quoteIdent$2(c.name)} ${c.type.trim()}`;
1217
+ if (!c.nullable || inlinePrimaryKey) line += " NOT NULL";
1218
+ if (c.default.trim() && !c.identity) line += ` DEFAULT ${c.default.trim()}`;
1219
+ if (c.identity) line += " AUTO_INCREMENT";
1220
+ if (inlinePrimaryKey) line += " PRIMARY KEY";
1221
+ else if (c.unique && !c.primaryKey) line += " UNIQUE";
1222
+ if (c.comment.trim()) line += ` COMMENT ${quoteLiteral(c.comment.trim())}`;
1223
+ return line;
1224
+ }
1225
+ function foreignKeyClause(column, r, sameSchema) {
1226
+ const target = r.schema === sameSchema ? quoteIdent$2(r.table) : `${quoteIdent$2(r.schema)}.${quoteIdent$2(r.table)}`;
1227
+ let line = `FOREIGN KEY (${quoteIdent$2(column)}) REFERENCES ${target} (${quoteIdent$2(r.column)})`;
1228
+ if (r.onDelete !== "NO ACTION") line += ` ON DELETE ${r.onDelete}`;
1229
+ if (r.onUpdate !== "NO ACTION") line += ` ON UPDATE ${r.onUpdate}`;
1230
+ return line;
1231
+ }
1232
+ /** The CREATE TABLE statement for a spec. Call validateTable first. */
1233
+ function createTableSql(t) {
1234
+ const table = `${quoteIdent$2(t.schema)}.${quoteIdent$2(t.name)}`;
1235
+ const pk = t.columns.filter((c) => c.primaryKey);
1236
+ const lines = [];
1237
+ for (const c of t.columns) lines.push(columnDefinition(c, pk.length === 1 && c.primaryKey));
1238
+ if (pk.length > 1) lines.push(`PRIMARY KEY (${pk.map((c) => quoteIdent$2(c.name)).join(", ")})`);
1239
+ for (const c of t.columns) if (c.references) lines.push(foreignKeyClause(c.name, c.references, t.schema));
1240
+ const options = [];
1241
+ if (t.engine.trim()) options.push(`ENGINE=${t.engine.trim().replace(/\W/g, "")}`);
1242
+ if (t.collation.trim()) options.push(`COLLATE=${t.collation.trim().replace(/\W/g, "")}`);
1243
+ if (t.comment.trim()) options.push(`COMMENT=${quoteLiteral(t.comment.trim())}`);
1244
+ return `CREATE TABLE ${table} (\n ${lines.join(",\n ")}\n)${options.length ? ` ${options.join(" ")}` : ""};\n`;
1245
+ }
1246
+ // src/shared/alter.ts
1247
+ const INDEX_METHODS = [
1248
+ "btree",
1249
+ "hash",
1250
+ "fulltext",
1251
+ "spatial"
1252
+ ];
1253
+ function validateAlter(a) {
1254
+ switch (a.action) {
1255
+ case "addColumn": return validateColumn(a.column, "Column");
1256
+ case "alterColumn": {
1257
+ const e = [];
1258
+ if (a.newName !== void 0 && !a.newName.trim()) e.push("The column needs a name.");
1259
+ if (a.newName && a.newName.length > 64) e.push("Names are limited to 64 characters.");
1260
+ if (a.type !== void 0 && !isValidType(a.type)) e.push(`"${a.type}" is not a valid type.`);
1261
+ return e;
1262
+ }
1263
+ case "createIndex": {
1264
+ const e = [];
1265
+ if (!a.columns.length) e.push("Pick at least one column.");
1266
+ if (a.name.length > 64) e.push("Names are limited to 64 characters.");
1267
+ if (a.unique && (a.method === "fulltext" || a.method === "spatial")) e.push(`${a.method === "fulltext" ? "Full-text" : "Spatial"} indexes can't be unique.`);
1268
+ if (a.method === "spatial" && a.columns.length !== 1) e.push("A spatial index covers exactly one column.");
1269
+ return e;
1270
+ }
1271
+ default: return [];
1272
+ }
1273
+ }
1274
+ /**
1275
+ * The full column definition MODIFY / CHANGE COLUMN needs: MySQL replaces the
1276
+ * whole definition, so everything not being changed is carried over from the
1277
+ * current column (charset, collation, default, ON UPDATE, AUTO_INCREMENT,
1278
+ * generated expression, visibility and comment).
1279
+ */
1280
+ /** Types that carry a character set: char, varchar, the text types, enum and set. */
1281
+ const TEXT_TYPE = /^\s*((var)?char|(tiny|medium|long)?text|enum|set)\b/i;
1282
+ function changedColumnDefinition(current, change) {
1283
+ const type = change.type?.trim() || current.type;
1284
+ const typeChanged = change.type !== void 0 && change.type.trim().toLowerCase() !== current.type.toLowerCase();
1285
+ let def = type;
1286
+ if ((typeChanged ? TEXT_TYPE.test(type) && !/\b(character\s+set|charset|collate)\b/i.test(type) : true) && current.collation && TEXT_TYPE.test(current.type)) def += ` CHARACTER SET ${current.charset} COLLATE ${current.collation}`;
1287
+ if (current.generated && current.generation) def += ` GENERATED ALWAYS AS (${current.generation}) ${/STORED/i.test(current.extra) ? "STORED" : "VIRTUAL"}`;
1288
+ const nullable = change.nullable ?? current.nullable;
1289
+ def += nullable ? " NULL" : " NOT NULL";
1290
+ const dflt = change.default !== void 0 ? change.default : current.default;
1291
+ if (dflt?.trim() && !current.identity && !current.generated) def += ` DEFAULT ${dflt.trim()}`;
1292
+ const onUpdate = /on update (current_timestamp(\(\d*\))?)/i.exec(current.extra);
1293
+ if (onUpdate) def += ` ON UPDATE ${onUpdate[1].toUpperCase()}`;
1294
+ if (current.identity) def += " AUTO_INCREMENT";
1295
+ if (/\bINVISIBLE\b/i.test(current.extra)) def += " INVISIBLE";
1296
+ const comment = change.comment !== void 0 ? change.comment : current.comment;
1297
+ if (comment?.trim()) def += ` COMMENT ${quoteLiteral(comment.trim())}`;
1298
+ return def;
1299
+ }
1300
+ /**
1301
+ * The statements for one change, in the order they must run. `columns` is
1302
+ * the table's current columns (needed to rebuild a changed column's definition).
1303
+ */
1304
+ function alterSql(schema, table, a, columns = []) {
1305
+ const rel = `${quoteIdent$2(schema)}.${quoteIdent$2(table)}`;
1306
+ const alter = (clause) => `ALTER TABLE ${rel} ${clause};`;
1307
+ switch (a.action) {
1308
+ case "addColumn": {
1309
+ const c = a.column;
1310
+ const clauses = [`ADD COLUMN ${columnDefinition(c, c.primaryKey)}`];
1311
+ if (c.references) clauses.push(`ADD ${foreignKeyClause(c.name, c.references, schema)}`);
1312
+ return [`ALTER TABLE ${rel}\n ${clauses.join(",\n ")};`];
1313
+ }
1314
+ case "alterColumn": {
1315
+ const current = columns.find((c) => c.name === a.column);
1316
+ if (!current) throw new Error(`Unknown column "${a.column}"`);
1317
+ const newName = a.newName?.trim() || a.column;
1318
+ return [alter(`CHANGE COLUMN ${quoteIdent$2(a.column)} ${quoteIdent$2(newName)} ${changedColumnDefinition(current, a)}`)];
1319
+ }
1320
+ case "dropColumn": return [alter(`DROP COLUMN ${quoteIdent$2(a.column)}`)];
1321
+ case "createIndex": {
1322
+ const plain = a.method === "btree" || a.method === "hash";
1323
+ const cols = a.columns.map((c) => {
1324
+ const col = columns.find((x) => x.name === c.name);
1325
+ const length = c.length ?? (plain && col && needsPrefixLength(col.type) ? 191 : null);
1326
+ return `${quoteIdent$2(c.name)}${length ? `(${Math.trunc(length)})` : ""}${c.desc && plain ? " DESC" : ""}`;
1327
+ }).join(", ");
1328
+ const kind = a.method === "fulltext" ? "FULLTEXT " : a.method === "spatial" ? "SPATIAL " : a.unique ? "UNIQUE " : "";
1329
+ const using = a.method === "hash" ? " USING HASH" : "";
1330
+ return [alter(`ADD ${kind}INDEX ${a.name.trim() ? `${quoteIdent$2(a.name.trim())} ` : ""}(${cols})${using}${a.online ? ", ALGORITHM=INPLACE, LOCK=NONE" : ""}`)];
1331
+ }
1332
+ case "dropIndex": return [alter(a.name === "PRIMARY" ? "DROP PRIMARY KEY" : `DROP INDEX ${quoteIdent$2(a.name)}`)];
1333
+ case "dropConstraint": switch (a.type) {
1334
+ case "p": return [alter("DROP PRIMARY KEY")];
1335
+ case "f": return [alter(`DROP FOREIGN KEY ${quoteIdent$2(a.name)}`)];
1336
+ case "u": return [alter(`DROP INDEX ${quoteIdent$2(a.name)}`)];
1337
+ default: return [alter(`DROP CHECK ${quoteIdent$2(a.name)}`)];
1338
+ }
1339
+ }
1340
+ }
1341
+ // src/db/create-table.ts
1342
+ async function createTable(ctx, spec) {
1343
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
1344
+ const errors = validateTable(spec);
1345
+ if (errors.length) throw new UserError(errors.join(" "));
1346
+ await exec(ctx.pool, createTableSql(spec));
1347
+ return {
1348
+ ok: true,
1349
+ message: `Created ${spec.name}`
1350
+ };
1351
+ }
1352
+ async function getCatalog(ctx) {
1353
+ const [engines, collations, dflt] = await Promise.all([
1354
+ queryObjects(ctx.pool, `SELECT engine AS name FROM information_schema.engines WHERE support IN ('YES', 'DEFAULT') ORDER BY support = 'DEFAULT' DESC, engine`),
1355
+ queryObjects(ctx.pool, `SELECT collation_name AS name FROM information_schema.collations
1356
+ WHERE character_set_name IN ('utf8mb4', 'utf8mb3', 'latin1', 'ascii', 'binary') ORDER BY character_set_name = 'utf8mb4' DESC, collation_name`),
1357
+ queryObjects(ctx.pool, "SELECT @@collation_database AS c")
1358
+ ]);
1359
+ return {
1360
+ schemas: [ctx.database],
1361
+ types: [],
1362
+ engines: engines.map((e) => e.name),
1363
+ collations: collations.map((c) => c.name),
1364
+ defaultCollation: dflt[0]?.c ?? ""
1365
+ };
1366
+ }
1367
+ /** Apply one Structure-tab change (columns, indexes, constraints). */
1368
+ async function alterTable(ctx, schema, table, a) {
1369
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
1370
+ const errors = validateAlter(a);
1371
+ if (errors.length) throw new UserError(errors.join(" "));
1372
+ const columns = await getColumns(ctx, schema, table);
1373
+ if (a.action === "alterColumn" && !columns.some((c) => c.name === a.column)) throw new UserError(`Unknown column "${a.column}"`, 404);
1374
+ const statements = alterSql(schema, table, a, columns);
1375
+ for (const s of statements) await exec(ctx.pool, s);
1376
+ return {
1377
+ ok: true,
1378
+ message: ALTER_DONE[a.action]
1379
+ };
1380
+ }
1381
+ const ALTER_DONE = {
1382
+ addColumn: "Column added",
1383
+ alterColumn: "Column updated",
1384
+ dropColumn: "Column dropped",
1385
+ createIndex: "Index created",
1386
+ dropIndex: "Index dropped",
1387
+ dropConstraint: "Constraint dropped"
1388
+ };
1389
+ // src/shared/export.ts
1390
+ const EXPORT_FORMATS = [
1391
+ "csv",
1392
+ "csv-excel",
1393
+ "tsv",
1394
+ "json",
1395
+ "ndjson",
1396
+ "sql",
1397
+ "markdown"
1398
+ ];
1399
+ const EXPORT_META = {
1400
+ csv: {
1401
+ label: "CSV",
1402
+ ext: "csv",
1403
+ mime: "text/csv",
1404
+ hint: "Comma-separated, RFC 4180"
1405
+ },
1406
+ "csv-excel": {
1407
+ label: "CSV for Excel",
1408
+ ext: "csv",
1409
+ mime: "text/csv",
1410
+ hint: "UTF-8 with BOM, CRLF line endings"
1411
+ },
1412
+ tsv: {
1413
+ label: "TSV",
1414
+ ext: "tsv",
1415
+ mime: "text/tab-separated-values",
1416
+ hint: "LOAD DATA format, NULL as \\N"
1417
+ },
1418
+ json: {
1419
+ label: "JSON",
1420
+ ext: "json",
1421
+ mime: "application/json",
1422
+ hint: "Array of objects, typed values"
1423
+ },
1424
+ ndjson: {
1425
+ label: "JSON Lines",
1426
+ ext: "ndjson",
1427
+ mime: "application/x-ndjson",
1428
+ hint: "One object per line"
1429
+ },
1430
+ sql: {
1431
+ label: "SQL INSERT",
1432
+ ext: "sql",
1433
+ mime: "application/sql",
1434
+ hint: "INSERT statements for this table"
1435
+ },
1436
+ markdown: {
1437
+ label: "Markdown",
1438
+ ext: "md",
1439
+ mime: "text/markdown",
1440
+ hint: "Table for docs and issues"
1441
+ }
1442
+ };
1443
+ const quoteIdent$1 = (s) => `\`${s.replace(/`/g, "``")}\``;
1444
+ const NUMERIC = /* @__PURE__ */ new Set([
1445
+ "tinyint",
1446
+ "smallint",
1447
+ "mediumint",
1448
+ "int",
1449
+ "integer",
1450
+ "bigint",
1451
+ "decimal",
1452
+ "numeric",
1453
+ "float",
1454
+ "double",
1455
+ "real",
1456
+ "bit",
1457
+ "year"
1458
+ ]);
1459
+ /** Shown as 0x… hex by mysqldeck; written back as a hex literal. */
1460
+ const BINARY = /* @__PURE__ */ new Set([
1461
+ "binary",
1462
+ "varbinary",
1463
+ "tinyblob",
1464
+ "blob",
1465
+ "mediumblob",
1466
+ "longblob",
1467
+ "geometry",
1468
+ "point",
1469
+ "linestring",
1470
+ "polygon",
1471
+ "multipoint",
1472
+ "multilinestring",
1473
+ "multipolygon",
1474
+ "geometrycollection",
1475
+ "geomcollection"
1476
+ ]);
1477
+ /** Raw MySQL text → a JSON value, without losing precision. */
1478
+ function typed(v, typeName) {
1479
+ if (v === null) return null;
1480
+ if (typeName === "json") try {
1481
+ return JSON.parse(v);
1482
+ } catch {
1483
+ return v;
1484
+ }
1485
+ if (typeName && NUMERIC.has(typeName)) {
1486
+ const n = Number(v);
1487
+ return Number.isFinite(n) && String(n) === v ? n : v;
1488
+ }
1489
+ return v;
1490
+ }
1491
+ /** A MySQL literal for a value (default sql_mode: backslashes escape). */
1492
+ function sqlLiteral(v, typeName) {
1493
+ if (v === null) return "NULL";
1494
+ if (typeName && NUMERIC.has(typeName) && /^-?\d+(\.\d+)?([eE][-+]?\d+)?$/.test(v)) return v;
1495
+ if (typeName && BINARY.has(typeName) && /^0x[0-9a-f]*$/i.test(v)) return v === "0x" ? "''" : v;
1496
+ return `'${v.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\0/g, "\\0")}'`;
1497
+ }
1498
+ const csvCell = (v, sep) => {
1499
+ if (v === null) return "";
1500
+ return v === "" || v.includes(sep) || /["\r\n]/.test(v) ? `"${v.replace(/"/g, "\"\"")}"` : v;
1501
+ };
1502
+ /** LOAD DATA / SELECT … INTO OUTFILE text format escaping. */
1503
+ const tsvCell = (v) => v === null ? "\\N" : v.replace(/\\/g, "\\\\").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
1504
+ const mdCell = (v) => v === null ? "_NULL_" : v.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
1505
+ /**
1506
+ * @param target Qualified table for SQL INSERT output, e.g. { schema: 'shop', table: 'users' }.
1507
+ */
1508
+ function createSerializer(format, columns, target) {
1509
+ const names = columns.map((c) => c.name);
1510
+ const obj = (cells) => Object.fromEntries(columns.map((c, i) => [c.name, typed(cells[i] ?? null, c.typeName)]));
1511
+ switch (format) {
1512
+ case "csv":
1513
+ case "csv-excel": {
1514
+ const nl = format === "csv-excel" ? "\r\n" : "\n";
1515
+ const line = (cells) => cells.map((v) => csvCell(v, ",")).join(",") + nl;
1516
+ return {
1517
+ header: () => (format === "csv-excel" ? "" : "") + names.map((n) => csvCell(n, ",")).join(",") + nl,
1518
+ row: line,
1519
+ footer: () => ""
1520
+ };
1521
+ }
1522
+ case "tsv": return {
1523
+ header: () => names.map(tsvCell).join(" ") + "\n",
1524
+ row: (cells) => cells.map(tsvCell).join(" ") + "\n",
1525
+ footer: () => ""
1526
+ };
1527
+ case "json": return {
1528
+ header: () => "[\n",
1529
+ row: (cells, i) => (i ? ",\n" : "") + " " + JSON.stringify(obj(cells)),
1530
+ footer: () => "\n]\n"
1531
+ };
1532
+ case "ndjson": return {
1533
+ header: () => "",
1534
+ row: (cells) => JSON.stringify(obj(cells)) + "\n",
1535
+ footer: () => ""
1536
+ };
1537
+ case "sql": {
1538
+ const rel = target ? `${quoteIdent$1(target.schema)}.${quoteIdent$1(target.table)}` : quoteIdent$1("query_result");
1539
+ const cols = names.map(quoteIdent$1).join(", ");
1540
+ return {
1541
+ header: () => "",
1542
+ row: (cells) => `INSERT INTO ${rel} (${cols}) VALUES (${cells.map((v, i) => sqlLiteral(v, columns[i]?.typeName)).join(", ")});\n`,
1543
+ footer: () => ""
1544
+ };
1545
+ }
1546
+ case "markdown": return {
1547
+ header: () => `| ${names.map(mdCell).join(" | ")} |\n| ${names.map(() => "---").join(" | ")} |\n`,
1548
+ row: (cells) => `| ${cells.map(mdCell).join(" | ")} |\n`,
1549
+ footer: () => ""
1550
+ };
1551
+ }
1552
+ }
1553
+ const IMPORT_FORMATS = [
1554
+ "csv",
1555
+ "tsv",
1556
+ "ndjson"
1557
+ ];
1558
+ // src/db/dump.ts
1559
+ /** Rows per INSERT and a rough cap on statement size, like mysqldump's extended inserts. */
1560
+ const ROWS_PER_INSERT = 1e3;
1561
+ const BYTES_PER_INSERT = 524288;
1562
+ async function resolveTables(ctx, wanted) {
1563
+ const all = (await queryObjects(ctx.pool, `SELECT table_name AS name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE' ORDER BY table_name`, [ctx.database])).map((r) => r.name);
1564
+ if (!wanted.length) return all;
1565
+ const missing = wanted.filter((w) => w.schema !== ctx.database || !all.includes(w.table));
1566
+ if (missing.length) throw new UserError(`Unknown table: ${missing.map((m) => `${m.schema}.${m.table}`).join(", ")}`);
1567
+ const keys = new Set(wanted.map((w) => w.table));
1568
+ return all.filter((t) => keys.has(t));
1569
+ }
1570
+ /** Views in an order where each comes after the views it selects from. */
1571
+ async function orderedViews(ctx) {
1572
+ const views = (await queryObjects(ctx.pool, `SELECT table_name AS name FROM information_schema.views WHERE table_schema = ? ORDER BY table_name`, [ctx.database])).map((v) => v.name);
1573
+ const deps = await queryObjects(ctx.pool, `SELECT view_name AS \`view\`, table_name AS uses FROM information_schema.view_table_usage
1574
+ WHERE view_schema = ? AND table_schema = ?`, [ctx.database, ctx.database]).catch(() => []);
1575
+ const set = new Set(views);
1576
+ const out = [];
1577
+ const state = /* @__PURE__ */ new Map();
1578
+ const visit = (v) => {
1579
+ if (state.has(v)) return;
1580
+ state.set(v, "visiting");
1581
+ for (const d of deps) if (d.view === v && set.has(d.uses)) visit(d.uses);
1582
+ state.set(v, "done");
1583
+ out.push(v);
1584
+ };
1585
+ for (const v of views) visit(v);
1586
+ return out;
1587
+ }
1588
+ const block = (sql) => `DELIMITER ;;\n${sql.trimEnd()};;\nDELIMITER ;\n\n`;
1589
+ async function* tableData(conn, schema, table, columns) {
1590
+ const list = columns.map((c) => quoteIdent$3(c.name)).join(", ");
1591
+ const head = `INSERT INTO ${quoteIdent$3(table)} (${list}) VALUES\n`;
1592
+ const query = coreConnection(conn).query({
1593
+ sql: `SELECT ${list} FROM ${qualified(schema, table)}`,
1594
+ rowsAsArray: true
1595
+ });
1596
+ let binary = [];
1597
+ query.on("fields", (f) => binary = binaryColumns(f));
1598
+ const stream = query.stream({ highWaterMark: ROWS_PER_INSERT });
1599
+ let tuples = [];
1600
+ let size = 0;
1601
+ const flush = () => {
1602
+ const sql = `${head}${tuples.join(",\n")};\n`;
1603
+ tuples = [];
1604
+ size = 0;
1605
+ return sql;
1606
+ };
1607
+ for await (const r of stream) {
1608
+ const t = `(${toCells(r, binary).map((v, i) => sqlLiteral(v, columns[i].typeName)).join(",")})`;
1609
+ tuples.push(t);
1610
+ size += t.length;
1611
+ if (tuples.length >= ROWS_PER_INSERT || size >= BYTES_PER_INSERT) yield flush();
1612
+ }
1613
+ if (tuples.length) yield flush();
1614
+ }
1615
+ /**
1616
+ * Generate the dump on one connection inside a consistent-snapshot,
1617
+ * read-only transaction, so every table is read at the same moment.
1618
+ */
1619
+ async function* dumpSql(ctx, opts) {
1620
+ if (!opts.structure && !opts.data) throw new UserError("Choose structure, data, or both");
1621
+ const full = opts.tables.length === 0;
1622
+ const tables = await resolveTables(ctx, opts.tables);
1623
+ const { mariadb } = await serverFlavor(ctx);
1624
+ const conn = await ctx.pool.getConnection();
1625
+ let clean = false;
1626
+ try {
1627
+ await conn.query(`SET SESSION time_zone = '+00:00'`);
1628
+ await conn.query("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ");
1629
+ await conn.query("START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY");
1630
+ const [info] = await queryObjects(conn, "SELECT VERSION() AS version, NOW() AS now");
1631
+ yield `-- mysqldeck dump of database \`${ctx.database}\` (${mariadb ? "MariaDB" : "MySQL"} ${info.version})\n-- Created ${info.now} UTC\n-- ${full ? "Whole database" : `${tables.length} table(s)`}; ${opts.structure && opts.data ? "structure and data" : opts.structure ? "structure only" : "data only"}\n-- Restore with: mysql <database> < <this file>\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\nSET NAMES utf8mb4;\n/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n/*!40103 SET TIME_ZONE='+00:00' */;\n/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n\n`;
1632
+ if (opts.structure) {
1633
+ yield `-- Tables\n\n`;
1634
+ for (const t of tables) yield `${(await queryRaw(conn, `SHOW CREATE TABLE ${qualified(ctx.database, t)}`)).rows[0][1]};\n\n`;
1635
+ }
1636
+ if (opts.data) {
1637
+ yield `-- Data\n\n`;
1638
+ for (const t of tables) {
1639
+ const columns = (await getColumns(ctx, ctx.database, t)).filter((c) => !c.generated).map((c) => ({
1640
+ name: c.name,
1641
+ typeName: c.typeName
1642
+ }));
1643
+ let any = false;
1644
+ for await (const sql of tableData(conn, ctx.database, t, columns)) {
1645
+ if (!any) yield `LOCK TABLES ${quoteIdent$3(t)} WRITE;\n`;
1646
+ any = true;
1647
+ yield sql;
1648
+ }
1649
+ if (any) yield `UNLOCK TABLES;\n\n`;
1650
+ }
1651
+ }
1652
+ if (opts.structure) {
1653
+ if (full) {
1654
+ const views = await orderedViews(ctx);
1655
+ if (views.length) {
1656
+ yield `-- Views\n\n`;
1657
+ for (const v of views) yield `${(await queryRaw(conn, `SHOW CREATE VIEW ${qualified(ctx.database, v)}`)).rows[0][1]};\n\n`;
1658
+ }
1659
+ const routines = await queryObjects(conn, `SELECT routine_name AS name, routine_type AS type FROM information_schema.routines
1660
+ WHERE routine_schema = ? ORDER BY routine_type, routine_name`, [ctx.database]);
1661
+ if (routines.length) {
1662
+ yield `-- Routines\n\n`;
1663
+ for (const r of routines) {
1664
+ const def = (await queryRaw(conn, `SHOW CREATE ${r.type} ${qualified(ctx.database, r.name)}`)).rows[0]?.[2];
1665
+ yield def ? block(def) : `-- ${r.type} ${r.name}: definition not visible to this account\n\n`;
1666
+ }
1667
+ }
1668
+ }
1669
+ const triggers = await queryObjects(conn, `SELECT trigger_name AS name, event_object_table AS \`table\` FROM information_schema.triggers
1670
+ WHERE trigger_schema = ? ORDER BY event_object_table, action_timing, event_manipulation, action_order`, [ctx.database]);
1671
+ const included = new Set(tables);
1672
+ const wantedTriggers = triggers.filter((t) => included.has(t.table));
1673
+ if (wantedTriggers.length) {
1674
+ yield `-- Triggers\n\n`;
1675
+ for (const t of wantedTriggers) {
1676
+ const res = await queryRaw(conn, `SHOW CREATE TRIGGER ${qualified(ctx.database, t.name)}`);
1677
+ yield block(res.rows[0][2]);
1678
+ }
1679
+ }
1680
+ if (full) {
1681
+ const events = await queryObjects(conn, `SELECT event_name AS name FROM information_schema.events WHERE event_schema = ? ORDER BY event_name`, [ctx.database]);
1682
+ if (events.length) {
1683
+ yield `-- Events\n\n`;
1684
+ for (const e of events) {
1685
+ const res = await queryRaw(conn, `SHOW CREATE EVENT ${qualified(ctx.database, e.name)}`);
1686
+ yield block(res.rows[0][3]);
1687
+ }
1688
+ }
1689
+ }
1690
+ }
1691
+ yield "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n\n-- End of mysqldeck dump\n";
1692
+ clean = true;
1693
+ } finally {
1694
+ if (clean) {
1695
+ await conn.query("ROLLBACK").catch(() => {});
1696
+ await conn.query("SET SESSION time_zone = DEFAULT").catch(() => {});
1697
+ conn.release();
1698
+ } else conn.destroy();
1699
+ }
1700
+ }
1701
+ // src/db/graph.ts
1702
+ /** Every table in this database with its columns, plus every foreign key, for the ER diagram. */
1703
+ async function getSchemaGraph(ctx) {
1704
+ const [tables, columns, pks, fks] = await Promise.all([
1705
+ queryObjects(ctx.pool, `SELECT table_name AS name, table_type AS type, table_rows AS \`rows\`, table_comment AS comment
1706
+ FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE' ORDER BY table_name`, [ctx.database]),
1707
+ queryObjects(ctx.pool, `SELECT table_name AS \`table\`, column_name AS name, column_type AS type, is_nullable AS nullable
1708
+ FROM information_schema.columns WHERE table_schema = ? ORDER BY table_name, ordinal_position`, [ctx.database]),
1709
+ queryObjects(ctx.pool, `SELECT table_name AS \`table\`, column_name AS name, seq_in_index AS seq
1710
+ FROM information_schema.statistics WHERE table_schema = ? AND index_name = 'PRIMARY'`, [ctx.database]),
1711
+ queryObjects(ctx.pool, `SELECT k.constraint_name AS name, k.table_name AS \`table\`, k.column_name AS \`column\`,
1712
+ k.referenced_table_schema AS ref_schema, k.referenced_table_name AS ref_table, k.referenced_column_name AS ref_column,
1713
+ r.delete_rule AS on_delete
1714
+ FROM information_schema.key_column_usage k
1715
+ LEFT JOIN information_schema.referential_constraints r
1716
+ ON r.constraint_schema = k.constraint_schema AND r.constraint_name = k.constraint_name AND r.table_name = k.table_name
1717
+ WHERE k.table_schema = ? AND k.referenced_table_name IS NOT NULL
1718
+ ORDER BY k.table_name, k.constraint_name, k.ordinal_position`, [ctx.database])
1719
+ ]);
1720
+ const pkPos = new Map(pks.map((p) => [`${p.table}\0${p.name}`, Number(p.seq)]));
1721
+ const colsByTable = /* @__PURE__ */ new Map();
1722
+ for (const c of columns) (colsByTable.get(c.table) ?? colsByTable.set(c.table, []).get(c.table)).push({
1723
+ name: c.name,
1724
+ type: c.type,
1725
+ nullable: c.nullable === "YES",
1726
+ pk: pkPos.get(`${c.table}\0${c.name}`) ?? 0
1727
+ });
1728
+ const graphTables = tables.map((t) => ({
1729
+ schema: ctx.database,
1730
+ name: t.name,
1731
+ kind: relKind(t.type),
1732
+ columns: colsByTable.get(t.name) ?? [],
1733
+ rows: t.rows === null ? -1 : Number(t.rows),
1734
+ comment: t.comment || null
1735
+ }));
1736
+ const byKey = /* @__PURE__ */ new Map();
1737
+ for (const f of fks) {
1738
+ const key = `${f.table}\0${f.name}`;
1739
+ let fk = byKey.get(key);
1740
+ if (!fk) {
1741
+ fk = {
1742
+ name: f.name,
1743
+ schema: ctx.database,
1744
+ table: f.table,
1745
+ columns: [],
1746
+ refSchema: f.ref_schema,
1747
+ refTable: f.ref_table,
1748
+ refColumns: [],
1749
+ onDelete: f.on_delete ?? "NO ACTION"
1750
+ };
1751
+ byKey.set(key, fk);
1752
+ }
1753
+ fk.columns.push(f.column);
1754
+ fk.refColumns.push(f.ref_column);
1755
+ }
1756
+ return {
1757
+ tables: graphTables,
1758
+ foreignKeys: [...byKey.values()]
1759
+ };
1760
+ }
1761
+ // src/db/status.ts
1762
+ /** SHOW GLOBAL STATUS for the given counters, as numbers (missing ones are 0). Works on MySQL and MariaDB. */
1763
+ async function globalStatus(pool, names) {
1764
+ const rows = await queryObjects(pool, `SHOW GLOBAL STATUS WHERE Variable_name IN (?)`, [names]);
1765
+ const out = Object.fromEntries(names.map((n) => [n, 0]));
1766
+ const lower = new Map(names.map((n) => [n.toLowerCase(), n]));
1767
+ for (const r of rows) {
1768
+ const k = lower.get(r.Variable_name.toLowerCase());
1769
+ if (k) out[k] = Number(r.Value) || 0;
1770
+ }
1771
+ return out;
1772
+ }
1773
+ /**
1774
+ * Connections using one database, from the process list. Without the PROCESS
1775
+ * privilege MySQL only shows your own, which is still a sensible answer.
1776
+ */
1777
+ async function connectionCounts(pool, database) {
1778
+ const [counts, trx, max] = await Promise.all([
1779
+ queryObjects(pool, `SELECT COUNT(*) AS total, COALESCE(SUM(command <> 'Sleep'), 0) AS active, COALESCE(SUM(command = 'Sleep'), 0) AS idle
1780
+ FROM information_schema.processlist WHERE db = ? AND command NOT IN ('Daemon', 'Binlog Dump', 'Binlog Dump GTID')`, [database]),
1781
+ queryObjects(pool, `SELECT COUNT(*) AS n FROM information_schema.innodb_trx t
1782
+ JOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id
1783
+ WHERE p.db = ? AND p.command = 'Sleep'`, [database]).catch(() => [{ n: "0" }]),
1784
+ queryObjects(pool, "SELECT @@max_connections AS max")
1785
+ ]);
1786
+ const c = counts[0];
1787
+ const idleTx = Number(trx[0]?.n ?? 0);
1788
+ return {
1789
+ total: Number(c.total),
1790
+ active: Number(c.active),
1791
+ idle: Number(c.idle) - idleTx,
1792
+ idleInTransaction: idleTx,
1793
+ max: Number(max[0].max)
1794
+ };
1795
+ }
1796
+ // src/db/live.ts
1797
+ const COUNTERS$1 = [
1798
+ "Questions",
1799
+ "Handler_commit",
1800
+ "Handler_rollback",
1801
+ "Innodb_rows_read",
1802
+ "Innodb_rows_inserted",
1803
+ "Innodb_rows_updated",
1804
+ "Innodb_rows_deleted",
1805
+ "Innodb_buffer_pool_read_requests",
1806
+ "Innodb_buffer_pool_reads"
1807
+ ];
1808
+ /** Most to least capable: leave out mysqldeck's own sessions, flag open transactions. */
1809
+ const ACTIVITY_QUERIES = [`SELECT p.id, p.user, p.host, p.db, p.command, p.time, p.state, LEFT(p.info, 500) AS query,
1810
+ EXISTS(SELECT 1 FROM information_schema.innodb_trx t WHERE t.trx_mysql_thread_id = p.id) AS in_trx
1811
+ FROM information_schema.processlist p
1812
+ WHERE p.db = ? AND p.id <> CONNECTION_ID() AND p.command NOT IN ('Daemon', 'Binlog Dump', 'Binlog Dump GTID')
1813
+ AND p.id NOT IN (SELECT a.processlist_id FROM performance_schema.session_connect_attrs a
1814
+ WHERE a.attr_name = 'program_name' AND a.attr_value = 'mysqldeck')
1815
+ ORDER BY p.command = 'Sleep', p.time DESC LIMIT 50`, `SELECT p.id, p.user, p.host, p.db, p.command, p.time, p.state, LEFT(p.info, 500) AS query, 0 AS in_trx
1816
+ FROM information_schema.processlist p
1817
+ WHERE p.db = ? AND p.id <> CONNECTION_ID() AND p.command NOT IN ('Daemon', 'Binlog Dump', 'Binlog Dump GTID')
1818
+ ORDER BY p.command = 'Sleep', p.time DESC LIMIT 50`];
1819
+ /**
1820
+ * Samples SHOW GLOBAL STATUS and the process list and turns the cumulative
1821
+ * counters into per-second rates between consecutive calls.
1822
+ */
1823
+ function createLiveSampler(ctx) {
1824
+ let prev = null;
1825
+ let activityQuery = 0;
1826
+ const activity = async () => {
1827
+ for (;;) try {
1828
+ return await queryObjects(ctx.pool, ACTIVITY_QUERIES[activityQuery], [ctx.database]);
1829
+ } catch (e) {
1830
+ if (activityQuery >= ACTIVITY_QUERIES.length - 1) throw e;
1831
+ activityQuery++;
1832
+ }
1833
+ };
1834
+ return async function sample() {
1835
+ const [status, conns, rows] = await Promise.all([
1836
+ globalStatus(ctx.pool, COUNTERS$1),
1837
+ connectionCounts(ctx.pool, ctx.database),
1838
+ activity()
1839
+ ]);
1840
+ const now = {
1841
+ t: Date.now(),
1842
+ queries: status.Questions,
1843
+ commits: status.Handler_commit,
1844
+ rollbacks: status.Handler_rollback,
1845
+ rowsRead: status.Innodb_rows_read,
1846
+ rowsWritten: status.Innodb_rows_inserted + status.Innodb_rows_updated + status.Innodb_rows_deleted,
1847
+ requests: status.Innodb_buffer_pool_read_requests,
1848
+ diskReads: status.Innodb_buffer_pool_reads
1849
+ };
1850
+ const last = prev;
1851
+ prev = now;
1852
+ const secs = last ? Math.max((now.t - last.t) / 1e3, .001) : 1;
1853
+ const delta = (key) => last ? Math.max(now[key] - last[key], 0) : 0;
1854
+ const rate = (key) => delta(key) / secs;
1855
+ const requests = delta("requests");
1856
+ return {
1857
+ type: "sample",
1858
+ t: now.t,
1859
+ connections: conns,
1860
+ queriesPerSec: rate("queries"),
1861
+ commitsPerSec: rate("commits"),
1862
+ rollbacksPerSec: rate("rollbacks"),
1863
+ rowsReadPerSec: rate("rowsRead"),
1864
+ rowsWrittenPerSec: rate("rowsWritten"),
1865
+ cacheHitRatio: requests > 0 ? Math.max(0, 1 - delta("diskReads") / requests) : null,
1866
+ activity: rows.map((a) => {
1867
+ const sleeping = a.command === "Sleep";
1868
+ return {
1869
+ pid: Number(a.id),
1870
+ user: a.user,
1871
+ db: a.db,
1872
+ client: a.host,
1873
+ state: !sleeping ? "active" : a.in_trx === "1" ? "idle in transaction" : "idle",
1874
+ command: a.command,
1875
+ waitEvent: a.state || null,
1876
+ durationSeconds: a.time === null ? null : Number(a.time),
1877
+ query: a.query ?? ""
1878
+ };
1879
+ })
1880
+ };
1881
+ };
1882
+ }
1883
+ // src/db/objects.ts
1884
+ const KEYWORD = {
1885
+ function: "FUNCTION",
1886
+ procedure: "PROCEDURE",
1887
+ trigger: "TRIGGER",
1888
+ event: "EVENT"
1889
+ };
1890
+ /** Column of SHOW CREATE … holding the statement. */
1891
+ const CREATE_COLUMN = {
1892
+ function: 2,
1893
+ procedure: 2,
1894
+ trigger: 2,
1895
+ event: 3
1896
+ };
1897
+ async function listObjects(ctx) {
1898
+ const [routines, params, triggers, events, scheduler] = await Promise.all([
1899
+ queryObjects(ctx.pool, `SELECT routine_name AS name, routine_type AS type, dtd_identifier AS returns, is_deterministic AS is_det
1900
+ FROM information_schema.routines WHERE routine_schema = ? ORDER BY routine_name`, [ctx.database]),
1901
+ queryObjects(ctx.pool, `SELECT specific_name AS routine, routine_type AS type, parameter_mode AS mode, parameter_name AS name, dtd_identifier AS dtd
1902
+ FROM information_schema.parameters WHERE specific_schema = ? AND ordinal_position > 0
1903
+ ORDER BY specific_name, ordinal_position`, [ctx.database]),
1904
+ queryObjects(ctx.pool, `SELECT trigger_name AS name, event_object_table AS \`table\`, action_timing AS timing, event_manipulation AS event
1905
+ FROM information_schema.triggers WHERE trigger_schema = ? ORDER BY event_object_table, action_timing, event_manipulation, action_order`, [ctx.database]),
1906
+ queryObjects(ctx.pool, `SELECT event_name AS name, status, event_type AS type, execute_at AS at, interval_value AS value, interval_field AS field
1907
+ FROM information_schema.events WHERE event_schema = ? ORDER BY event_name`, [ctx.database]),
1908
+ queryObjects(ctx.pool, "SELECT @@event_scheduler AS v").catch(() => [{ v: "unknown" }])
1909
+ ]);
1910
+ const paramList = (name, type) => params.filter((p) => p.routine === name && p.type === type).map((p) => [
1911
+ p.mode,
1912
+ p.name,
1913
+ p.dtd
1914
+ ].filter(Boolean).join(" ")).join(", ");
1915
+ const routine = (r) => ({
1916
+ name: r.name,
1917
+ params: paramList(r.name, r.type),
1918
+ returns: r.type === "FUNCTION" ? r.returns : null,
1919
+ deterministic: r.is_det === "YES"
1920
+ });
1921
+ return {
1922
+ functions: routines.filter((r) => r.type === "FUNCTION").map(routine),
1923
+ procedures: routines.filter((r) => r.type === "PROCEDURE").map(routine),
1924
+ triggers: triggers.map((t) => ({
1925
+ name: t.name,
1926
+ table: t.table,
1927
+ timing: `${t.timing} ${t.event}`
1928
+ })),
1929
+ events: events.map((e) => ({
1930
+ name: e.name,
1931
+ enabled: e.status === "ENABLED",
1932
+ schedule: e.type === "RECURRING" ? `every ${e.value} ${e.field}` : `at ${e.at}`
1933
+ })),
1934
+ eventScheduler: scheduler[0]?.v ?? "unknown"
1935
+ };
1936
+ }
1937
+ /** SHOW CREATE … text, or null when MySQL hides it (you are not the definer and lack SHOW_ROUTINE). */
1938
+ async function showCreate(ctx, kind, name) {
1939
+ try {
1940
+ const r = await queryRaw(ctx.pool, `SHOW CREATE ${KEYWORD[kind]} ${qualified(ctx.database, name)}`);
1941
+ if (!r.rows.length) throw new UserError(`That ${kind} no longer exists.`, 404);
1942
+ return r.rows[0][CREATE_COLUMN[kind]] ?? null;
1943
+ } catch (e) {
1944
+ const errno = e.errno;
1945
+ if (errno === 1305 || errno === 1360 || errno === 1539) throw new UserError(`That ${kind} no longer exists.`, 404);
1946
+ throw e;
1947
+ }
1948
+ }
1949
+ const prop = (label, value) => value === null || value === void 0 || value === "" ? [] : [[label, value]];
1950
+ async function getObject(ctx, kind, name) {
1951
+ const definition = await showCreate(ctx, kind, name);
1952
+ const hidden = definition === null;
1953
+ const base = {
1954
+ kind,
1955
+ name,
1956
+ schema: ctx.database,
1957
+ definition: definition ?? `-- MySQL won't show this definition: you are not its definer and lack the SHOW_ROUTINE privilege.`,
1958
+ editable: !hidden && !ctx.readonly
1959
+ };
1960
+ switch (kind) {
1961
+ case "function":
1962
+ case "procedure": {
1963
+ const [r] = await queryObjects(ctx.pool, `SELECT dtd_identifier AS returns, definer, security_type AS security, is_deterministic AS is_det,
1964
+ sql_data_access AS access, created, last_altered AS altered, routine_comment AS comment
1965
+ FROM information_schema.routines WHERE routine_schema = ? AND routine_name = ? AND routine_type = ?`, [
1966
+ ctx.database,
1967
+ name,
1968
+ KEYWORD[kind]
1969
+ ]);
1970
+ if (!r) throw new UserError(`That ${kind} no longer exists.`, 404);
1971
+ const args = (await queryObjects(ctx.pool, `SELECT CONCAT_WS(' ', parameter_mode, parameter_name, dtd_identifier) AS p FROM information_schema.parameters
1972
+ WHERE specific_schema = ? AND specific_name = ? AND routine_type = ? AND ordinal_position > 0 ORDER BY ordinal_position`, [
1973
+ ctx.database,
1974
+ name,
1975
+ KEYWORD[kind]
1976
+ ])).map((p) => p.p).join(", ");
1977
+ return {
1978
+ ...base,
1979
+ title: `${name}(${args})`,
1980
+ properties: [
1981
+ ["Kind", kind],
1982
+ ["Parameters", args || "(none)"],
1983
+ ...prop("Returns", kind === "function" ? r.returns : null),
1984
+ ["Deterministic", r.is_det === "YES" ? "yes" : "no"],
1985
+ ["Data access", r.access.toLowerCase().replace(/_/g, " ")],
1986
+ ["Security", r.security === "DEFINER" ? "definer (runs as its definer)" : "invoker"],
1987
+ ["Definer", r.definer],
1988
+ ["Created", r.created],
1989
+ ["Last changed", r.altered],
1990
+ ...prop("Comment", r.comment)
1991
+ ]
1992
+ };
1993
+ }
1994
+ case "trigger": {
1995
+ const [t] = await queryObjects(ctx.pool, `SELECT event_object_table AS \`table\`, action_timing AS timing, event_manipulation AS event, definer, created,
1996
+ action_order AS \`order\`
1997
+ FROM information_schema.triggers WHERE trigger_schema = ? AND trigger_name = ?`, [ctx.database, name]);
1998
+ if (!t) throw new UserError("That trigger no longer exists.", 404);
1999
+ return {
2000
+ ...base,
2001
+ title: name,
2002
+ properties: [
2003
+ ["Table", t.table],
2004
+ ["Fires", `${t.timing} ${t.event}, for each row`],
2005
+ ["Order", t.order],
2006
+ ["Definer", t.definer],
2007
+ ...prop("Created", t.created)
2008
+ ]
2009
+ };
2010
+ }
2011
+ case "event": {
2012
+ const [e] = await queryObjects(ctx.pool, `SELECT status, event_type AS type, execute_at AS at, interval_value AS value, interval_field AS field,
2013
+ starts, ends, last_executed AS last, on_completion AS completion, definer, event_comment AS comment
2014
+ FROM information_schema.events WHERE event_schema = ? AND event_name = ?`, [ctx.database, name]);
2015
+ if (!e) throw new UserError("That event no longer exists.", 404);
2016
+ return {
2017
+ ...base,
2018
+ title: name,
2019
+ enabled: e.status === "ENABLED",
2020
+ properties: [
2021
+ ["Status", e.status.toLowerCase().replace(/_/g, " ")],
2022
+ ["Schedule", e.type === "RECURRING" ? `every ${e.value} ${e.field}` : `once, at ${e.at}`],
2023
+ ...prop("Starts", e.starts),
2024
+ ...prop("Ends", e.ends),
2025
+ ["Last run", e.last ?? "never"],
2026
+ ["When done", e.completion === "PRESERVE" ? "keep the event" : "drop the event"],
2027
+ ["Definer", e.definer],
2028
+ ...prop("Comment", e.comment)
2029
+ ]
2030
+ };
2031
+ }
2032
+ }
2033
+ }
2034
+ const NAME_AFTER = (kw) => new RegExp(`\\b${kw}\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:(?:\`(?:[^\`]|\`\`)+\`|\\w+)\\s*\\.\\s*)?(\`(?:[^\`]|\`\`)+\`|\\w+)`, "i");
2035
+ /** The one statement in an edited definition, without DELIMITER lines or a trailing delimiter. */
2036
+ function singleStatement(sql) {
2037
+ const statements = new ScriptScanner().push(sql, true);
2038
+ if (statements.length !== 1) throw new UserError("The definition must be exactly one CREATE statement.");
2039
+ return statements[0].sql;
2040
+ }
2041
+ async function runObjectAction(ctx, a) {
2042
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2043
+ const kw = KEYWORD[a.kind];
2044
+ const target = qualified(ctx.database, a.name);
2045
+ if (a.action === "drop") {
2046
+ await exec(ctx.pool, `DROP ${kw} ${target}`);
2047
+ return {
2048
+ ok: true,
2049
+ message: `Dropped ${a.kind} ${a.name}`
2050
+ };
2051
+ }
2052
+ if (a.action === "enable" || a.action === "disable") {
2053
+ await exec(ctx.pool, `ALTER EVENT ${target} ${a.action === "enable" ? "ENABLE" : "DISABLE"}`);
2054
+ return {
2055
+ ok: true,
2056
+ message: `${a.action === "enable" ? "Enabled" : "Disabled"} event ${a.name}`
2057
+ };
2058
+ }
2059
+ if (a.action !== "replace") throw new UserError("Unknown action");
2060
+ const sql = singleStatement(a.sql);
2061
+ const head = stripLeadingComments(sql);
2062
+ if (!new RegExp(`^create\\s+(definer\\s*=\\s*\\S+\\s+)?(\\w+\\s+)*?${kw}\\b`, "i").test(head)) throw new UserError(`The definition must be a CREATE ${kw} statement.`);
2063
+ const m = NAME_AFTER(kw).exec(head);
2064
+ const newName = m ? m[1].replace(/^`|`$/g, "").replace(/``/g, "`") : a.name;
2065
+ const old = await showCreate(ctx, a.kind, a.name);
2066
+ if (old === null) throw new UserError(`You can't see this ${a.kind}'s definition, so it can't be replaced safely.`);
2067
+ const conn = await ctx.pool.getConnection();
2068
+ try {
2069
+ await conn.query(`USE ${quoteIdent$3(ctx.database)}`);
2070
+ await conn.query(`DROP ${kw} ${target}`);
2071
+ try {
2072
+ await conn.query(sql);
2073
+ } catch (e) {
2074
+ await conn.query(old).catch((restoreErr) => {
2075
+ e.message += ` (and restoring the previous version failed: ${restoreErr.message})`;
2076
+ });
2077
+ throw e;
2078
+ }
2079
+ } finally {
2080
+ conn.release();
2081
+ }
2082
+ return {
2083
+ ok: true,
2084
+ message: `Saved ${newName}`,
2085
+ name: newName
2086
+ };
2087
+ }
2088
+ // src/db/perf.ts
2089
+ const NUM = "([\\d.]+(?:e[-+]?\\d+)?)";
2090
+ const COST = new RegExp(`\\s*\\(cost=${NUM}(?:\\.\\.${NUM})? rows=${NUM}\\)`, "i");
2091
+ const ACTUAL = new RegExp(`\\s*\\(actual time=${NUM}\\.\\.${NUM} rows=${NUM} loops=(\\d+)\\)`, "i");
2092
+ const NEVER = /\s*\(never executed\)/i;
2093
+ /**
2094
+ * Parse EXPLAIN FORMAT=TREE / EXPLAIN ANALYZE output: one iterator per line,
2095
+ * "-> " after four spaces of indent per level, figures in trailing brackets.
2096
+ */
2097
+ function parseTreePlan(text) {
2098
+ const root = {
2099
+ operation: "Query",
2100
+ children: []
2101
+ };
2102
+ const stack = [{
2103
+ depth: -1,
2104
+ node: root
2105
+ }];
2106
+ for (const raw of text.split("\n")) {
2107
+ const m = /^(\s*)-> (.*)$/.exec(raw);
2108
+ if (!m) {
2109
+ const top = stack.at(-1).node;
2110
+ if (raw.trim() && top !== root) top.operation += ` ${raw.trim()}`;
2111
+ continue;
2112
+ }
2113
+ const depth = Math.floor(m[1].length / 4);
2114
+ let rest = m[2];
2115
+ const node = {
2116
+ operation: "",
2117
+ children: []
2118
+ };
2119
+ const actual = ACTUAL.exec(rest);
2120
+ if (actual) {
2121
+ node.actualFirstMs = Number(actual[1]);
2122
+ node.actualLastMs = Number(actual[2]);
2123
+ node.actualRows = Number(actual[3]);
2124
+ node.loops = Number(actual[4]);
2125
+ rest = rest.replace(ACTUAL, "");
2126
+ }
2127
+ if (NEVER.test(rest)) {
2128
+ node.neverExecuted = true;
2129
+ rest = rest.replace(NEVER, "");
2130
+ }
2131
+ const cost = COST.exec(rest);
2132
+ if (cost) {
2133
+ node.cost = Number(cost[2] ?? cost[1]);
2134
+ node.rows = Number(cost[3]);
2135
+ rest = rest.replace(COST, "");
2136
+ }
2137
+ node.operation = rest.trim();
2138
+ while (stack.length > 1 && stack.at(-1).depth >= depth) stack.pop();
2139
+ stack.at(-1).node.children.push(node);
2140
+ stack.push({
2141
+ depth,
2142
+ node
2143
+ });
2144
+ }
2145
+ return root.children.length === 1 ? root.children[0] : root;
2146
+ }
2147
+ /** Text outside quotes, so a ? inside a string literal doesn't count as a placeholder. */
2148
+ const unquoted = (sql) => sql.replace(/'(?:[^'\\]|\\.|'')*'|"(?:[^"\\]|\\.|"")*"|`(?:[^`]|``)*`/g, "");
2149
+ /**
2150
+ * EXPLAIN one statement as an iterator tree. With `analyze` the statement
2151
+ * really runs (MySQL only allows that for reads), inside a transaction that
2152
+ * is always rolled back. The pool refuses multiple statements, so exactly
2153
+ * one runs.
2154
+ */
2155
+ async function explainQuery(ctx, sql, analyze) {
2156
+ const text = sql.trim().replace(/;\s*$/, "");
2157
+ if (!text) throw new UserError("Nothing to explain");
2158
+ if (/^explain\b/i.test(stripLeadingComments(text))) throw new UserError("Leave out EXPLAIN: mysqldeck adds it for you.");
2159
+ if (splitStatements(text).length !== 1) throw new UserError("Explain one statement at a time: select it in the editor first.");
2160
+ if (/\?/.test(unquoted(text))) throw new UserError("This query has ? placeholders (it is a normalized digest). Replace them with real values first.");
2161
+ const conn = await ctx.pool.getConnection();
2162
+ try {
2163
+ await conn.query("START TRANSACTION");
2164
+ const started = performance.now();
2165
+ let out;
2166
+ try {
2167
+ out = (await queryRaw(conn, `EXPLAIN ${analyze ? "ANALYZE" : "FORMAT=TREE"} ${text}`)).rows.map((row) => row[0] ?? "").join("\n");
2168
+ } catch (e) {
2169
+ const err = e;
2170
+ if (err.errno === 1235 || /FORMAT=TREE|syntax.*(ANALYZE|TREE)/i.test(err.message)) throw new UserError("Plan trees need MySQL 8.0.18 or later (MariaDB is not supported here).");
2171
+ throw e;
2172
+ } finally {
2173
+ await conn.query("ROLLBACK").catch(() => {});
2174
+ }
2175
+ const ms = performance.now() - started;
2176
+ if (!out.trim()) throw new UserError("MySQL returned no plan");
2177
+ return {
2178
+ plan: parseTreePlan(out),
2179
+ text: out,
2180
+ analyzed: analyze,
2181
+ ms
2182
+ };
2183
+ } finally {
2184
+ conn.release();
2185
+ }
2186
+ }
2187
+ const SORT_SQL = {
2188
+ total: "SUM_TIMER_WAIT",
2189
+ mean: "AVG_TIMER_WAIT",
2190
+ calls: "COUNT_STAR",
2191
+ rows: "SUM_ROWS_SENT"
2192
+ };
2193
+ /** Timer columns are picoseconds. */
2194
+ const PS_PER_MS = 1e9;
2195
+ async function digestState(ctx) {
2196
+ const [r] = await queryObjects(ctx.pool, "SELECT @@performance_schema AS ps");
2197
+ if (r?.ps !== "1") return "off";
2198
+ const [c] = await queryObjects(ctx.pool, `SELECT enabled FROM performance_schema.setup_consumers WHERE name = 'statements_digest'`);
2199
+ return c?.enabled === "YES" ? "ok" : "disabled";
2200
+ }
2201
+ /**
2202
+ * The most expensive statements in this database, from performance_schema's
2203
+ * digest summary. mysqldeck's own catalog and status queries are left out.
2204
+ */
2205
+ async function listStatements(ctx, sort, limit) {
2206
+ let state;
2207
+ try {
2208
+ state = await digestState(ctx);
2209
+ } catch {
2210
+ return {
2211
+ status: "unavailable",
2212
+ statements: [],
2213
+ totalMs: 0
2214
+ };
2215
+ }
2216
+ if (state !== "ok") return {
2217
+ status: state,
2218
+ statements: [],
2219
+ totalMs: 0
2220
+ };
2221
+ const { version } = await serverFlavor(ctx);
2222
+ const sample = version >= 80003 ? "QUERY_SAMPLE_TEXT" : "NULL";
2223
+ const own = `DIGEST_TEXT IS NOT NULL
2224
+ AND DIGEST_TEXT NOT LIKE '%information\\_schema%' AND DIGEST_TEXT NOT LIKE '%performance\\_schema%'
2225
+ AND DIGEST_TEXT NOT REGEXP '^(SHOW|SET|USE|START TRANSACTION|COMMIT|ROLLBACK|SELECT @@|SELECT VERSION|EXPLAIN)'`;
2226
+ try {
2227
+ const rows = await queryObjects(ctx.pool, `SELECT DIGEST AS id, DIGEST_TEXT AS query, COUNT_STAR AS calls, SUM_TIMER_WAIT AS total, AVG_TIMER_WAIT AS mean,
2228
+ SUM_ROWS_SENT AS rows_sent, SUM_ROWS_EXAMINED AS examined,
2229
+ SUM_NO_INDEX_USED + SUM_NO_GOOD_INDEX_USED AS no_index, SUM_CREATED_TMP_DISK_TABLES AS tmp_disk,
2230
+ ${sample} AS sample,
2231
+ (SELECT SUM(SUM_TIMER_WAIT) FROM performance_schema.events_statements_summary_by_digest
2232
+ WHERE SCHEMA_NAME = ? AND ${own}) AS all_total
2233
+ FROM performance_schema.events_statements_summary_by_digest
2234
+ WHERE SCHEMA_NAME = ? AND ${own}
2235
+ ORDER BY ${SORT_SQL[sort]} DESC
2236
+ LIMIT ${Math.max(1, Math.min(limit, 200))}`, [ctx.database, ctx.database]);
2237
+ return {
2238
+ status: "ok",
2239
+ totalMs: Number(rows[0]?.all_total ?? 0) / PS_PER_MS,
2240
+ statements: rows.map((r) => ({
2241
+ id: r.id,
2242
+ query: r.query,
2243
+ calls: Number(r.calls),
2244
+ totalMs: Number(r.total) / PS_PER_MS,
2245
+ meanMs: Number(r.mean) / PS_PER_MS,
2246
+ rows: Number(r.rows_sent),
2247
+ rowsExamined: Number(r.examined),
2248
+ noIndexCalls: Number(r.no_index),
2249
+ tempDiskTables: Number(r.tmp_disk),
2250
+ sample: r.sample || null
2251
+ }))
2252
+ };
2253
+ } catch (e) {
2254
+ if (e.errno === 1142) return {
2255
+ status: "unavailable",
2256
+ statements: [],
2257
+ totalMs: 0
2258
+ };
2259
+ throw e;
2260
+ }
2261
+ }
2262
+ /** Turn on the statements_digest consumer (performance_schema itself can only be enabled at startup). */
2263
+ async function enableStatements(ctx) {
2264
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2265
+ if (await digestState(ctx) === "off") throw new UserError("performance_schema is off. Start MySQL with performance_schema=ON to collect query statistics.");
2266
+ await exec(ctx.pool, `UPDATE performance_schema.setup_consumers SET enabled = 'YES' WHERE name = 'statements_digest'`);
2267
+ return {
2268
+ ok: true,
2269
+ message: "Statement statistics are being collected"
2270
+ };
2271
+ }
2272
+ async function resetStatements(ctx) {
2273
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2274
+ await exec(ctx.pool, "TRUNCATE TABLE performance_schema.events_statements_summary_by_digest");
2275
+ return {
2276
+ ok: true,
2277
+ message: "Query statistics reset (for every database on the server)"
2278
+ };
2279
+ }
2280
+ /** Cancel a connection's running statement (KILL QUERY), or close the connection (KILL), if it uses this database. */
2281
+ async function signalSession(ctx, pid, terminate) {
2282
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2283
+ if (!(await queryObjects(ctx.pool, "SELECT id FROM information_schema.processlist WHERE id = ? AND db = ? AND id <> CONNECTION_ID()", [pid, ctx.database])).length) throw new UserError("That connection has already ended.", 404);
2284
+ await exec(ctx.pool, `${terminate ? "KILL" : "KILL QUERY"} ${Math.trunc(pid)}`);
2285
+ return {
2286
+ ok: true,
2287
+ message: terminate ? `Closed connection ${pid}` : `Cancelled the statement on connection ${pid}`
2288
+ };
2289
+ }
2290
+ // src/db/query.ts
2291
+ const isHeader = (r) => !!r && typeof r === "object" && !Array.isArray(r) && "affectedRows" in r;
2292
+ /**
2293
+ * MySQL reports syntax errors as "… near 'rest of query' at line N". Turn
2294
+ * that into a 1-based offset into the submitted SQL so the editor can point at it.
2295
+ */
2296
+ function errorPosition(sql, message, from = 0) {
2297
+ const m = /near '([\s\S]*)' at line (\d+)$/.exec(message);
2298
+ if (!m) return void 0;
2299
+ const near = m[1];
2300
+ if (!near) return sql.trimEnd().length;
2301
+ const i = sql.indexOf(near.slice(0, 80), from);
2302
+ return i >= 0 ? i + 1 : void 0;
2303
+ }
2304
+ /** A client-side DELIMITER command anywhere in the script. */
2305
+ const USES_DELIMITER = /^\s*delimiter\s+\S+\s*$/im;
2306
+ /** Turn what one conn.query() returned into results, labelled with the statements' keywords. */
2307
+ function collect(rows, fields, keywords, maxRows, out) {
2308
+ const multi = Array.isArray(fields) && fields.some((f) => f === void 0 || Array.isArray(f));
2309
+ const raws = multi ? rows : [rows];
2310
+ const fieldSets = multi ? fields : [fields];
2311
+ let stmt = 0;
2312
+ raws.forEach((r, i) => {
2313
+ const keyword = keywords[Math.min(stmt, keywords.length - 1)] || "SQL";
2314
+ if (isHeader(r)) {
2315
+ if (keyword === "CALL" && i > 0 && !isHeader(raws[i - 1])) {
2316
+ stmt++;
2317
+ return;
2318
+ }
2319
+ out.push({
2320
+ command: keyword,
2321
+ rowCount: r.affectedRows,
2322
+ fields: [],
2323
+ rows: [],
2324
+ truncated: false
2325
+ });
2326
+ stmt++;
2327
+ } else {
2328
+ const f = fieldSets[i];
2329
+ const binary = binaryColumns(f);
2330
+ const all = r;
2331
+ out.push({
2332
+ command: keyword,
2333
+ rowCount: all.length,
2334
+ fields: (f ?? []).map((x) => x.name),
2335
+ rows: all.slice(0, maxRows).map((row) => toCells(row, binary)),
2336
+ truncated: all.length > maxRows
2337
+ });
2338
+ if (keyword !== "CALL") stmt++;
2339
+ }
2340
+ });
2341
+ return raws.at(-1);
2342
+ }
2343
+ async function runOne(conn, sql, from, whole) {
2344
+ try {
2345
+ return await conn.query({
2346
+ sql,
2347
+ rowsAsArray: true
2348
+ });
2349
+ } catch (e) {
2350
+ const err = e;
2351
+ if (err.sqlMessage) err.position = errorPosition(whole, err.sqlMessage, from);
2352
+ throw err;
2353
+ }
2354
+ }
2355
+ /**
2356
+ * Run arbitrary SQL from the editor. Several statements (and CALLs returning
2357
+ * several result sets) give one result each. Runs on the multi-statement
2358
+ * pool, on a connection reset to this database first so a USE in an earlier
2359
+ * script can't leak into this one. Scripts with mysql-client DELIMITER
2360
+ * commands are split here and run statement by statement.
2361
+ */
2362
+ async function runQuery(ctx, sql) {
2363
+ if (ctx.readonly) {
2364
+ const refusal = readonlyRefusal(sql);
2365
+ if (refusal) throw new UserError(refusal, 403);
2366
+ }
2367
+ const statements = new ScriptScanner().push(sql, true);
2368
+ const conn = await ctx.scriptPool().getConnection();
2369
+ try {
2370
+ await conn.query(`USE ${quoteIdent$3(ctx.database)}`);
2371
+ const started = performance.now();
2372
+ const results = [];
2373
+ let last;
2374
+ if (USES_DELIMITER.test(sql)) {
2375
+ let from = 0;
2376
+ for (const st of statements) {
2377
+ from = Math.max(sql.indexOf(st.sql.slice(0, 40), from), from);
2378
+ const [rows, fields] = await runOne(conn, st.sql, from, sql);
2379
+ last = collect(rows, fields, [statementKeyword(st.sql)], ctx.maxRows, results);
2380
+ }
2381
+ } else {
2382
+ const [rows, fields] = await runOne(conn, sql, 0, sql);
2383
+ last = collect(rows, fields, statements.map((s) => statementKeyword(s.sql)), ctx.maxRows, results);
2384
+ }
2385
+ const ms = performance.now() - started;
2386
+ if (results.length && isHeader(last) && last.warningStatus > 0) {
2387
+ const [w] = await conn.query({
2388
+ sql: "SHOW WARNINGS",
2389
+ rowsAsArray: true
2390
+ });
2391
+ results.at(-1).warnings = w.map((x) => `${String(x[0])} ${String(x[1])}: ${String(x[2])}`);
2392
+ }
2393
+ return {
2394
+ ms,
2395
+ results
2396
+ };
2397
+ } finally {
2398
+ conn.release();
2399
+ }
2400
+ }
2401
+ // src/db/restore.ts
2402
+ const ACCOUNT_STATEMENT = /^(grant|revoke|create\s+(user|role)|alter\s+user|drop\s+(user|role)|rename\s+user|set\s+password|set\s+default\s+role)\b/i;
2403
+ /**
2404
+ * mysqldump's replication bookkeeping: GTID_PURGED rewrites server state (and
2405
+ * fails on a server with its own history), SQL_LOG_BIN=0 would hide the
2406
+ * restore from replicas. Neither belongs in loading data.
2407
+ */
2408
+ const REPLICATION_STATE = /^set\s+@@(global\.gtid_purged|session\.sql_log_bin)\b/i;
2409
+ /** Statements that would leave the database the restore was started in. */
2410
+ const SWITCHES_DATABASE = /^(use\b|create\s+(database|schema)\b)/i;
2411
+ /** DEFINER=`user`@`host` (or 'user'@'host', user@host, CURRENT_USER) in CREATE VIEW/TRIGGER/ROUTINE/EVENT. */
2412
+ const DEFINER = /\bDEFINER\s*=\s*(?:CURRENT_USER(?:\(\))?|(?:`(?:[^`]|``)*`|'(?:[^'\\]|\\.|'')*'|[\w.$-]+)@(?:`(?:[^`]|``)*`|'(?:[^'\\]|\\.|'')*'|[\w.%$:-]+))\s*/i;
2413
+ /** Remove the DEFINER clause near the start of a CREATE statement so it defaults to the restoring account. */
2414
+ function stripDefiner(sql) {
2415
+ const head = sql.slice(0, 600);
2416
+ if (!DEFINER.test(head)) return sql;
2417
+ return head.replace(DEFINER, "") + sql.slice(600);
2418
+ }
2419
+ /** Attach "where in the dump" context to a MySQL error. */
2420
+ function annotate(err, line, sql) {
2421
+ const e = err;
2422
+ if (e && e.sqlMessage) {
2423
+ const snippet = sql.trim().replace(/\s+/g, " ").slice(0, 160);
2424
+ e.detail = `line ${line} of the dump: ${snippet}${snippet.length >= 160 ? "…" : ""}`;
2425
+ }
2426
+ return err;
2427
+ }
2428
+ /** Execute a mysql-client style script (mysqldump output) from a stream, statement by statement. */
2429
+ async function restoreScript(ctx, body, opts) {
2430
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2431
+ let bytes = 0;
2432
+ const counted = body.pipe(new Transform({ transform(chunk, _enc, cb) {
2433
+ bytes += chunk.length;
2434
+ cb(null, chunk);
2435
+ } }));
2436
+ body.on("error", (e) => counted.destroy(e));
2437
+ const source = opts.gzip ? counted.pipe(createGunzip()) : counted;
2438
+ if (opts.gzip) counted.on("error", (e) => source.destroy(e));
2439
+ source.setEncoding("utf8");
2440
+ const started = performance.now();
2441
+ const scanner = new ScriptScanner();
2442
+ const conn = await ctx.pool.getConnection();
2443
+ const result = {
2444
+ statements: 0,
2445
+ skipped: 0,
2446
+ rows: 0,
2447
+ ms: 0,
2448
+ bytes: 0
2449
+ };
2450
+ const run = async (statements) => {
2451
+ for (const st of statements) {
2452
+ const head = stripLeadingComments(st.sql);
2453
+ if (!head) continue;
2454
+ if (SWITCHES_DATABASE.test(head) || REPLICATION_STATE.test(head) || opts.skipOwnership && ACCOUNT_STATEMENT.test(head)) {
2455
+ result.skipped++;
2456
+ continue;
2457
+ }
2458
+ const sql = opts.skipOwnership && /^(create|alter)\b/i.test(head) ? stripDefiner(st.sql) : st.sql;
2459
+ try {
2460
+ const [res] = await conn.query(sql);
2461
+ if (statementKeyword(head) === "INSERT" || statementKeyword(head) === "REPLACE") result.rows += res.affectedRows ?? 0;
2462
+ result.statements++;
2463
+ } catch (e) {
2464
+ const errno = e.errno;
2465
+ if (/^set\b/i.test(head) && (errno === 1227 || errno === 1193 || errno === 1229 || errno === 1238)) {
2466
+ result.skipped++;
2467
+ continue;
2468
+ }
2469
+ throw annotate(e, st.line, st.sql);
2470
+ }
2471
+ }
2472
+ };
2473
+ try {
2474
+ await conn.query(`USE ${quoteIdent$3(ctx.database)}`);
2475
+ if (opts.singleTransaction) await conn.query("START TRANSACTION");
2476
+ for await (const chunk of source) await run(scanner.push(chunk, false));
2477
+ await run(scanner.push("", true));
2478
+ if (opts.singleTransaction) await conn.query("COMMIT");
2479
+ return {
2480
+ ...result,
2481
+ ms: performance.now() - started,
2482
+ bytes
2483
+ };
2484
+ } catch (err) {
2485
+ if (opts.singleTransaction) await conn.query("ROLLBACK").catch(() => {});
2486
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") throw new UserError("Upload was cancelled.");
2487
+ if (err.code === "Z_DATA_ERROR") throw new UserError("The file is not valid gzip.");
2488
+ throw err;
2489
+ } finally {
2490
+ conn.destroy();
2491
+ source.destroy();
2492
+ }
2493
+ }
2494
+ // src/db/stats.ts
2495
+ const num = (v) => v === null || v === void 0 ? 0 : Number(v);
2496
+ const numOrNull = (v) => v === null || v === void 0 ? null : Number(v);
2497
+ const COUNTERS = [
2498
+ "Uptime",
2499
+ "Questions",
2500
+ "Slow_queries",
2501
+ "Handler_commit",
2502
+ "Handler_rollback",
2503
+ "Innodb_rows_inserted",
2504
+ "Innodb_rows_updated",
2505
+ "Innodb_rows_deleted",
2506
+ "Innodb_rows_read",
2507
+ "Innodb_buffer_pool_read_requests",
2508
+ "Innodb_buffer_pool_reads",
2509
+ "Innodb_deadlocks",
2510
+ "Created_tmp_tables",
2511
+ "Created_tmp_disk_tables"
2512
+ ];
2513
+ /** MySQL's DATETIME text ("2026-01-02 03:04:05") as ISO, in the server's time zone (treated as local). */
2514
+ const iso = (v) => v ? new Date(v.replace(" ", "T")).toISOString() : null;
2515
+ async function getStats(ctx) {
2516
+ const [status, server, conns, tables, deadlocks, io] = await Promise.all([
2517
+ globalStatus(ctx.pool, COUNTERS),
2518
+ queryObjects(ctx.pool, `SELECT VERSION() AS version, @@character_set_database AS charset, @@collation_database AS collation,
2519
+ (SELECT SUM(data_length + index_length) FROM information_schema.tables WHERE table_schema = DATABASE()) AS size`),
2520
+ connectionCounts(ctx.pool, ctx.database),
2521
+ queryObjects(ctx.pool, `SELECT t.table_name AS name, t.table_type AS type, t.engine, t.table_rows AS \`rows\`,
2522
+ t.data_length AS data, t.index_length AS idx, t.data_free AS free, t.auto_increment,
2523
+ t.update_time, t.table_collation AS collation,
2524
+ (SELECT COUNT(DISTINCT s.index_name) FROM information_schema.statistics s
2525
+ WHERE s.table_schema = t.table_schema AND s.table_name = t.table_name) AS index_count
2526
+ FROM information_schema.tables t
2527
+ WHERE t.table_schema = ?
2528
+ ORDER BY COALESCE(t.data_length, 0) + COALESCE(t.index_length, 0) DESC, t.table_name`, [ctx.database]),
2529
+ queryObjects(ctx.pool, `SELECT count AS n FROM information_schema.innodb_metrics WHERE name = 'lock_deadlocks'`).then((r) => numOrNull(r[0]?.n)).catch(() => null),
2530
+ queryObjects(ctx.pool, `SELECT object_name AS name, SUM(IF(index_name IS NULL, count_read, 0)) AS scans,
2531
+ SUM(IF(index_name IS NULL, 0, count_read)) AS idx
2532
+ FROM performance_schema.table_io_waits_summary_by_index_usage
2533
+ WHERE object_schema = ? GROUP BY object_name`, [ctx.database]).catch(() => null)
2534
+ ]);
2535
+ const s = server[0];
2536
+ const ioByTable = new Map((io ?? []).map((r) => [r.name, r]));
2537
+ const requests = status.Innodb_buffer_pool_read_requests;
2538
+ const diskReads = status.Innodb_buffer_pool_reads;
2539
+ return {
2540
+ sizeBytes: num(s.size),
2541
+ uptimeSeconds: status.Uptime,
2542
+ serverVersion: s.version,
2543
+ charset: s.charset,
2544
+ collation: s.collation,
2545
+ connections: conns,
2546
+ cacheHitRatio: requests > 0 ? Math.max(0, 1 - diskReads / requests) : null,
2547
+ transactions: {
2548
+ commits: status.Handler_commit,
2549
+ rollbacks: status.Handler_rollback
2550
+ },
2551
+ rowsTotal: {
2552
+ inserted: status.Innodb_rows_inserted,
2553
+ updated: status.Innodb_rows_updated,
2554
+ deleted: status.Innodb_rows_deleted,
2555
+ read: status.Innodb_rows_read
2556
+ },
2557
+ queries: status.Questions,
2558
+ slowQueries: status.Slow_queries,
2559
+ deadlocks: deadlocks ?? (status.Innodb_deadlocks || null),
2560
+ tempTables: status.Created_tmp_tables,
2561
+ tempDiskTables: status.Created_tmp_disk_tables,
2562
+ tables: tables.map((t) => {
2563
+ const kind = relKind(t.type);
2564
+ const tableBytes = num(t.data);
2565
+ const indexBytes = num(t.idx);
2566
+ const usage = io ? ioByTable.get(t.name) : void 0;
2567
+ return {
2568
+ schema: ctx.database,
2569
+ name: t.name,
2570
+ kind,
2571
+ rows: num(t.rows),
2572
+ tableBytes,
2573
+ indexBytes,
2574
+ totalBytes: tableBytes + indexBytes,
2575
+ freeBytes: num(t.free),
2576
+ indexCount: num(t.index_count),
2577
+ engine: t.engine,
2578
+ collation: t.collation,
2579
+ autoIncrement: numOrNull(t.auto_increment),
2580
+ updatedAt: iso(t.update_time),
2581
+ fullScans: io && kind === "r" ? num(usage?.scans) : null,
2582
+ indexReads: io && kind === "r" ? num(usage?.idx) : null
2583
+ };
2584
+ })
2585
+ };
2586
+ }
2587
+ // src/db/table-actions.ts
2588
+ /**
2589
+ * ANALYZE / OPTIMIZE / CHECK TABLE report problems as result rows, not
2590
+ * errors. Throw on an error row, return the notes otherwise.
2591
+ */
2592
+ async function adminStatement(pool, verb, rel) {
2593
+ const rows = await queryObjects(pool, `${verb} TABLE ${rel}`);
2594
+ const errors = rows.filter((r) => /^error$/i.test(r.Msg_type)).map((r) => r.Msg_text);
2595
+ if (errors.length) throw new UserError(errors.join(" "));
2596
+ const bad = rows.find((r) => /^status$/i.test(r.Msg_type) && !/^(ok|table is already up to date)$/i.test(r.Msg_text));
2597
+ if (bad) throw new UserError(`${verb} TABLE: ${bad.Msg_text}`);
2598
+ return rows.filter((r) => /^(note|warning|info)$/i.test(r.Msg_type)).map((r) => r.Msg_text);
2599
+ }
2600
+ /** Run statements on one connection with FOREIGN_KEY_CHECKS off, then restore them. */
2601
+ async function withoutForeignKeyChecks(pool, statements) {
2602
+ const conn = await pool.getConnection();
2603
+ try {
2604
+ await conn.query("SET SESSION FOREIGN_KEY_CHECKS = 0");
2605
+ for (const s of statements) await conn.query(s);
2606
+ } finally {
2607
+ await conn.query("SET SESSION FOREIGN_KEY_CHECKS = 1").catch(() => conn.destroy());
2608
+ conn.release();
2609
+ }
2610
+ }
2611
+ async function runTableAction(ctx, schema, table, a) {
2612
+ const meta = await getTableMeta(ctx, schema, table);
2613
+ const rel = qualified(schema, table);
2614
+ const isTable = meta.kind === "r";
2615
+ const changes = a.action !== "check";
2616
+ if (ctx.readonly && changes) throw new UserError(READONLY_MESSAGE, 403);
2617
+ switch (a.action) {
2618
+ case "truncate": {
2619
+ if (!isTable) throw new UserError("Only tables can be emptied");
2620
+ const sql = `TRUNCATE TABLE ${rel}`;
2621
+ if (a.ignoreForeignKeys) await withoutForeignKeyChecks(ctx.pool, [sql]);
2622
+ else await exec(ctx.pool, sql);
2623
+ return {
2624
+ ok: true,
2625
+ message: `Emptied ${table}`
2626
+ };
2627
+ }
2628
+ case "drop": {
2629
+ const sql = `DROP ${isTable ? "TABLE" : "VIEW"} ${rel}`;
2630
+ if (a.ignoreForeignKeys) await withoutForeignKeyChecks(ctx.pool, [sql]);
2631
+ else await exec(ctx.pool, sql);
2632
+ return {
2633
+ ok: true,
2634
+ message: `Dropped ${table}`
2635
+ };
2636
+ }
2637
+ case "rename":
2638
+ await exec(ctx.pool, `RENAME TABLE ${rel} TO ${qualified(schema, a.newName)}`);
2639
+ return {
2640
+ ok: true,
2641
+ message: `Renamed to ${a.newName}`
2642
+ };
2643
+ case "duplicate": {
2644
+ if (!isTable) throw new UserError("Only tables can be duplicated");
2645
+ const target = qualified(schema, a.newName);
2646
+ await exec(ctx.pool, `CREATE TABLE ${target} LIKE ${rel}`);
2647
+ if (a.withData) {
2648
+ const cols = meta.columns.filter((c) => !c.generated).map((c) => quoteIdent$3(c.name)).join(", ");
2649
+ try {
2650
+ await exec(ctx.pool, `INSERT INTO ${target} (${cols}) SELECT ${cols} FROM ${rel}`);
2651
+ } catch (e) {
2652
+ await exec(ctx.pool, `DROP TABLE ${target}`).catch(() => {});
2653
+ throw e;
2654
+ }
2655
+ }
2656
+ return {
2657
+ ok: true,
2658
+ message: `Created ${a.newName}${a.withData ? " with data" : ""}`
2659
+ };
2660
+ }
2661
+ case "optimize":
2662
+ if (!isTable) throw new UserError("Only tables can be optimized");
2663
+ await adminStatement(ctx.pool, "OPTIMIZE", rel);
2664
+ return {
2665
+ ok: true,
2666
+ message: `Optimized ${table}`
2667
+ };
2668
+ case "analyze":
2669
+ if (!isTable) throw new UserError("Only tables can be analyzed");
2670
+ await adminStatement(ctx.pool, "ANALYZE", rel);
2671
+ return {
2672
+ ok: true,
2673
+ message: `Analyzed ${table}`
2674
+ };
2675
+ case "check": {
2676
+ if (!isTable) throw new UserError("Only tables can be checked");
2677
+ const notes = await adminStatement(ctx.pool, "CHECK", rel);
2678
+ return {
2679
+ ok: true,
2680
+ message: notes.length ? `${table}: ${notes.join(" ")}` : `${table} is OK`
2681
+ };
2682
+ }
2683
+ case "resetAutoIncrement":
2684
+ if (!isTable) throw new UserError("Only tables have an auto-increment counter");
2685
+ await exec(ctx.pool, `ALTER TABLE ${rel} AUTO_INCREMENT = ${Math.max(1, Math.trunc(a.value))}`);
2686
+ return {
2687
+ ok: true,
2688
+ message: `The next auto-increment value is at least ${Math.max(1, Math.trunc(a.value))}`
2689
+ };
2690
+ }
2691
+ }
2692
+ /** SHOW CREATE output for a table (with its triggers) or a view. */
2693
+ async function relationDdl(ctx, schema, table) {
2694
+ const meta = await getTableMeta(ctx, schema, table);
2695
+ const rel = qualified(schema, table);
2696
+ if (meta.kind === "v") return `${(await queryRaw(ctx.pool, `SHOW CREATE VIEW ${rel}`)).rows[0][1]};\n`;
2697
+ let out = `${(await queryRaw(ctx.pool, `SHOW CREATE TABLE ${rel}`)).rows[0][1]};\n`;
2698
+ const triggers = await queryObjects(ctx.pool, `SELECT trigger_name AS name FROM information_schema.triggers
2699
+ WHERE event_object_schema = ? AND event_object_table = ? ORDER BY action_timing, event_manipulation, action_order`, [schema, table]);
2700
+ for (const t of triggers) {
2701
+ const tr = await queryRaw(ctx.pool, `SHOW CREATE TRIGGER ${qualified(schema, t.name)}`);
2702
+ out += `\nDELIMITER ;;\n${tr.rows[0][2]};;\nDELIMITER ;\n`;
2703
+ }
2704
+ return out;
2705
+ }
2706
+ /** ANALYZE, OPTIMIZE or CHECK a batch of tables, one at a time. */
2707
+ async function runMaintenance(ctx, action, tables) {
2708
+ if (ctx.readonly && action !== "check") throw new UserError(READONLY_MESSAGE, 403);
2709
+ const failed = [];
2710
+ let done = 0;
2711
+ for (const t of tables) try {
2712
+ await adminStatement(ctx.pool, action.toUpperCase(), qualified(t.schema, t.table));
2713
+ done++;
2714
+ } catch (e) {
2715
+ failed.push({
2716
+ table: t.table,
2717
+ error: e.message
2718
+ });
2719
+ }
2720
+ return {
2721
+ ok: true,
2722
+ message: `${action === "optimize" ? "Optimized" : action === "check" ? "Checked" : "Analyzed"} ${done} table${done === 1 ? "" : "s"}${failed.length ? `, ${failed.length} failed` : ""}`,
2723
+ done,
2724
+ failed
2725
+ };
2726
+ }
2727
+ // src/db/transfer.ts
2728
+ const BATCH = 2e3;
2729
+ /**
2730
+ * Stream every row matching the filters, serialized. mysql2 streams the
2731
+ * result row by row, so memory stays flat no matter how big the table is.
2732
+ */
2733
+ async function* exportRows(ctx, req, signal) {
2734
+ const meta = await getTableMeta(ctx, req.schema, req.table);
2735
+ const { where, values, orderBy } = buildQueryParts(meta, req);
2736
+ const columns = meta.columns.map((c) => ({
2737
+ name: c.name,
2738
+ typeName: c.typeName
2739
+ }));
2740
+ const sql = `SELECT ${meta.columns.map((c) => quoteIdent$3(c.name)).join(", ")} FROM ${qualified(req.schema, req.table)}${where}${orderBy}`;
2741
+ const serializer = createSerializer(req.format, columns, {
2742
+ schema: req.schema,
2743
+ table: req.table
2744
+ });
2745
+ const conn = await ctx.pool.getConnection();
2746
+ let finished = false;
2747
+ const query = coreConnection(conn).query({
2748
+ sql,
2749
+ values,
2750
+ rowsAsArray: true
2751
+ });
2752
+ let binary = [];
2753
+ query.on("fields", (f) => binary = binaryColumns(f));
2754
+ const rows = query.stream({ highWaterMark: BATCH });
2755
+ try {
2756
+ yield serializer.header();
2757
+ let index = 0;
2758
+ let chunk = "";
2759
+ for await (const r of rows) {
2760
+ if (signal?.aborted) return;
2761
+ chunk += serializer.row(toCells(r, binary), index++);
2762
+ if (index % BATCH === 0) {
2763
+ yield chunk;
2764
+ chunk = "";
2765
+ }
2766
+ }
2767
+ if (chunk) yield chunk;
2768
+ yield serializer.footer();
2769
+ finished = true;
2770
+ } finally {
2771
+ if (finished) conn.release();
2772
+ else {
2773
+ rows.destroy();
2774
+ conn.destroy();
2775
+ }
2776
+ }
2777
+ }
2778
+ /**
2779
+ * RFC 4180 CSV → records. An unquoted empty field is NULL, a quoted one ("")
2780
+ * an empty string: the same convention mysqldeck's CSV export uses.
2781
+ */
2782
+ function csvParser(delimiter) {
2783
+ let field = "";
2784
+ let quoted = false;
2785
+ let inQuotes = false;
2786
+ let pendingQuote = false;
2787
+ let cells = [];
2788
+ let line = 1;
2789
+ let recordLine = 1;
2790
+ let atFieldStart = true;
2791
+ let lastWasCr = false;
2792
+ const endField = () => {
2793
+ cells.push(!quoted && field === "" ? null : field);
2794
+ field = "";
2795
+ quoted = false;
2796
+ atFieldStart = true;
2797
+ };
2798
+ return { push(text, out, final = false) {
2799
+ for (let i = 0; i < text.length; i++) {
2800
+ const ch = text[i];
2801
+ if (pendingQuote) {
2802
+ pendingQuote = false;
2803
+ if (ch === "\"") {
2804
+ field += "\"";
2805
+ continue;
2806
+ }
2807
+ inQuotes = false;
2808
+ }
2809
+ if (inQuotes) {
2810
+ if (ch === "\"") pendingQuote = true;
2811
+ else {
2812
+ if (ch === "\n") line++;
2813
+ field += ch;
2814
+ }
2815
+ continue;
2816
+ }
2817
+ if (ch === "\"" && atFieldStart) {
2818
+ inQuotes = true;
2819
+ quoted = true;
2820
+ atFieldStart = false;
2821
+ continue;
2822
+ }
2823
+ if (ch === delimiter) {
2824
+ endField();
2825
+ continue;
2826
+ }
2827
+ if (ch === "\n" || ch === "\r") {
2828
+ if (ch === "\n" && lastWasCr) {
2829
+ lastWasCr = false;
2830
+ continue;
2831
+ }
2832
+ lastWasCr = ch === "\r";
2833
+ line++;
2834
+ endField();
2835
+ if (!(cells.length === 1 && cells[0] === null)) out.push({
2836
+ cells,
2837
+ line: recordLine
2838
+ });
2839
+ cells = [];
2840
+ recordLine = line;
2841
+ continue;
2842
+ }
2843
+ lastWasCr = false;
2844
+ atFieldStart = false;
2845
+ field += ch;
2846
+ }
2847
+ if (final) {
2848
+ if (pendingQuote) {
2849
+ pendingQuote = false;
2850
+ inQuotes = false;
2851
+ }
2852
+ if (inQuotes) throw new UserError(`Line ${recordLine}: a quoted field is never closed`);
2853
+ if (field !== "" || quoted || cells.length) {
2854
+ endField();
2855
+ out.push({
2856
+ cells,
2857
+ line: recordLine
2858
+ });
2859
+ cells = [];
2860
+ }
2861
+ }
2862
+ } };
2863
+ }
2864
+ const TSV_ESCAPES = {
2865
+ "0": "\0",
2866
+ b: "\b",
2867
+ n: "\n",
2868
+ r: "\r",
2869
+ t: " ",
2870
+ Z: "",
2871
+ "\\": "\\"
2872
+ };
2873
+ /** LOAD DATA / SELECT … INTO OUTFILE text format: tab-separated, \N is NULL, backslash escapes. */
2874
+ function tsvParser() {
2875
+ let buffered = "";
2876
+ let line = 0;
2877
+ const parseLine = (l, out) => {
2878
+ line++;
2879
+ const text = l.replace(/\r$/, "");
2880
+ if (!text) return;
2881
+ out.push({
2882
+ line,
2883
+ cells: text.split(" ").map((f) => f === "\\N" ? null : f.replace(/\\(.)/g, (_, c) => TSV_ESCAPES[c] ?? c))
2884
+ });
2885
+ };
2886
+ return { push(text, out, final = false) {
2887
+ buffered += text;
2888
+ const lines = buffered.split("\n");
2889
+ buffered = lines.pop() ?? "";
2890
+ for (const l of lines) parseLine(l, out);
2891
+ if (final && buffered) {
2892
+ parseLine(buffered, out);
2893
+ buffered = "";
2894
+ }
2895
+ } };
2896
+ }
2897
+ /** JSON Lines: one object per line, picking `keys`. Objects and arrays are stored as JSON text. */
2898
+ function ndjsonParser(keys) {
2899
+ let buffered = "";
2900
+ let line = 0;
2901
+ const parseLine = (l, out) => {
2902
+ line++;
2903
+ const t = l.trim();
2904
+ if (!t) return;
2905
+ let obj;
2906
+ try {
2907
+ obj = JSON.parse(t);
2908
+ } catch {
2909
+ throw new UserError(`Line ${line} is not valid JSON`);
2910
+ }
2911
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new UserError(`Line ${line} is not a JSON object`);
2912
+ out.push({
2913
+ line,
2914
+ cells: keys.map((k) => {
2915
+ const v = obj[k];
2916
+ if (v === null || v === void 0) return null;
2917
+ if (typeof v === "boolean") return v ? "1" : "0";
2918
+ return typeof v === "object" ? JSON.stringify(v) : String(v);
2919
+ })
2920
+ });
2921
+ };
2922
+ return { push(text, out, final = false) {
2923
+ buffered += text;
2924
+ const lines = buffered.split("\n");
2925
+ buffered = lines.pop() ?? "";
2926
+ for (const l of lines) parseLine(l, out);
2927
+ if (final && buffered) {
2928
+ parseLine(buffered, out);
2929
+ buffered = "";
2930
+ }
2931
+ } };
2932
+ }
2933
+ /** Counts bytes flowing through, for the response summary. */
2934
+ function byteCounter() {
2935
+ const counter = new Transform({ transform(chunk, _enc, cb) {
2936
+ counter.bytes += chunk.length;
2937
+ cb(null, chunk);
2938
+ } });
2939
+ counter.bytes = 0;
2940
+ return counter;
2941
+ }
2942
+ /** Rows per INSERT statement. */
2943
+ const INSERT_BATCH = 500;
2944
+ /**
2945
+ * Stream an uploaded file into the table with multi-row INSERTs, all in one
2946
+ * transaction: any bad row rolls the whole import back. (LOAD DATA LOCAL
2947
+ * would be faster but is off by default on MySQL 8.)
2948
+ */
2949
+ async function importRows(ctx, req, body) {
2950
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
2951
+ const meta = await getTableMeta(ctx, req.schema, req.table);
2952
+ if (meta.kind !== "r") throw new UserError("Data can only be imported into tables");
2953
+ if (!req.columns.length) throw new UserError("Choose at least one column to import");
2954
+ const byName = new Map(meta.columns.map((c) => [c.name, c]));
2955
+ for (const c of req.columns) if (!byName.has(c)) throw new UserError(`Unknown column "${c}"`);
2956
+ if (new Set(req.columns).size !== req.columns.length) throw new UserError("Each column can only be mapped once");
2957
+ if (req.delimiter.length !== 1) throw new UserError("Delimiter must be a single character");
2958
+ if (req.keys?.length && req.keys.length !== req.columns.length) throw new UserError("keys and columns must be the same length");
2959
+ const rel = qualified(req.schema, req.table);
2960
+ const cols = req.columns.map((c) => byName.get(c));
2961
+ const head = `INSERT INTO ${rel} (${req.columns.map(quoteIdent$3).join(", ")}) VALUES `;
2962
+ const parser = req.format === "csv" ? csvParser(req.delimiter) : req.format === "tsv" ? tsvParser() : ndjsonParser(req.keys?.length ? req.keys : req.columns);
2963
+ let skipHeader = req.header && req.format !== "ndjson";
2964
+ const started = performance.now();
2965
+ const counter = byteCounter();
2966
+ let source = body.pipe(counter);
2967
+ body.on("error", (e) => counter.destroy(e));
2968
+ if (req.gzip) {
2969
+ const gunzip = createGunzip();
2970
+ counter.on("error", (e) => gunzip.destroy(e));
2971
+ source = counter.pipe(gunzip);
2972
+ }
2973
+ source.setEncoding("utf8");
2974
+ const conn = await ctx.pool.getConnection();
2975
+ let rowCount = 0;
2976
+ const flush = async (records) => {
2977
+ if (!records.length) return;
2978
+ const values = [];
2979
+ const tuples = records.map((rec) => {
2980
+ if (rec.cells.length !== cols.length) throw new UserError(`Line ${rec.line}: expected ${cols.length} values but found ${rec.cells.length}`);
2981
+ return `(${rec.cells.map((v, i) => {
2982
+ const p = valueSql(cols[i], v);
2983
+ values.push(p.param);
2984
+ return p.sql;
2985
+ }).join(", ")})`;
2986
+ });
2987
+ try {
2988
+ await conn.query(head + tuples.join(", "), values);
2989
+ } catch (e) {
2990
+ const err = e;
2991
+ const first = records[0].line;
2992
+ const last = records.at(-1).line;
2993
+ const row = /at row (\d+)/.exec(err.sqlMessage ?? "");
2994
+ const at = row ? records[Number(row[1]) - 1]?.line : void 0;
2995
+ if (err.sqlMessage) err.detail = at ? `Line ${at} of the file.` : `Somewhere in lines ${first}–${last} of the file.`;
2996
+ throw err;
2997
+ }
2998
+ rowCount += records.length;
2999
+ };
3000
+ try {
3001
+ await conn.query("START TRANSACTION");
3002
+ if (req.truncate) await exec(conn, `DELETE FROM ${rel}`);
3003
+ let pending = [];
3004
+ const take = async (out) => {
3005
+ for (const rec of out) {
3006
+ if (skipHeader) {
3007
+ skipHeader = false;
3008
+ continue;
3009
+ }
3010
+ pending.push(rec);
3011
+ if (pending.length >= INSERT_BATCH) {
3012
+ await flush(pending);
3013
+ pending = [];
3014
+ }
3015
+ }
3016
+ };
3017
+ for await (const chunk of source) {
3018
+ const out = [];
3019
+ parser.push(chunk, out);
3020
+ await take(out);
3021
+ }
3022
+ const out = [];
3023
+ parser.push("", out, true);
3024
+ await take(out);
3025
+ await flush(pending);
3026
+ await conn.query("COMMIT");
3027
+ return {
3028
+ rowCount,
3029
+ ms: performance.now() - started,
3030
+ bytes: counter.bytes
3031
+ };
3032
+ } catch (err) {
3033
+ await conn.query("ROLLBACK").catch(() => {});
3034
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") throw new UserError("Upload was cancelled; nothing was imported.");
3035
+ if (err.code === "Z_DATA_ERROR") throw new UserError("The file is not valid gzip; nothing was imported.");
3036
+ throw err;
3037
+ } finally {
3038
+ conn.release();
3039
+ source.destroy();
3040
+ }
3041
+ }
3042
+ // src/shared/users.ts
3043
+ /**
3044
+ * MySQL accounts, roles and privileges: types and SQL builders shared by the
3045
+ * server and the UI (so the UI can preview exactly what will run).
3046
+ */
3047
+ const quoteIdent = (name) => `\`${name.replace(/`/g, "``")}\``;
3048
+ const quoteString = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
3049
+ /** 'user'@'host' as it appears in GRANT, CREATE USER and friends. */
3050
+ const accountSql = (a) => `${quoteString(a.user)}@${quoteString(a.host)}`;
3051
+ const sameAccount = (a, b) => a.user === b.user && a.host === b.host;
3052
+ /** Accounts MySQL creates for itself; they are locked and shouldn't be touched. */
3053
+ const isSystemAccount = (a) => a.host === "localhost" && [
3054
+ "mysql.sys",
3055
+ "mysql.session",
3056
+ "mysql.infoschema"
3057
+ ].includes(a.user);
3058
+ const DATABASE_PRESETS = [
3059
+ {
3060
+ value: "read",
3061
+ label: "Read only",
3062
+ hint: "SELECT, SHOW VIEW, EXECUTE",
3063
+ privileges: [
3064
+ "SELECT",
3065
+ "SHOW VIEW",
3066
+ "EXECUTE"
3067
+ ]
3068
+ },
3069
+ {
3070
+ value: "write",
3071
+ label: "Read and write",
3072
+ hint: "Read, plus INSERT, UPDATE, DELETE, temporary tables and LOCK TABLES",
3073
+ privileges: [
3074
+ "SELECT",
3075
+ "SHOW VIEW",
3076
+ "EXECUTE",
3077
+ "INSERT",
3078
+ "UPDATE",
3079
+ "DELETE",
3080
+ "CREATE TEMPORARY TABLES",
3081
+ "LOCK TABLES"
3082
+ ]
3083
+ },
3084
+ {
3085
+ value: "all",
3086
+ label: "Full control",
3087
+ hint: "ALL PRIVILEGES: data and structure",
3088
+ privileges: ["ALL PRIVILEGES"]
3089
+ },
3090
+ {
3091
+ value: "none",
3092
+ label: "No access",
3093
+ hint: "Revoke everything on this database",
3094
+ privileges: []
3095
+ }
3096
+ ];
3097
+ function validateAccount(a) {
3098
+ if (!a.user.trim()) return "Enter a user name.";
3099
+ if (a.user.length > 32) return "User names can be at most 32 characters.";
3100
+ if (a.host.length > 255) return "Hosts can be at most 255 characters.";
3101
+ if (!a.host.trim()) return "Enter a host, or % for any host.";
3102
+ return null;
3103
+ }
3104
+ /** Database names in GRANT treat _ and % as wildcards; escape them to mean only this database. */
3105
+ const grantDbSql = (db) => quoteIdent(db.replace(/([_%])/g, "\\$1"));
3106
+ const unescapeGrantDb = (db) => db.replace(/\\([_%])/g, "$1");
3107
+ function grantTarget(level, db, table) {
3108
+ if (level === "global") return "*.*";
3109
+ if (level === "database") return `${grantDbSql(db ?? "")}.*`;
3110
+ return `${quoteIdent(db ?? "")}.${quoteIdent(table ?? "")}`;
3111
+ }
3112
+ const PRIVILEGE_RE = /^[A-Z][A-Z_ ]*$/;
3113
+ /** GRANT/REVOKE statements for a set of changes, grouped by object and direction. */
3114
+ function grantChangesSql(account, changes) {
3115
+ const groups = /* @__PURE__ */ new Map();
3116
+ for (const c of changes) {
3117
+ if (!PRIVILEGE_RE.test(c.privilege)) throw new Error(`Unknown privilege "${c.privilege}"`);
3118
+ const target = grantTarget(c.level, c.db, c.table);
3119
+ const key = `${c.grant ? "G" : "R"} ${target}`;
3120
+ const g = groups.get(key) ?? groups.set(key, {
3121
+ target,
3122
+ grant: c.grant,
3123
+ privileges: []
3124
+ }).get(key);
3125
+ if (!g.privileges.includes(c.privilege)) g.privileges.push(c.privilege);
3126
+ }
3127
+ return [...groups.values()].map((g) => g.grant ? `GRANT ${g.privileges.join(", ")} ON ${g.target} TO ${accountSql(account)};` : `REVOKE ${g.privileges.join(", ")} ON ${g.target} FROM ${accountSql(account)};`);
3128
+ }
3129
+ /**
3130
+ * Set exactly the preset's privileges on one database. The two REVOKEs come
3131
+ * first and fail harmlessly (error 1141) when there was nothing to revoke.
3132
+ */
3133
+ function databasePresetSql(account, db, preset) {
3134
+ const target = `${grantDbSql(db)}.*`;
3135
+ const p = DATABASE_PRESETS.find((x) => x.value === preset);
3136
+ const out = [`REVOKE ALL PRIVILEGES ON ${target} FROM ${accountSql(account)};`, `REVOKE GRANT OPTION ON ${target} FROM ${accountSql(account)};`];
3137
+ if (p.privileges.length) out.push(`GRANT ${p.privileges.join(", ")} ON ${target} TO ${accountSql(account)};`);
3138
+ return out;
3139
+ }
3140
+ /** Statements for a user action; the password goes in as a placeholder (`?`), never in the text. */
3141
+ function userActionSql(a) {
3142
+ const acct = {
3143
+ user: a.user,
3144
+ host: a.host
3145
+ };
3146
+ switch (a.action) {
3147
+ case "create": {
3148
+ if (a.role) return [{ sql: `CREATE ROLE ${accountSql(acct)};` }];
3149
+ const auth = a.password ? ` IDENTIFIED${a.plugin ? ` WITH ${a.plugin.replace(/\W/g, "")}` : ""} BY ?` : a.plugin ? ` IDENTIFIED WITH ${a.plugin.replace(/\W/g, "")}` : "";
3150
+ const out = [{
3151
+ sql: `CREATE USER ${accountSql(acct)}${auth};`,
3152
+ password: !!a.password
3153
+ }];
3154
+ if (a.roles.length) {
3155
+ out.push({ sql: `GRANT ${a.roles.map(accountSql).join(", ")} TO ${accountSql(acct)};` });
3156
+ out.push({ sql: `SET DEFAULT ROLE ALL TO ${accountSql(acct)};` });
3157
+ }
3158
+ return out;
3159
+ }
3160
+ case "update": {
3161
+ const out = [];
3162
+ if (a.password !== void 0) out.push({
3163
+ sql: `ALTER USER ${accountSql(acct)} IDENTIFIED BY ?;`,
3164
+ password: true
3165
+ });
3166
+ if (a.locked !== void 0) out.push({ sql: `ALTER USER ${accountSql(acct)} ACCOUNT ${a.locked ? "LOCK" : "UNLOCK"};` });
3167
+ if (a.expirePassword) out.push({ sql: `ALTER USER ${accountSql(acct)} PASSWORD EXPIRE;` });
3168
+ if (a.maxUserConnections !== void 0) out.push({ sql: `ALTER USER ${accountSql(acct)} WITH MAX_USER_CONNECTIONS ${Math.max(0, Math.trunc(a.maxUserConnections))};` });
3169
+ const renamed = {
3170
+ user: a.newUser ?? a.user,
3171
+ host: a.newHost ?? a.host
3172
+ };
3173
+ if (!sameAccount(renamed, acct)) out.push({ sql: `RENAME USER ${accountSql(acct)} TO ${accountSql(renamed)};` });
3174
+ return out;
3175
+ }
3176
+ case "drop": return [{ sql: `DROP USER ${accountSql(acct)};` }];
3177
+ case "membership": return a.grant ? [{ sql: `GRANT ${accountSql(a.role)} TO ${accountSql(acct)};` }, { sql: `SET DEFAULT ROLE ALL TO ${accountSql(acct)};` }] : [{ sql: `REVOKE ${accountSql(a.role)} FROM ${accountSql(acct)};` }];
3178
+ }
3179
+ }
3180
+ const ACCT = "`((?:[^`]|``)*)`@`((?:[^`]|``)*)`";
3181
+ const unq = (s) => s.replace(/``/g, "`");
3182
+ /** Split "SELECT, INSERT (`a`, `b`), UPDATE" on top-level commas. */
3183
+ function splitPrivileges(list) {
3184
+ const out = [];
3185
+ let depth = 0;
3186
+ let cur = "";
3187
+ for (const ch of list) {
3188
+ if (ch === "(") depth++;
3189
+ if (ch === ")") depth--;
3190
+ if (ch === "," && depth === 0) {
3191
+ out.push(cur.trim());
3192
+ cur = "";
3193
+ } else cur += ch;
3194
+ }
3195
+ if (cur.trim()) out.push(cur.trim());
3196
+ return out;
3197
+ }
3198
+ /** Turn SHOW GRANTS FOR lines into privileges and role grants. */
3199
+ function parseGrants(lines) {
3200
+ const privileges = [];
3201
+ const roles = [];
3202
+ const roleLine = new RegExp(`^GRANT ((?:${ACCT})(?:\\s*,\\s*${ACCT})*) TO ${ACCT}( WITH ADMIN OPTION)?$`);
3203
+ for (const raw of lines) {
3204
+ const line = raw.trim().replace(/;$/, "");
3205
+ if (roleLine.test(line)) {
3206
+ const admin = line.endsWith(" WITH ADMIN OPTION");
3207
+ const list = line.slice(6, line.lastIndexOf(" TO "));
3208
+ for (const m of list.matchAll(new RegExp(ACCT, "g"))) roles.push({
3209
+ user: unq(m[1]),
3210
+ host: unq(m[2]),
3211
+ admin
3212
+ });
3213
+ continue;
3214
+ }
3215
+ const m = /^GRANT (.+?) ON (?:(FUNCTION|PROCEDURE) )?(\*|`(?:[^`]|``)*`)\.(\*|`(?:[^`]|``)*`) TO .+?( WITH GRANT OPTION)?$/.exec(line);
3216
+ if (!m) continue;
3217
+ const [, list, routine, dbPart, tablePart, grantOption] = m;
3218
+ if (/^PROXY$/i.test(list.trim())) continue;
3219
+ const db = dbPart === "*" ? null : unq(dbPart.slice(1, -1));
3220
+ const table = tablePart === "*" ? null : unq(tablePart.slice(1, -1));
3221
+ const parts = splitPrivileges(list);
3222
+ privileges.push({
3223
+ level: db === null ? "global" : table === null ? "database" : "table",
3224
+ db: db === null ? null : table === null ? unescapeGrantDb(db) : db,
3225
+ table,
3226
+ routine: routine ?? null,
3227
+ privileges: parts.filter((p) => !p.includes("(")).map((p) => p === "ALL" ? "ALL PRIVILEGES" : p),
3228
+ columns: parts.filter((p) => p.includes("(")),
3229
+ grantOption: !!grantOption
3230
+ });
3231
+ }
3232
+ return {
3233
+ privileges,
3234
+ roles
3235
+ };
3236
+ }
3237
+ // src/db/users.ts
3238
+ async function currentAccount(pool) {
3239
+ const [r] = await queryObjects(pool, "SELECT CURRENT_USER() AS u");
3240
+ const at = r.u.lastIndexOf("@");
3241
+ return {
3242
+ user: r.u.slice(0, at),
3243
+ host: r.u.slice(at + 1)
3244
+ };
3245
+ }
3246
+ async function showGrants(pool, a) {
3247
+ return (await queryRaw(pool, `SHOW GRANTS FOR ${accountSql(a)}`)).rows.map((row) => row[0] ?? "");
3248
+ }
3249
+ async function canCreateUsers(pool) {
3250
+ return (await queryRaw(pool, "SHOW GRANTS").then((r) => r.rows.map((x) => x[0] ?? ""))).some((g) => /^GRANT (ALL PRIVILEGES|.*\bCREATE USER\b).* ON \*\.\* /.test(g));
3251
+ }
3252
+ async function listUsers(ctx) {
3253
+ const current = await currentAccount(ctx.pool);
3254
+ let rows;
3255
+ let edges = [];
3256
+ try {
3257
+ rows = await queryObjects(ctx.pool, `SELECT user, host, account_locked AS locked, password_expired AS expired, plugin,
3258
+ authentication_string <> '' AS has_password, super_priv = 'Y' AS super,
3259
+ max_user_connections AS max_conn, password_last_changed AS changed
3260
+ FROM mysql.user ORDER BY user, host`);
3261
+ edges = await queryObjects(ctx.pool, "SELECT from_user, from_host, to_user, to_host FROM mysql.role_edges").catch(() => []);
3262
+ } catch (e) {
3263
+ if (e.errno !== 1142) throw e;
3264
+ const { roles } = parseGrants(await showGrants(ctx.pool, current));
3265
+ return {
3266
+ status: "limited",
3267
+ current,
3268
+ canManage: false,
3269
+ users: [{
3270
+ ...current,
3271
+ isRole: false,
3272
+ isSystem: false,
3273
+ locked: false,
3274
+ passwordExpired: false,
3275
+ hasPassword: true,
3276
+ plugin: "",
3277
+ superuser: false,
3278
+ memberOf: roles.map((r) => ({
3279
+ user: r.user,
3280
+ host: r.host
3281
+ })),
3282
+ maxUserConnections: 0,
3283
+ passwordLastChanged: null
3284
+ }]
3285
+ };
3286
+ }
3287
+ const roleNames = new Set(edges.map((e) => `${e.from_user}@${e.from_host}`));
3288
+ const users = rows.map((r) => {
3289
+ const a = {
3290
+ user: r.user,
3291
+ host: r.host
3292
+ };
3293
+ return {
3294
+ ...a,
3295
+ isRole: roleNames.has(`${r.user}@${r.host}`) || r.locked === "Y" && r.has_password !== "1" && !isSystemAccount(a),
3296
+ isSystem: isSystemAccount(a),
3297
+ locked: r.locked === "Y",
3298
+ passwordExpired: r.expired === "Y",
3299
+ hasPassword: r.has_password === "1",
3300
+ plugin: r.plugin,
3301
+ superuser: r.super === "1",
3302
+ memberOf: edges.filter((e) => e.to_user === r.user && e.to_host === r.host).map((e) => ({
3303
+ user: e.from_user,
3304
+ host: e.from_host
3305
+ })),
3306
+ maxUserConnections: Number(r.max_conn),
3307
+ passwordLastChanged: r.changed
3308
+ };
3309
+ });
3310
+ return {
3311
+ status: "ok",
3312
+ current,
3313
+ canManage: await canCreateUsers(ctx.pool).catch(() => false),
3314
+ users
3315
+ };
3316
+ }
3317
+ async function getUser(ctx, a) {
3318
+ const list = await listUsers(ctx);
3319
+ const summary = list.users.find((u) => sameAccount(u, a));
3320
+ if (!summary) throw new UserError(`Account ${a.user}@${a.host} not found`, 404);
3321
+ let grants;
3322
+ try {
3323
+ grants = await showGrants(ctx.pool, a);
3324
+ } catch (e) {
3325
+ if (e.errno === 1044 || e.errno === 1142) throw new UserError("You don't have permission to see this account's privileges.", 403);
3326
+ throw e;
3327
+ }
3328
+ const { privileges, roles } = parseGrants(grants);
3329
+ const members = list.users.filter((u) => u.memberOf.some((m) => sameAccount(m, a))).map((u) => ({
3330
+ user: u.user,
3331
+ host: u.host
3332
+ }));
3333
+ return {
3334
+ summary,
3335
+ grants,
3336
+ privileges,
3337
+ roles,
3338
+ members
3339
+ };
3340
+ }
3341
+ async function run$1(pool, statements, password) {
3342
+ const conn = await pool.getConnection();
3343
+ try {
3344
+ for (const s of statements) await conn.query(s.sql, s.password ? [password ?? ""] : []);
3345
+ } finally {
3346
+ conn.release();
3347
+ }
3348
+ }
3349
+ async function runUserAction(ctx, a) {
3350
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
3351
+ const acct = {
3352
+ user: a.user,
3353
+ host: a.host
3354
+ };
3355
+ const invalid = validateAccount(acct);
3356
+ if (invalid) throw new UserError(invalid);
3357
+ if (isSystemAccount(acct)) throw new UserError("MySQL manages its own system accounts; leave them as they are.", 403);
3358
+ if (a.action === "drop" || a.action === "update" && (a.newUser !== void 0 || a.newHost !== void 0)) {
3359
+ const me = await currentAccount(ctx.pool);
3360
+ if (sameAccount(me, acct)) throw new UserError("That is the account mysqldeck is connected as. Change it from another account.", 409);
3361
+ }
3362
+ if (a.action === "update") {
3363
+ const bad = validateAccount({
3364
+ user: a.newUser ?? a.user,
3365
+ host: a.newHost ?? a.host
3366
+ });
3367
+ if (bad) throw new UserError(bad);
3368
+ }
3369
+ await run$1(ctx.pool, userActionSql(a), a.action === "create" || a.action === "update" ? a.password : void 0);
3370
+ const label = `${a.user}@${a.host}`;
3371
+ switch (a.action) {
3372
+ case "create": return {
3373
+ ok: true,
3374
+ message: `Created ${a.role ? "role" : "user"} ${label}`,
3375
+ user: acct
3376
+ };
3377
+ case "update": {
3378
+ const user = {
3379
+ user: a.newUser ?? a.user,
3380
+ host: a.newHost ?? a.host
3381
+ };
3382
+ return {
3383
+ ok: true,
3384
+ message: `Saved ${user.user}@${user.host}`,
3385
+ user
3386
+ };
3387
+ }
3388
+ case "drop": return {
3389
+ ok: true,
3390
+ message: `Dropped ${label}`
3391
+ };
3392
+ case "membership": return {
3393
+ ok: true,
3394
+ message: `${a.grant ? "Granted" : "Revoked"} ${a.role.user}@${a.role.host} ${a.grant ? "to" : "from"} ${label}`
3395
+ };
3396
+ }
3397
+ }
3398
+ async function applyGrants(ctx, a, changes) {
3399
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
3400
+ let statements;
3401
+ try {
3402
+ statements = grantChangesSql(a, changes);
3403
+ } catch (e) {
3404
+ throw new UserError(e.message);
3405
+ }
3406
+ for (const s of statements) await exec(ctx.pool, s);
3407
+ const n = changes.length;
3408
+ return {
3409
+ ok: true,
3410
+ message: `Applied ${n} privilege change${n === 1 ? "" : "s"}`,
3411
+ statements
3412
+ };
3413
+ }
3414
+ async function applyDatabasePreset(ctx, a, db, preset) {
3415
+ if (ctx.readonly) throw new UserError(READONLY_MESSAGE, 403);
3416
+ for (const sql of databasePresetSql(a, db, preset)) try {
3417
+ await exec(ctx.pool, sql);
3418
+ } catch (e) {
3419
+ if (!(sql.startsWith("REVOKE") && e.errno === 1141)) throw e;
3420
+ }
3421
+ return {
3422
+ ok: true,
3423
+ message: `${a.user}@${a.host} now has ${preset === "none" ? "no access to" : `${preset} access to`} ${db}`
3424
+ };
3425
+ }
3426
+ // src/db/database.ts
3427
+ /** Operations against one database, backed by its own pools. */
3428
+ function createDatabase(config) {
3429
+ const pools = createPools(config);
3430
+ const ctx = {
3431
+ pool: pools.pool,
3432
+ scriptPool: pools.scriptPool,
3433
+ database: config.database,
3434
+ readonly: config.readonly,
3435
+ maxRows: config.maxRows
3436
+ };
3437
+ return {
3438
+ name: config.database,
3439
+ readonly: config.readonly,
3440
+ info: () => getInfo(ctx),
3441
+ stats: () => getStats(ctx),
3442
+ /** A sampler that reports per-second rates since its previous call. */
3443
+ liveSampler: () => createLiveSampler(ctx),
3444
+ /** Stream all matching rows, serialized (async iterator of text chunks). */
3445
+ exportRows: (req, signal) => exportRows(ctx, req, signal),
3446
+ /** Insert an uploaded CSV/TSV/NDJSON stream into a table. */
3447
+ importRows: (req, body) => importRows(ctx, req, body),
3448
+ /** mysqldump-style SQL for some or all tables (async iterator of chunks). */
3449
+ dumpSql: (opts) => dumpSql(ctx, opts),
3450
+ /** Run an uploaded SQL dump. */
3451
+ restore: (body, opts) => restoreScript(ctx, body, opts),
3452
+ /** Truncate / drop / rename / duplicate / optimize / analyze / check / reset auto-increment. */
3453
+ tableAction: (schema, table, action) => runTableAction(ctx, schema, table, action),
3454
+ ddl: (schema, table) => relationDdl(ctx, schema, table),
3455
+ maintenance: (action, tables) => runMaintenance(ctx, action, tables),
3456
+ createTable: (spec) => createTable(ctx, spec),
3457
+ catalog: () => getCatalog(ctx),
3458
+ /** Tables, columns and foreign keys for the ER diagram. */
3459
+ graph: () => getSchemaGraph(ctx),
3460
+ /** Accounts are server-wide. */
3461
+ users: () => listUsers(ctx),
3462
+ user: (a) => getUser(ctx, a),
3463
+ userAction: (a) => runUserAction(ctx, a),
3464
+ grants: (a, changes) => applyGrants(ctx, a, changes),
3465
+ databasePreset: (a, db, preset) => applyDatabasePreset(ctx, a, db, preset),
3466
+ objects: () => listObjects(ctx),
3467
+ object: (kind, name) => getObject(ctx, kind, name),
3468
+ objectAction: (a) => runObjectAction(ctx, a),
3469
+ explain: (sql, analyze) => explainQuery(ctx, sql, analyze),
3470
+ statements: (sort, limit) => listStatements(ctx, sort, limit),
3471
+ enableStatements: () => enableStatements(ctx),
3472
+ resetStatements: () => resetStatements(ctx),
3473
+ signalSession: (pid, terminate) => signalSession(ctx, pid, terminate),
3474
+ alter: (schema, table, a) => alterTable(ctx, schema, table, a),
3475
+ listDatabases: () => listDatabases(ctx),
3476
+ tables: () => listTables(ctx),
3477
+ meta: (schema, table) => getTableMeta(ctx, schema, table),
3478
+ rows: (req) => selectRows(ctx, req),
3479
+ insert: (schema, table, values) => insertRow(ctx, schema, table, values),
3480
+ update: (schema, table, key, values) => updateRow(ctx, schema, table, key, values),
3481
+ remove: (schema, table, keys) => deleteRows(ctx, schema, table, keys),
3482
+ query: (sql) => runQuery(ctx, sql),
3483
+ /** Run one trusted, server-built statement (CREATE DATABASE etc). */
3484
+ exec: async (sql) => {
3485
+ await exec(ctx.pool, sql);
3486
+ },
3487
+ close: () => pools.close()
3488
+ };
3489
+ }
3490
+ // src/db/manager.ts
3491
+ const truthy = (v) => v !== null && /^(1|true|yes|on|required|require|verify_ca|verify_identity)$/i.test(v);
3492
+ /**
3493
+ * mysql://user:password@host:port/database?ssl=true (also mariadb://), with
3494
+ * MYSQL_HOST, MYSQL_TCP_PORT, MYSQL_USER, MYSQL_PWD and MYSQL_DATABASE as
3495
+ * fallbacks for anything the URL leaves out.
3496
+ */
3497
+ function parseConnection(connectionString, sslInsecure, env = process.env) {
3498
+ const opts = {
3499
+ host: env.MYSQL_HOST || "localhost",
3500
+ port: Number(env.MYSQL_TCP_PORT || 3306),
3501
+ user: env.MYSQL_USER || env.USER || "root",
3502
+ password: env.MYSQL_PWD || void 0,
3503
+ database: env.MYSQL_DATABASE || void 0
3504
+ };
3505
+ if (connectionString) {
3506
+ let url;
3507
+ try {
3508
+ url = new URL(connectionString);
3509
+ } catch {
3510
+ throw new UserError("The connection string must look like mysql://user:password@host:3306/database");
3511
+ }
3512
+ if (!/^(mysql|mariadb)s?:$/.test(url.protocol)) throw new UserError(`Unsupported scheme "${url.protocol}": use mysql://user:password@host:3306/database`);
3513
+ if (url.hostname) opts.host = decodeURIComponent(url.hostname.replace(/^\[|\]$/g, ""));
3514
+ if (url.port) opts.port = Number(url.port);
3515
+ if (url.username) opts.user = decodeURIComponent(url.username);
3516
+ if (url.password) opts.password = decodeURIComponent(url.password);
3517
+ const db = decodeURIComponent(url.pathname.replace(/^\//, ""));
3518
+ if (db) opts.database = db;
3519
+ const socket = url.searchParams.get("socket") ?? url.searchParams.get("socketPath");
3520
+ if (socket) opts.socketPath = socket;
3521
+ const ssl = url.searchParams.get("ssl") ?? url.searchParams.get("ssl-mode") ?? url.searchParams.get("sslmode");
3522
+ if (truthy(ssl) || url.protocol.endsWith("s:")) opts.ssl = { rejectUnauthorized: !/^(required|require)$/i.test(ssl ?? "") };
3523
+ }
3524
+ if (sslInsecure) opts.ssl = { rejectUnauthorized: false };
3525
+ return opts;
3526
+ }
3527
+ /**
3528
+ * Owns one pool per database on the server, created on first use, so the UI
3529
+ * can switch databases without restarting mysqldeck.
3530
+ */
3531
+ var DatabaseManager = class {
3532
+ config;
3533
+ base;
3534
+ pools = /* @__PURE__ */ new Map();
3535
+ known = null;
3536
+ defaultName = "";
3537
+ constructor(config) {
3538
+ this.config = config;
3539
+ this.base = parseConnection(config.connectionString, config.ssl);
3540
+ }
3541
+ get readonly() {
3542
+ return this.config.readonly;
3543
+ }
3544
+ get defaultDatabase() {
3545
+ return this.defaultName;
3546
+ }
3547
+ /** Where the connection goes, for messages: user@host:port/db. */
3548
+ get target() {
3549
+ const b = this.base;
3550
+ return `${b.user ?? ""}@${b.socketPath ?? `${b.host}:${b.port}`}${b.database ? `/${b.database}` : ""}`;
3551
+ }
3552
+ /**
3553
+ * Connect and fail fast if the server is unreachable. Without a database in
3554
+ * the connection string, the first user database (or `mysql`) is the default.
3555
+ */
3556
+ async connect() {
3557
+ if (this.base.database) {
3558
+ const db = this.open(this.base.database);
3559
+ await db.info();
3560
+ this.defaultName = this.base.database;
3561
+ return db;
3562
+ }
3563
+ const probe = createDatabase({
3564
+ client: {
3565
+ ...this.base,
3566
+ database: void 0
3567
+ },
3568
+ database: "",
3569
+ readonly: true,
3570
+ maxRows: 1
3571
+ });
3572
+ try {
3573
+ const dbs = await probe.listDatabases();
3574
+ this.defaultName = dbs.find((d) => !d.system)?.name ?? dbs.find((d) => d.name === "mysql")?.name ?? dbs[0]?.name ?? "";
3575
+ } finally {
3576
+ await probe.close();
3577
+ }
3578
+ if (!this.defaultName) throw new UserError("This account cannot see any database");
3579
+ const db = this.open(this.defaultName);
3580
+ await db.info();
3581
+ return db;
3582
+ }
3583
+ async list() {
3584
+ const databases = await (await this.get(this.defaultName)).listDatabases();
3585
+ this.known = new Set(databases.map((d) => d.name));
3586
+ return {
3587
+ default: this.defaultName,
3588
+ databases
3589
+ };
3590
+ }
3591
+ /** Get the handle for a database, opening its pool if needed. */
3592
+ async get(name) {
3593
+ const existing = this.pools.get(name);
3594
+ if (existing) {
3595
+ this.pools.delete(name);
3596
+ this.pools.set(name, existing);
3597
+ return existing;
3598
+ }
3599
+ if (name !== this.defaultName) {
3600
+ if (!this.known?.has(name)) await this.list();
3601
+ if (!this.known?.has(name)) throw new UserError(`Database "${name}" does not exist or you cannot see it`, 404);
3602
+ }
3603
+ return this.open(name);
3604
+ }
3605
+ async admin() {
3606
+ if (this.config.readonly) throw new UserError(READONLY_MESSAGE, 403);
3607
+ return this.get(this.defaultName);
3608
+ }
3609
+ async release(name) {
3610
+ const db = this.pools.get(name);
3611
+ if (!db) return;
3612
+ this.pools.delete(name);
3613
+ await db.close().catch(() => {});
3614
+ }
3615
+ async createDb(name, opts) {
3616
+ const admin = await this.admin();
3617
+ let sql = `CREATE DATABASE ${quoteIdent$3(name)}`;
3618
+ if (opts.charset) sql += ` CHARACTER SET ${opts.charset.replace(/\W/g, "")}`;
3619
+ if (opts.collation) sql += ` COLLATE ${opts.collation.replace(/\W/g, "")}`;
3620
+ await admin.exec(sql);
3621
+ this.known = null;
3622
+ return {
3623
+ ok: true,
3624
+ message: `Created database ${name}`
3625
+ };
3626
+ }
3627
+ async dropDb(name) {
3628
+ const admin = await this.admin();
3629
+ if (name === this.defaultName) throw new UserError(`"${name}" is the database mysqldeck connects through, so it can't be dropped from here. Connect mysqldeck to another database first.`, 409);
3630
+ if (SYSTEM_DATABASES.has(name.toLowerCase())) throw new UserError(`${name} is a system database; MySQL needs it.`, 403);
3631
+ await this.release(name);
3632
+ await admin.exec(`DROP DATABASE ${quoteIdent$3(name)}`);
3633
+ this.known = null;
3634
+ return {
3635
+ ok: true,
3636
+ message: `Dropped database ${name}`
3637
+ };
3638
+ }
3639
+ async closeAll() {
3640
+ await Promise.allSettled([...this.pools.values()].map((db) => db.close()));
3641
+ this.pools.clear();
3642
+ }
3643
+ open(name) {
3644
+ const db = createDatabase({
3645
+ client: {
3646
+ ...this.base,
3647
+ database: name
3648
+ },
3649
+ database: name,
3650
+ readonly: this.config.readonly,
3651
+ maxRows: this.config.maxRows
3652
+ });
3653
+ this.pools.set(name, db);
3654
+ this.evict();
3655
+ return db;
3656
+ }
3657
+ evict() {
3658
+ const max = this.config.maxOpenPools ?? 6;
3659
+ for (const [name, db] of this.pools) {
3660
+ if (this.pools.size <= max) break;
3661
+ if (name === this.defaultName) continue;
3662
+ this.pools.delete(name);
3663
+ db.close().catch(() => {});
3664
+ }
3665
+ }
3666
+ };
3667
+ // ../../packages/server/src/auth.ts
3668
+ const loginBody = z.object({
3669
+ username: z.string().min(1).max(256),
3670
+ password: z.string().min(1).max(1024)
3671
+ });
3672
+ function clientKey(c) {
3673
+ const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
3674
+ if (forwarded) return forwarded;
3675
+ try {
3676
+ return getConnInfo(c).remote.address ?? "unknown";
3677
+ } catch {
3678
+ return "unknown";
3679
+ }
3680
+ }
3681
+ const isHttps = (c) => c.req.header("x-forwarded-proto") === "https" || new URL(c.req.url).protocol === "https:";
3682
+ /** Cookie-session auth for the UI's own login page, mounted at /api/auth. */
3683
+ function createAuth({ auth, cookieName: COOKIE }) {
3684
+ const sessions = new SessionStore();
3685
+ const limiter = new LoginLimiter();
3686
+ const currentUser = (c) => auth ? sessions.touch(getCookie(c, COOKIE)) : null;
3687
+ const requireSession = async (c, next) => {
3688
+ if (auth && !currentUser(c)) return c.json({ error: "Not signed in" }, 401);
3689
+ await next();
3690
+ };
3691
+ const routes = new Hono().get("/session", (c) => {
3692
+ const username = currentUser(c);
3693
+ return c.json({
3694
+ authRequired: !!auth,
3695
+ authenticated: !auth || !!username,
3696
+ username
3697
+ });
3698
+ }).post("/login", async (c) => {
3699
+ if (!auth) return c.json({
3700
+ authRequired: false,
3701
+ authenticated: true,
3702
+ username: null
3703
+ });
3704
+ const key = clientKey(c);
3705
+ const wait = limiter.retryAfter(key);
3706
+ if (wait) {
3707
+ c.header("retry-after", String(wait));
3708
+ return c.json({ error: `Too many failed attempts. Try again in ${Math.ceil(wait / 60)} min.` }, 429);
3709
+ }
3710
+ const body = loginBody.safeParse(await c.req.json().catch(() => ({})));
3711
+ if (!body.success) return c.json({ error: `Invalid request: ${z.prettifyError(body.error)}` }, 400);
3712
+ const { username, password } = body.data;
3713
+ const userOk = safeEqual(username, auth.username);
3714
+ const passOk = safeEqual(password, auth.password);
3715
+ if (!userOk || !passOk) {
3716
+ limiter.fail(key);
3717
+ return c.json({ error: "Incorrect username or password" }, 401);
3718
+ }
3719
+ limiter.succeed(key);
3720
+ setCookie(c, COOKIE, sessions.create(username), {
3721
+ httpOnly: true,
3722
+ sameSite: "Strict",
3723
+ secure: isHttps(c),
3724
+ path: "/"
3725
+ });
3726
+ return c.json({
3727
+ authRequired: true,
3728
+ authenticated: true,
3729
+ username
3730
+ });
3731
+ }).post("/logout", (c) => {
3732
+ sessions.revoke(getCookie(c, COOKIE));
3733
+ deleteCookie(c, COOKIE, { path: "/" });
3734
+ return c.json({
3735
+ authRequired: !!auth,
3736
+ authenticated: !auth,
3737
+ username: null
3738
+ });
3739
+ });
3740
+ /** For requests Hono doesn't see (WebSocket upgrades): is this Cookie header signed in? */
3741
+ const authorizeCookieHeader = (cookieHeader) => {
3742
+ if (!auth) return true;
3743
+ return !!sessions.touch(parse$1(cookieHeader ?? "", COOKIE)[COOKIE]);
3744
+ };
3745
+ return {
3746
+ routes,
3747
+ requireSession,
3748
+ authorizeCookieHeader
3749
+ };
3750
+ }
3751
+ // ../../packages/server/src/csrf.ts
3752
+ /**
3753
+ * Require a custom header on API calls. A browser cannot attach one to a
3754
+ * cross-origin request without a CORS preflight, which a deck never
3755
+ * approves, so other sites can't make requests that ride on the session cookie.
3756
+ *
3757
+ * Only exempt read-only GETs: they still can't be triggered cross-site as the
3758
+ * user, because the SameSite=Strict session cookie isn't sent on cross-site
3759
+ * navigations.
3760
+ */
3761
+ function requireCsrfHeader({ header, exempt }) {
3762
+ return async (c, next) => {
3763
+ if (!exempt?.(c) && c.req.header(header) !== "1") return c.json({ error: `Missing ${header} header` }, 403);
3764
+ await next();
3765
+ };
3766
+ }
3767
+ // ../../packages/server/src/static.ts
3768
+ const MIME = {
3769
+ ".html": "text/html; charset=utf-8",
3770
+ ".js": "text/javascript; charset=utf-8",
3771
+ ".css": "text/css; charset=utf-8",
3772
+ ".svg": "image/svg+xml",
3773
+ ".png": "image/png",
3774
+ ".ico": "image/x-icon",
3775
+ ".json": "application/json",
3776
+ ".woff2": "font/woff2",
3777
+ ".woff": "font/woff",
3778
+ ".map": "application/json"
3779
+ };
3780
+ /** Load the built UI into memory. It is small, and this avoids any path traversal surface. */
3781
+ function loadAssets(root) {
3782
+ if (!fs.existsSync(path.join(root, "index.html"))) return null;
3783
+ const assets = /* @__PURE__ */ new Map();
3784
+ for (const rel of fs.readdirSync(root, {
3785
+ recursive: true,
3786
+ encoding: "utf8"
3787
+ })) {
3788
+ const abs = path.join(root, rel);
3789
+ if (!fs.statSync(abs).isFile()) continue;
3790
+ assets.set("/" + rel.split(path.sep).join("/"), {
3791
+ body: new Uint8Array(fs.readFileSync(abs)),
3792
+ type: MIME[path.extname(rel)] ?? "application/octet-stream"
3793
+ });
3794
+ }
3795
+ return assets;
3796
+ }
3797
+ function serveAssets(assets, { name, csp = contentSecurityPolicy() }) {
3798
+ return async (c) => {
3799
+ if (!assets) return c.text(`${name} UI is not built. Run "pnpm build", or use "pnpm dev" during development.`, 503);
3800
+ const p = c.req.path === "/" ? "/index.html" : c.req.path;
3801
+ const asset = assets.get(p);
3802
+ if (!asset) return c.json({ error: "Not found" }, 404);
3803
+ c.header("content-type", asset.type);
3804
+ c.header("x-content-type-options", "nosniff");
3805
+ if (p === "/index.html") {
3806
+ c.header("cache-control", "no-store");
3807
+ c.header("content-security-policy", csp);
3808
+ c.header("referrer-policy", "no-referrer");
3809
+ } else if (p.startsWith("/assets/")) c.header("cache-control", "public, max-age=31536000, immutable");
3810
+ return c.body(asset.body);
3811
+ };
3812
+ }
3813
+ // ../../packages/server/src/app.ts
3814
+ const ADD_SLASH = "/__deck_add_slash";
3815
+ const OUTSIDE_BASE = "/__deck_outside_base";
3816
+ /**
3817
+ * The HTTP app every deck shares:
3818
+ *
3819
+ * /healthz liveness probe
3820
+ * /api/auth/* login, logout, session (CSRF-checked, public)
3821
+ * /api/* the tool's API (CSRF-checked, needs a session)
3822
+ * everything else the built UI
3823
+ *
3824
+ * all of it optionally under a base path.
3825
+ */
3826
+ function createDeckApp({ name, auth, basePath, webRoot, cookieName, csrf, api, mapError, csp }) {
3827
+ const log = createLogger(name);
3828
+ const app = new Hono({ getPath: (req) => {
3829
+ const pathname = new URL(req.url).pathname;
3830
+ if (!basePath) return pathname;
3831
+ if (pathname === basePath) return ADD_SLASH;
3832
+ if (!pathname.startsWith(basePath + "/")) return OUTSIDE_BASE;
3833
+ return pathname.slice(basePath.length);
3834
+ } });
3835
+ const onError = async (err, c) => {
3836
+ if (err instanceof HTTPException) return err.getResponse();
3837
+ const mapped = await mapError?.(err, c);
3838
+ if (mapped) return mapped;
3839
+ log.error(err);
3840
+ return c.json({ error: err.message || "Internal error" }, 500);
3841
+ };
3842
+ app.onError(onError);
3843
+ app.get(ADD_SLASH, (c) => c.redirect(`${basePath}/${new URL(c.req.url).search}`, 301));
3844
+ app.all(OUTSIDE_BASE, (c) => c.json({ error: "Not found" }, 404));
3845
+ app.get("/healthz", (c) => c.json({ ok: true }));
3846
+ const { routes: authRoutes, requireSession, authorizeCookieHeader } = createAuth({
3847
+ auth,
3848
+ cookieName
3849
+ });
3850
+ app.use("/api/*", requireCsrfHeader(csrf));
3851
+ app.route("/api/auth", authRoutes);
3852
+ app.use("/api/*", requireSession);
3853
+ app.route("/api", api);
3854
+ app.all("/api/*", (c) => c.json({ error: "Not found" }, 404));
3855
+ app.get("*", serveAssets(loadAssets(webRoot), {
3856
+ name,
3857
+ csp
3858
+ }));
3859
+ return {
3860
+ app,
3861
+ authorizeCookieHeader
3862
+ };
3863
+ }
3864
+ // ../../packages/server/src/listen.ts
3865
+ /** Start listening (HTTP + optional WebSocket upgrades). Resolves once the port is bound. */
3866
+ function listen({ fetch, port, host, onUpgrade, onClose }) {
3867
+ return new Promise((resolve, reject) => {
3868
+ const server = serve({
3869
+ fetch,
3870
+ port,
3871
+ hostname: host
3872
+ }, (info) => {
3873
+ server.off("error", reject);
3874
+ resolve({
3875
+ server,
3876
+ port: info.port,
3877
+ close: () => {
3878
+ onClose?.();
3879
+ server.close();
3880
+ }
3881
+ });
3882
+ });
3883
+ server.requestTimeout = 0;
3884
+ server.on("upgrade", (req, socket, head) => {
3885
+ if (!onUpgrade?.(req, socket, head)) socket.destroy();
3886
+ });
3887
+ server.once("error", reject);
3888
+ });
3889
+ }
3890
+ // src/server/middleware/errors.ts
3891
+ /** Errors that mean "fix your request/SQL", not "mysqldeck is broken". */
3892
+ const isServerError = (e) => typeof e.errno === "number" && typeof e.sqlState === "string";
3893
+ /** Connection-level problems: worth showing, but they're about reaching MySQL. */
3894
+ const CONNECTION_CODES = /* @__PURE__ */ new Set([
3895
+ "ECONNREFUSED",
3896
+ "ENOTFOUND",
3897
+ "ETIMEDOUT",
3898
+ "PROTOCOL_CONNECTION_LOST",
3899
+ "ECONNRESET"
3900
+ ]);
3901
+ const HINTS = {
3902
+ 1045: "Check the user name and password in the connection string.",
3903
+ 1142: "The account mysqldeck connects as lacks this privilege.",
3904
+ 1227: "The account mysqldeck connects as lacks this privilege.",
3905
+ 1451: "Other rows reference this one through a foreign key. Delete or change those first.",
3906
+ 1452: "The value must match an existing row in the referenced table.",
3907
+ 1792: "mysqldeck is running in --readonly mode."
3908
+ };
3909
+ /** Map mysqldeck's own and MySQL's errors to responses; anything else becomes a logged 500. */
3910
+ function mapError(err, c) {
3911
+ if (err instanceof UserError) return c.json({ error: err.message }, err.status);
3912
+ const e = err;
3913
+ if (isServerError(e)) return c.json({
3914
+ error: e.sqlMessage ?? e.message,
3915
+ detail: e.detail,
3916
+ hint: HINTS[e.errno],
3917
+ position: e.position === void 0 ? void 0 : String(e.position),
3918
+ code: `${e.code ?? "ER"} (${e.errno})`
3919
+ }, 400);
3920
+ if (e.code && CONNECTION_CODES.has(e.code)) return c.json({
3921
+ error: `Lost the connection to MySQL: ${e.message}`,
3922
+ code: e.code
3923
+ }, 502);
3924
+ }
3925
+ // src/server/schemas.ts
3926
+ const ident = z.string().min(1).max(256);
3927
+ const cell = z.string().nullable();
3928
+ const cellRecord = z.record(z.string(), cell);
3929
+ const tableRef = z.object({
3930
+ schema: ident,
3931
+ table: ident
3932
+ });
3933
+ const metaQuery = tableRef;
3934
+ const rowsBody = tableRef.extend({
3935
+ limit: z.number().int().min(1).max(1e5).default(100),
3936
+ offset: z.number().int().min(0).default(0),
3937
+ sort: ident.optional(),
3938
+ dir: z.enum(["asc", "desc"]).optional(),
3939
+ filters: z.array(z.object({
3940
+ col: ident,
3941
+ op: z.enum(FILTER_OPS),
3942
+ val: z.string().optional()
3943
+ })).max(50).default([]),
3944
+ match: z.enum(["and", "or"]).default("and")
3945
+ });
3946
+ /** A JSON-encoded value inside a query-string parameter. */
3947
+ const jsonParam = (inner, fallback) => z.string().default(fallback).transform((s, ctx) => {
3948
+ try {
3949
+ return JSON.parse(s);
3950
+ } catch {
3951
+ ctx.addIssue({
3952
+ code: "custom",
3953
+ message: "must be JSON"
3954
+ });
3955
+ return z.NEVER;
3956
+ }
3957
+ }).pipe(inner);
3958
+ const flag = z.enum(["0", "1"]).default("0").transform((v) => v === "1");
3959
+ const flagOn = z.enum(["0", "1"]).default("1").transform((v) => v === "1");
3960
+ /** GET /export: everything is in the query string so a plain download link works. */
3961
+ const exportQuery = tableRef.extend({
3962
+ format: z.enum(EXPORT_FORMATS),
3963
+ filters: jsonParam(rowsBody.shape.filters, "[]"),
3964
+ match: z.enum(["and", "or"]).default("and"),
3965
+ sort: ident.optional(),
3966
+ dir: z.enum(["asc", "desc"]).optional()
3967
+ });
3968
+ /** GET /dump: database export as one .sql file or a ZIP of per-table files. */
3969
+ const dumpQuery = z.object({
3970
+ tables: jsonParam(z.array(z.object({
3971
+ schema: ident,
3972
+ table: ident
3973
+ })).max(1e4), "[]"),
3974
+ structure: flag,
3975
+ data: flag,
3976
+ gzip: flag,
3977
+ format: z.enum(["sql", "zip"]).default("sql"),
3978
+ dataFormat: z.enum(EXPORT_FORMATS).default("csv")
3979
+ });
3980
+ /** POST /table-action */
3981
+ const tableActionBody = z.object({
3982
+ schema: ident,
3983
+ table: ident,
3984
+ action: z.discriminatedUnion("action", [
3985
+ z.object({
3986
+ action: z.literal("truncate"),
3987
+ ignoreForeignKeys: z.boolean().default(false)
3988
+ }),
3989
+ z.object({
3990
+ action: z.literal("drop"),
3991
+ ignoreForeignKeys: z.boolean().default(false)
3992
+ }),
3993
+ z.object({
3994
+ action: z.literal("rename"),
3995
+ newName: z.string().min(1).max(64)
3996
+ }),
3997
+ z.object({
3998
+ action: z.literal("duplicate"),
3999
+ newName: z.string().min(1).max(64),
4000
+ withData: z.boolean().default(false)
4001
+ }),
4002
+ z.object({ action: z.literal("optimize") }),
4003
+ z.object({ action: z.literal("analyze") }),
4004
+ z.object({ action: z.literal("check") }),
4005
+ z.object({
4006
+ action: z.literal("resetAutoIncrement"),
4007
+ value: z.number().int().min(1)
4008
+ })
4009
+ ])
4010
+ });
4011
+ const fkAction = z.enum(FK_ACTIONS);
4012
+ const explainBody = z.object({
4013
+ sql: z.string().min(1).max(1e6),
4014
+ analyze: z.boolean().default(false)
4015
+ });
4016
+ const statementsQuery = z.object({
4017
+ sort: z.enum([
4018
+ "total",
4019
+ "mean",
4020
+ "calls",
4021
+ "rows"
4022
+ ]).default("total"),
4023
+ limit: z.coerce.number().int().min(1).max(200).default(50)
4024
+ });
4025
+ const signalBody = z.object({
4026
+ pid: z.number().int().positive(),
4027
+ terminate: z.boolean().default(false)
4028
+ });
4029
+ const objectName = z.string().min(1).max(64);
4030
+ const objectQuery = z.object({
4031
+ kind: z.enum(OBJECT_KINDS),
4032
+ name: objectName
4033
+ });
4034
+ const objectActionBody = z.union([
4035
+ z.object({
4036
+ kind: z.enum(OBJECT_KINDS),
4037
+ name: objectName,
4038
+ action: z.literal("replace"),
4039
+ sql: z.string().min(1).max(1e6)
4040
+ }),
4041
+ z.object({
4042
+ kind: z.enum(OBJECT_KINDS),
4043
+ name: objectName,
4044
+ action: z.literal("drop")
4045
+ }),
4046
+ z.object({
4047
+ kind: z.literal("event"),
4048
+ name: objectName,
4049
+ action: z.enum(["enable", "disable"])
4050
+ })
4051
+ ]);
4052
+ /** POST /maintenance: ANALYZE / OPTIMIZE / CHECK many tables. */
4053
+ const maintenanceBody = z.object({
4054
+ action: z.enum([
4055
+ "analyze",
4056
+ "optimize",
4057
+ "check"
4058
+ ]),
4059
+ tables: z.array(tableRef).min(1).max(1e4)
4060
+ });
4061
+ const newColumn = z.object({
4062
+ name: z.string().min(1).max(64),
4063
+ type: z.string().min(1).max(4096),
4064
+ nullable: z.boolean().default(true),
4065
+ primaryKey: z.boolean().default(false),
4066
+ unique: z.boolean().default(false),
4067
+ identity: z.boolean().default(false),
4068
+ default: z.string().max(1e4).default(""),
4069
+ references: z.object({
4070
+ schema: ident,
4071
+ table: ident,
4072
+ column: ident,
4073
+ onDelete: fkAction.default("NO ACTION"),
4074
+ onUpdate: fkAction.default("NO ACTION")
4075
+ }).nullable().default(null),
4076
+ comment: z.string().max(1024).default("")
4077
+ });
4078
+ /** POST /create-table */
4079
+ const createTableBody = z.object({
4080
+ schema: ident,
4081
+ name: z.string().min(1).max(64),
4082
+ comment: z.string().max(2048).default(""),
4083
+ engine: z.string().max(64).default("InnoDB"),
4084
+ collation: z.string().max(64).default(""),
4085
+ columns: z.array(newColumn).min(1).max(4096)
4086
+ });
4087
+ /** POST /alter: one Structure-tab change. */
4088
+ const alterBody = tableRef.extend({ change: z.discriminatedUnion("action", [
4089
+ z.object({
4090
+ action: z.literal("addColumn"),
4091
+ column: newColumn
4092
+ }),
4093
+ z.object({
4094
+ action: z.literal("alterColumn"),
4095
+ column: ident,
4096
+ newName: z.string().max(64).optional(),
4097
+ type: z.string().min(1).max(4096).optional(),
4098
+ nullable: z.boolean().optional(),
4099
+ default: z.string().max(1e4).nullable().optional(),
4100
+ comment: z.string().max(1024).nullable().optional()
4101
+ }),
4102
+ z.object({
4103
+ action: z.literal("dropColumn"),
4104
+ column: ident
4105
+ }),
4106
+ z.object({
4107
+ action: z.literal("createIndex"),
4108
+ name: z.string().max(64).default(""),
4109
+ columns: z.array(z.object({
4110
+ name: ident,
4111
+ desc: z.boolean().default(false),
4112
+ length: z.number().int().min(1).max(3072).nullable().optional()
4113
+ })).min(1).max(16),
4114
+ unique: z.boolean().default(false),
4115
+ method: z.enum(INDEX_METHODS).default("btree"),
4116
+ online: z.boolean().default(false)
4117
+ }),
4118
+ z.object({
4119
+ action: z.literal("dropIndex"),
4120
+ name: ident
4121
+ }),
4122
+ z.object({
4123
+ action: z.literal("dropConstraint"),
4124
+ name: ident,
4125
+ type: z.enum([
4126
+ "p",
4127
+ "u",
4128
+ "f",
4129
+ "c"
4130
+ ])
4131
+ })
4132
+ ]) });
4133
+ const dbName = z.string().min(1).max(64);
4134
+ /** POST /databases */
4135
+ const createDatabaseBody = z.object({
4136
+ name: dbName,
4137
+ charset: z.string().max(64).optional(),
4138
+ collation: z.string().max(64).optional()
4139
+ });
4140
+ /** POST /databases/action */
4141
+ const databaseActionBody = z.object({
4142
+ action: z.literal("drop"),
4143
+ name: dbName
4144
+ });
4145
+ /** POST /restore: run an uploaded dump. */
4146
+ const restoreQuery = z.object({
4147
+ gzip: flag,
4148
+ single: flag,
4149
+ skipOwnership: flagOn
4150
+ });
4151
+ /** POST /import: options in the query string, the raw file is the body. */
4152
+ const importQuery = tableRef.extend({
4153
+ format: z.enum(IMPORT_FORMATS),
4154
+ columns: jsonParam(z.array(ident).min(1).max(4096), "[]"),
4155
+ keys: jsonParam(z.array(z.string().max(1024)).max(4096), "[]"),
4156
+ header: flag,
4157
+ delimiter: z.string().min(1).max(1).default(","),
4158
+ gzip: flag,
4159
+ truncate: flag
4160
+ });
4161
+ const insertBody = tableRef.extend({ values: cellRecord });
4162
+ const updateBody = tableRef.extend({
4163
+ key: cellRecord,
4164
+ values: cellRecord
4165
+ });
4166
+ const deleteBody = tableRef.extend({ keys: z.array(cellRecord).min(1).max(1e4) });
4167
+ const queryBody = z.object({ sql: z.string().min(1).max(5e6) });
4168
+ const userName = z.string().min(1).max(32);
4169
+ const hostName = z.string().min(1).max(255);
4170
+ const account = z.object({
4171
+ user: userName,
4172
+ host: hostName
4173
+ });
4174
+ const userQuery = account;
4175
+ /** POST /user-action */
4176
+ const userActionBody = z.discriminatedUnion("action", [
4177
+ z.object({
4178
+ action: z.literal("create"),
4179
+ user: userName,
4180
+ host: hostName,
4181
+ password: z.string().max(1024).default(""),
4182
+ plugin: z.string().max(64).default(""),
4183
+ role: z.boolean().default(false),
4184
+ roles: z.array(account).max(100).default([])
4185
+ }),
4186
+ z.object({
4187
+ action: z.literal("update"),
4188
+ user: userName,
4189
+ host: hostName,
4190
+ newUser: userName.optional(),
4191
+ newHost: hostName.optional(),
4192
+ password: z.string().max(1024).optional(),
4193
+ locked: z.boolean().optional(),
4194
+ expirePassword: z.boolean().optional(),
4195
+ maxUserConnections: z.number().int().min(0).max(0xffffffff).optional()
4196
+ }),
4197
+ z.object({
4198
+ action: z.literal("drop"),
4199
+ user: userName,
4200
+ host: hostName
4201
+ }),
4202
+ z.object({
4203
+ action: z.literal("membership"),
4204
+ user: userName,
4205
+ host: hostName,
4206
+ role: account,
4207
+ grant: z.boolean()
4208
+ })
4209
+ ]);
4210
+ /** POST /grants */
4211
+ const grantsBody = z.object({
4212
+ account,
4213
+ changes: z.array(z.object({
4214
+ level: z.enum([
4215
+ "global",
4216
+ "database",
4217
+ "table"
4218
+ ]),
4219
+ db: ident.optional(),
4220
+ table: ident.optional(),
4221
+ privilege: z.string().regex(/^[A-Z][A-Z_ ]*$/),
4222
+ grant: z.boolean()
4223
+ })).min(1).max(2e4)
4224
+ });
4225
+ /** POST /database-preset */
4226
+ const databasePresetBody = z.object({
4227
+ account,
4228
+ db: dbName,
4229
+ preset: z.enum([
4230
+ "read",
4231
+ "write",
4232
+ "all",
4233
+ "none"
4234
+ ])
4235
+ });
4236
+ /** Validate input, turning schema failures into a 400 the UI can display. */
4237
+ function parse(schema, input) {
4238
+ const result = schema.safeParse(input);
4239
+ if (!result.success) throw new UserError(`Invalid request: ${z.prettifyError(result.error)}`);
4240
+ return result.data;
4241
+ }
4242
+ // src/server/routes/api.ts
4243
+ async function jsonBody(req) {
4244
+ try {
4245
+ return await req.json();
4246
+ } catch {
4247
+ throw new UserError("Request body must be JSON");
4248
+ }
4249
+ }
4250
+ /** Routes that operate on one database, mounted at /api/db/:database. */
4251
+ function databaseRoutes() {
4252
+ return new Hono().get("/info", async (c) => c.json(await c.var.db.info())).get("/tables", async (c) => c.json(await c.var.db.tables())).get("/stats", async (c) => c.json(await c.var.db.stats())).get("/meta", async (c) => {
4253
+ const { schema, table } = parse(metaQuery, c.req.query());
4254
+ return c.json(await c.var.db.meta(schema, table));
4255
+ }).post("/rows", async (c) => {
4256
+ const body = parse(rowsBody, await jsonBody(c.req));
4257
+ return c.json(await c.var.db.rows(body));
4258
+ }).post("/insert", async (c) => {
4259
+ const { schema, table, values } = parse(insertBody, await jsonBody(c.req));
4260
+ return c.json(await c.var.db.insert(schema, table, values));
4261
+ }).post("/update", async (c) => {
4262
+ const { schema, table, key, values } = parse(updateBody, await jsonBody(c.req));
4263
+ return c.json(await c.var.db.update(schema, table, key, values));
4264
+ }).post("/delete", async (c) => {
4265
+ const { schema, table, keys } = parse(deleteBody, await jsonBody(c.req));
4266
+ return c.json(await c.var.db.remove(schema, table, keys));
4267
+ }).get("/export", async (c) => {
4268
+ const q = parse(exportQuery, c.req.query());
4269
+ const meta = EXPORT_META[q.format];
4270
+ const name = `${q.table}.${meta.ext}`;
4271
+ const ac = new AbortController();
4272
+ const chunks = c.var.db.exportRows(q, ac.signal);
4273
+ const first = await chunks.next();
4274
+ c.header("content-type", `${meta.mime}; charset=utf-8`);
4275
+ c.header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(name)}`);
4276
+ c.header("cache-control", "no-store");
4277
+ c.header("x-content-type-options", "nosniff");
4278
+ return stream(c, async (s) => {
4279
+ s.onAbort(() => ac.abort());
4280
+ if (!first.done && first.value) await s.write(first.value);
4281
+ for await (const chunk of chunks) if (chunk) await s.write(chunk);
4282
+ });
4283
+ }).get("/dump", async (c) => {
4284
+ const q = parse(dumpQuery, c.req.query());
4285
+ const info = await c.var.db.info();
4286
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace(/[:T]/g, "-");
4287
+ const base = `${info.database}_${stamp}`;
4288
+ const dumpOpts = {
4289
+ tables: q.tables,
4290
+ structure: q.structure,
4291
+ data: q.data
4292
+ };
4293
+ let body;
4294
+ let name;
4295
+ let type;
4296
+ if (q.format === "zip") {
4297
+ const zip = new yazl.ZipFile();
4298
+ if (q.structure) zip.addReadStreamLazy("schema.sql", (cb) => cb(null, Readable.from(c.var.db.dumpSql({
4299
+ ...dumpOpts,
4300
+ data: false
4301
+ }))));
4302
+ if (q.data) {
4303
+ const tables = q.tables.length ? q.tables : (await c.var.db.tables()).filter((t) => t.kind === "r").map((t) => ({
4304
+ schema: t.schema,
4305
+ table: t.name
4306
+ }));
4307
+ const ext = EXPORT_META[q.dataFormat].ext;
4308
+ for (const t of tables) zip.addReadStreamLazy(`data/${t.table}.${ext}`, (cb) => cb(null, Readable.from(c.var.db.exportRows({
4309
+ schema: t.schema,
4310
+ table: t.table,
4311
+ format: q.dataFormat
4312
+ }))));
4313
+ }
4314
+ zip.end();
4315
+ body = zip.outputStream;
4316
+ name = `${base}.zip`;
4317
+ type = "application/zip";
4318
+ } else {
4319
+ const chunks = c.var.db.dumpSql(dumpOpts);
4320
+ const first = await chunks.next();
4321
+ const all = (async function* () {
4322
+ if (!first.done) yield first.value;
4323
+ yield* chunks;
4324
+ })();
4325
+ body = Readable.from(all);
4326
+ name = `${base}.sql${q.gzip ? ".gz" : ""}`;
4327
+ type = q.gzip ? "application/gzip" : "application/sql; charset=utf-8";
4328
+ if (q.gzip) body = body.pipe(createGzip());
4329
+ }
4330
+ return new Response(Readable.toWeb(body), { headers: {
4331
+ "content-type": type,
4332
+ "content-disposition": `attachment; filename="${name.replace(/[^\w.-]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(name)}`,
4333
+ "cache-control": "no-store",
4334
+ "x-content-type-options": "nosniff"
4335
+ } });
4336
+ }).post("/restore", async (c) => {
4337
+ const q = parse(restoreQuery, c.req.query());
4338
+ const body = c.req.raw.body;
4339
+ if (!body) throw new UserError("The upload is empty");
4340
+ const stream = Readable.fromWeb(body);
4341
+ return c.json(await c.var.db.restore(stream, {
4342
+ gzip: q.gzip,
4343
+ singleTransaction: q.single,
4344
+ skipOwnership: q.skipOwnership
4345
+ }));
4346
+ }).post("/import", async (c) => {
4347
+ const q = parse(importQuery, c.req.query());
4348
+ const body = c.req.raw.body;
4349
+ if (!body) throw new UserError("The upload is empty");
4350
+ return c.json(await c.var.db.importRows(q, Readable.fromWeb(body)));
4351
+ }).post("/table-action", async (c) => {
4352
+ const { schema, table, action } = parse(tableActionBody, await jsonBody(c.req));
4353
+ return c.json(await c.var.db.tableAction(schema, table, action));
4354
+ }).get("/ddl", async (c) => {
4355
+ const { schema, table } = parse(metaQuery, c.req.query());
4356
+ return c.json({ sql: await c.var.db.ddl(schema, table) });
4357
+ }).post("/create-table", async (c) => {
4358
+ const spec = parse(createTableBody, await jsonBody(c.req));
4359
+ return c.json(await c.var.db.createTable(spec));
4360
+ }).post("/maintenance", async (c) => {
4361
+ const { action, tables } = parse(maintenanceBody, await jsonBody(c.req));
4362
+ return c.json(await c.var.db.maintenance(action, tables));
4363
+ }).post("/alter", async (c) => {
4364
+ const { schema, table, change } = parse(alterBody, await jsonBody(c.req));
4365
+ return c.json(await c.var.db.alter(schema, table, change));
4366
+ }).post("/explain", async (c) => {
4367
+ const { sql, analyze } = parse(explainBody, await jsonBody(c.req));
4368
+ return c.json(await c.var.db.explain(sql, analyze));
4369
+ }).get("/statements", async (c) => {
4370
+ const { sort, limit } = parse(statementsQuery, c.req.query());
4371
+ return c.json(await c.var.db.statements(sort, limit));
4372
+ }).post("/statements/enable", async (c) => c.json(await c.var.db.enableStatements())).post("/statements/reset", async (c) => c.json(await c.var.db.resetStatements())).post("/sessions/signal", async (c) => {
4373
+ const { pid, terminate } = parse(signalBody, await jsonBody(c.req));
4374
+ return c.json(await c.var.db.signalSession(pid, terminate));
4375
+ }).get("/objects", async (c) => c.json(await c.var.db.objects())).get("/object", async (c) => {
4376
+ const { kind, name } = parse(objectQuery, c.req.query());
4377
+ return c.json(await c.var.db.object(kind, name));
4378
+ }).post("/object-action", async (c) => c.json(await c.var.db.objectAction(parse(objectActionBody, await jsonBody(c.req))))).get("/users", async (c) => c.json(await c.var.db.users())).get("/user", async (c) => c.json(await c.var.db.user(parse(userQuery, c.req.query())))).post("/user-action", async (c) => c.json(await c.var.db.userAction(parse(userActionBody, await jsonBody(c.req))))).post("/grants", async (c) => {
4379
+ const { account, changes } = parse(grantsBody, await jsonBody(c.req));
4380
+ return c.json(await c.var.db.grants(account, changes));
4381
+ }).post("/database-preset", async (c) => {
4382
+ const { account, db, preset } = parse(databasePresetBody, await jsonBody(c.req));
4383
+ return c.json(await c.var.db.databasePreset(account, db, preset));
4384
+ }).get("/graph", async (c) => c.json(await c.var.db.graph())).get("/catalog", async (c) => c.json(await c.var.db.catalog())).post("/query", async (c) => {
4385
+ const { sql } = parse(queryBody, await jsonBody(c.req));
4386
+ return c.json(await c.var.db.query(sql));
4387
+ });
4388
+ }
4389
+ function apiRoutes(manager) {
4390
+ const perDb = new Hono().use("*", async (c, next) => {
4391
+ c.set("db", await manager.get(c.req.param("database") ?? ""));
4392
+ await next();
4393
+ }).route("/", databaseRoutes());
4394
+ return new Hono().get("/databases", async (c) => c.json(await manager.list())).post("/databases", async (c) => {
4395
+ const { name, charset, collation } = parse(createDatabaseBody, await jsonBody(c.req));
4396
+ return c.json(await manager.createDb(name, {
4397
+ charset,
4398
+ collation
4399
+ }));
4400
+ }).post("/databases/action", async (c) => {
4401
+ const a = parse(databaseActionBody, await jsonBody(c.req));
4402
+ return c.json(await manager.dropDb(a.name));
4403
+ }).route("/db/:database", perDb);
4404
+ }
4405
+ // src/server/app.ts
4406
+ /** Session cookie, CSRF header: part of the contract with existing browsers and the UI. */
4407
+ const SESSION_COOKIE = "mysqldeck_session";
4408
+ const CSRF_HEADER = "x-mysqldeck";
4409
+ const isExport = (method, path) => method === "GET" && /^\/api\/db\/[^/]+\/(export|dump)$/.test(path);
4410
+ function createApp({ manager, auth, basePath, webRoot }) {
4411
+ return createDeckApp({
4412
+ name: "mysqldeck",
4413
+ auth,
4414
+ basePath,
4415
+ webRoot,
4416
+ cookieName: SESSION_COOKIE,
4417
+ csrf: {
4418
+ header: CSRF_HEADER,
4419
+ exempt: (c) => isExport(c.req.method, c.req.path)
4420
+ },
4421
+ api: apiRoutes(manager),
4422
+ mapError
4423
+ });
4424
+ }
4425
+ // src/server/live.ts
4426
+ const INTERVAL_MS = 2e3;
4427
+ const LIVE_PATH = /^\/api\/db\/([^/]+)\/live$/;
4428
+ /**
4429
+ * Pushes live database metrics over WebSockets at /api/db/<name>/live.
4430
+ * One sampler per database is shared by all its viewers and stops when the
4431
+ * last one disconnects.
4432
+ */
4433
+ function createLiveHub({ manager, basePath, authorizeCookieHeader }) {
4434
+ const wss = new WebSocketServer({
4435
+ noServer: true,
4436
+ maxPayload: 4096
4437
+ });
4438
+ const channels = /* @__PURE__ */ new Map();
4439
+ const send = (ws, msg) => {
4440
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg));
4441
+ };
4442
+ async function join(dbName, ws) {
4443
+ let channel = channels.get(dbName);
4444
+ if (!channel) {
4445
+ let sample = (await manager.get(dbName)).liveSampler();
4446
+ const clients = /* @__PURE__ */ new Set();
4447
+ let busy = false;
4448
+ const tick = async () => {
4449
+ if (busy) return;
4450
+ busy = true;
4451
+ try {
4452
+ const msg = JSON.stringify(await sample());
4453
+ for (const c of clients) if (c.readyState === c.OPEN) c.send(msg);
4454
+ } catch (err) {
4455
+ if (/pool is closed/i.test(err.message)) {
4456
+ sample = await manager.get(dbName).then((db) => db.liveSampler()).catch(() => sample);
4457
+ return;
4458
+ }
4459
+ const msg = {
4460
+ type: "error",
4461
+ error: err.message
4462
+ };
4463
+ for (const c of clients) send(c, msg);
4464
+ } finally {
4465
+ busy = false;
4466
+ }
4467
+ };
4468
+ channel = {
4469
+ clients,
4470
+ timer: setInterval(tick, INTERVAL_MS)
4471
+ };
4472
+ channels.set(dbName, channel);
4473
+ clients.add(ws);
4474
+ tick();
4475
+ } else channel.clients.add(ws);
4476
+ ws.on("close", () => {
4477
+ const ch = channels.get(dbName);
4478
+ if (!ch) return;
4479
+ ch.clients.delete(ws);
4480
+ if (!ch.clients.size) {
4481
+ clearInterval(ch.timer);
4482
+ channels.delete(dbName);
4483
+ }
4484
+ });
4485
+ }
4486
+ /** Browsers don't preflight WebSockets, so check Origin to stop cross-site use of the cookie. */
4487
+ function sameOrigin(req) {
4488
+ const origin = req.headers.origin;
4489
+ if (!origin) return true;
4490
+ const host = req.headers["x-forwarded-host"]?.split(",")[0]?.trim() ?? req.headers.host;
4491
+ try {
4492
+ return new URL(origin).host === host;
4493
+ } catch {
4494
+ return false;
4495
+ }
4496
+ }
4497
+ function reject(socket, status, text) {
4498
+ socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
4499
+ }
4500
+ /** Handle an HTTP upgrade. Returns false if the path isn't ours. */
4501
+ function handleUpgrade(req, socket, head) {
4502
+ let pathname = new URL(req.url ?? "/", "http://local").pathname;
4503
+ if (basePath && pathname.startsWith(basePath + "/")) pathname = pathname.slice(basePath.length);
4504
+ const match = LIVE_PATH.exec(pathname);
4505
+ if (!match) return false;
4506
+ if (!sameOrigin(req)) {
4507
+ reject(socket, 403, "Forbidden");
4508
+ return true;
4509
+ }
4510
+ if (!authorizeCookieHeader(req.headers.cookie)) {
4511
+ reject(socket, 401, "Unauthorized");
4512
+ return true;
4513
+ }
4514
+ const dbName = decodeURIComponent(match[1]);
4515
+ wss.handleUpgrade(req, socket, head, (ws) => {
4516
+ join(dbName, ws).catch((err) => {
4517
+ send(ws, {
4518
+ type: "error",
4519
+ error: err.message
4520
+ });
4521
+ ws.close(1011, "unavailable");
4522
+ });
4523
+ });
4524
+ return true;
4525
+ }
4526
+ function close() {
4527
+ for (const ch of channels.values()) clearInterval(ch.timer);
4528
+ channels.clear();
4529
+ for (const ws of wss.clients) ws.terminate();
4530
+ wss.close();
4531
+ }
4532
+ return {
4533
+ handleUpgrade,
4534
+ close
4535
+ };
4536
+ }
4537
+ // src/server/index.ts
4538
+ /** Start listening (HTTP + live WebSocket). Resolves once the port is bound. */
4539
+ function startServer({ port, host, ...appOptions }) {
4540
+ const { app, authorizeCookieHeader } = createApp(appOptions);
4541
+ const live = createLiveHub({
4542
+ manager: appOptions.manager,
4543
+ basePath: appOptions.basePath,
4544
+ authorizeCookieHeader
4545
+ });
4546
+ return listen({
4547
+ fetch: app.fetch,
4548
+ port,
4549
+ host,
4550
+ onUpgrade: live.handleUpgrade,
4551
+ onClose: live.close
4552
+ });
4553
+ }
4554
+ // src/cli/banner.ts
4555
+ function printBanner(version, config, info, databaseCount, url, port) {
4556
+ const serverVersion = `${info.flavor} ${info.version.split("-")[0]}`;
4557
+ printBanner$1({
4558
+ name: "mysqldeck",
4559
+ version,
4560
+ server: config,
4561
+ url,
4562
+ port,
4563
+ resource: "database",
4564
+ before: [` ${symbols.ok} ${label("Connected")}${colors.bold(info.database)} as ${info.user} ${colors.dim(`(${serverVersion})`)}`, ` ${label("Databases")}${databaseCount} available ${colors.dim("(switch in the UI)")}`],
4565
+ after: config.readonly ? [` ${label("Mode")}${colors.yellow("read-only")}`] : []
4566
+ });
4567
+ }
4568
+ // src/cli/config.ts
4569
+ /** Locate the built UI: next to the bundled CLI in dist/, or dist/web when run from source. */
4570
+ const resolveWebRoot = () => firstExistingDir([new URL("./web", import.meta.url), new URL("../../dist/web", import.meta.url)]);
4571
+ function resolveConfig(connectionArg, opts) {
4572
+ return {
4573
+ connectionString: connectionArg ?? process.env.MYSQL_URL ?? process.env.DATABASE_URL ?? "",
4574
+ port: opts.port,
4575
+ host: opts.host,
4576
+ auth: resolveAuth({
4577
+ enabled: opts.auth,
4578
+ username: opts.user,
4579
+ password: opts.password,
4580
+ passwordEnv: "MYSQLDECK_PASSWORD"
4581
+ }),
4582
+ readonly: opts.readonly,
4583
+ ssl: opts.ssl,
4584
+ basePath: normalizeBasePath(opts.basePath),
4585
+ maxRows: opts.maxRows,
4586
+ open: opts.open,
4587
+ webRoot: resolveWebRoot()
4588
+ };
4589
+ }
4590
+ /** Hide the password in a connection string before printing it. */
4591
+ function redact(connectionString) {
4592
+ if (!connectionString) return "(MYSQL_* environment defaults)";
4593
+ return redactCredentials(connectionString);
4594
+ }
4595
+ // src/cli/index.ts
4596
+ /** Deliberately uncommon so it doesn't collide with typical dev servers. */
4597
+ const DEFAULT_PORT = 47915;
4598
+ const EXAMPLES = `
4599
+ Examples:
4600
+ $ npx mysqldeck mysql://root:secret@localhost:3306/app
4601
+ $ npx mysqldeck "$DATABASE_URL" --readonly --port 8080
4602
+ $ npx mysqldeck mysql://... --host 0.0.0.0 --password hunter2 --base-path /db
4603
+
4604
+ Environment:
4605
+ MYSQL_URL connection string when none is given as an argument
4606
+ DATABASE_URL used when MYSQL_URL isn't set
4607
+ MYSQL_HOST, MYSQL_TCP_PORT, MYSQL_USER, MYSQL_PWD, MYSQL_DATABASE
4608
+ used for anything the connection string leaves out
4609
+ MYSQLDECK_PASSWORD login password for the web UI (same as --password)
4610
+ PORT port for the web UI (same as --port)
4611
+ `;
4612
+ async function run(connection, opts) {
4613
+ const config = resolveConfig(connection, opts);
4614
+ let manager;
4615
+ try {
4616
+ manager = new DatabaseManager({
4617
+ connectionString: config.connectionString,
4618
+ ssl: config.ssl,
4619
+ readonly: config.readonly,
4620
+ maxRows: config.maxRows
4621
+ });
4622
+ } catch (err) {
4623
+ printFatal("Invalid connection string", err.message);
4624
+ process.exit(1);
4625
+ }
4626
+ let info;
4627
+ let databaseCount;
4628
+ try {
4629
+ info = await (await manager.connect()).info();
4630
+ databaseCount = (await manager.list()).databases.length;
4631
+ } catch (err) {
4632
+ printFatal(`Could not connect to ${config.connectionString ? redact(config.connectionString) : manager.target}`, err.message);
4633
+ await manager.closeAll();
4634
+ process.exit(1);
4635
+ }
4636
+ let started;
4637
+ try {
4638
+ started = await startServer({
4639
+ manager,
4640
+ auth: config.auth,
4641
+ basePath: config.basePath,
4642
+ webRoot: config.webRoot,
4643
+ port: config.port,
4644
+ host: config.host
4645
+ });
4646
+ } catch (err) {
4647
+ printFatal(listenErrorMessage(err, config.port));
4648
+ await manager.closeAll();
4649
+ process.exit(1);
4650
+ }
4651
+ const url = serverUrl(config.host, started.port, config.basePath);
4652
+ printBanner(version, config, info, databaseCount, url, started.port);
4653
+ if (config.open) openBrowser(url);
4654
+ onShutdown(async () => {
4655
+ started.close();
4656
+ await manager.closeAll();
4657
+ });
4658
+ }
4659
+ const server = serverOptions({ defaultPort: DEFAULT_PORT });
4660
+ await new Command().name("mysqldeck").description(description).version(version, "-v, --version").argument("[connection-string]", "mysql:// URL (default: $MYSQL_URL or $DATABASE_URL, then MYSQL_* variables)").addOption(server.port).addOption(server.host).addOption(server.user).addOption(server.password).addOption(server.noAuth).option("--readonly", "open every session read-only and disable editing", false).option("--ssl", "connect with TLS without verifying the certificate", false).addOption(server.basePath).addOption(new Option("--max-rows <n>", "max rows returned per query").argParser(parsePositiveInt).default(2e3)).addOption(server.open).addHelpText("after", EXAMPLES).action(run).parseAsync();
4661
+ export {};