dsh-data-window 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/AGENTS.md +111 -0
  2. package/CHANGELOG.md +267 -0
  3. package/LICENSE +21 -0
  4. package/README.md +151 -2
  5. package/client.js +8271 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/BRIDGE.md +106 -0
  8. package/docs/DESIGN.md +417 -0
  9. package/docs/DETAIL.md +242 -0
  10. package/docs/screenshots/ddl.png +0 -0
  11. package/docs/screenshots/workbench.png +0 -0
  12. package/icon.svg +30 -0
  13. package/index.js +180 -0
  14. package/locale/en.json +304 -0
  15. package/locale/zh.json +304 -0
  16. package/package.json +68 -4
  17. package/src/client/00-css.js +1110 -0
  18. package/src/client/05-icons.js +156 -0
  19. package/src/client/05-theme.js +107 -0
  20. package/src/client/06-shortcuts.js +89 -0
  21. package/src/client/07-bridge.js +202 -0
  22. package/src/client/10-core.js +1320 -0
  23. package/src/client/20-tree.js +293 -0
  24. package/src/client/25-sql.js +631 -0
  25. package/src/client/30-editor.js +742 -0
  26. package/src/client/40-results.js +556 -0
  27. package/src/client/45-export.js +219 -0
  28. package/src/client/50-panel.js +768 -0
  29. package/src/client/60-settings.js +180 -0
  30. package/src/client/63-schema.js +186 -0
  31. package/src/client/64-manual.js +350 -0
  32. package/src/client/65-ai.js +320 -0
  33. package/src/client/66-optimize.js +217 -0
  34. package/src/client/90-apply.js +183 -0
  35. package/src/host/ai.js +721 -0
  36. package/src/host/cache.js +157 -0
  37. package/src/host/catalog.js +161 -0
  38. package/src/host/consoles.js +116 -0
  39. package/src/host/discovery.js +603 -0
  40. package/src/host/manual.js +276 -0
  41. package/src/host/mysql.js +650 -0
  42. package/src/host/remembered.js +225 -0
  43. package/src/host/rpc.js +487 -0
  44. package/src/host/shared.js +180 -0
  45. package/src/host/yaml.js +335 -0
@@ -0,0 +1,650 @@
1
+ /**
2
+ * The read-only MySQL gateway.
3
+ *
4
+ * Two promises are kept here and nowhere else:
5
+ *
6
+ * 1. A statement the viewer sends cannot modify data. The first word must be a
7
+ * read verb, one statement per request, and every pooled connection opens with
8
+ * `SET SESSION TRANSACTION READ ONLY`, so the server itself rejects a write even
9
+ * if a parser gap lets one through.
10
+ * 2. Credentials stay in the Host process. The browser names a target id; the
11
+ * password never leaves this module.
12
+ */
13
+ import { createPool } from 'mysql2/promise'
14
+ import { SYSTEM_SCHEMAS } from './discovery.js'
15
+
16
+ /** Statements a work viewer needs; everything else is refused before connecting. */
17
+ const ALLOWED_VERBS = new Set(['select', 'show', 'desc', 'describe', 'explain', 'with', 'table'])
18
+
19
+ /** Row ceiling when the caller does not choose one. */
20
+ const DEFAULT_LIMIT = 200
21
+
22
+ /** Hard row ceiling, so one accidental full scan cannot exhaust the browser. */
23
+ const MAX_LIMIT = 5000
24
+
25
+ /** Reject anything this large before it reaches the driver. */
26
+ const MAX_SQL_BYTES = 512 * 1024
27
+
28
+ export class ReadOnlyViolation extends Error {
29
+ constructor(message) {
30
+ super(message)
31
+ this.code = 'read-only-violation'
32
+ }
33
+ }
34
+
35
+ /** Strip `--`, `#` and block comments so the first word is really the first word. */
36
+ export function significantSql(sql) {
37
+ let text = String(sql ?? '')
38
+ // Block comments first: `/*! ... */` is executable in MySQL, and a viewer never
39
+ // needs one, so the whole comment region is removed rather than trusted.
40
+ text = text.replace(/\/\*[\s\S]*?\*\//g, ' ')
41
+ text = text.replace(/^\s*(?:--[^\n]*|#[^\n]*)\s*$/gm, ' ')
42
+ text = text.replace(/--[^\n]*/g, ' ')
43
+ text = text.replace(/(^|\s)#[^\n]*/g, ' ')
44
+ return text.trim()
45
+ }
46
+
47
+ /** Split one request into statements, honoring quotes and comments. */
48
+ export function splitStatements(sql) {
49
+ const text = String(sql ?? '')
50
+ const statements = []
51
+ let current = ''
52
+ let single = false
53
+ let double = false
54
+ let backtick = false
55
+ let lineComment = false
56
+ let blockComment = false
57
+ for (let index = 0; index < text.length; index += 1) {
58
+ const character = text[index]
59
+ const next = text[index + 1]
60
+ if (lineComment) {
61
+ if (character === '\n') {
62
+ lineComment = false
63
+ current += character
64
+ }
65
+ continue
66
+ }
67
+ if (blockComment) {
68
+ if (character === '*' && next === '/') {
69
+ blockComment = false
70
+ index += 1
71
+ }
72
+ continue
73
+ }
74
+ if (!single && !double && !backtick) {
75
+ if (character === '-' && next === '-') {
76
+ lineComment = true
77
+ index += 1
78
+ continue
79
+ }
80
+ if (character === '#') {
81
+ lineComment = true
82
+ continue
83
+ }
84
+ if (character === '/' && next === '*') {
85
+ blockComment = true
86
+ index += 1
87
+ continue
88
+ }
89
+ }
90
+ if (character === "'" && !double && !backtick) {
91
+ single = text[index - 1] === '\\' ? single : !single
92
+ current += character
93
+ continue
94
+ }
95
+ if (character === '"' && !single && !backtick) {
96
+ double = text[index - 1] === '\\' ? double : !double
97
+ current += character
98
+ continue
99
+ }
100
+ if (character === '`' && !single && !double) {
101
+ backtick = !backtick
102
+ current += character
103
+ continue
104
+ }
105
+ if (character === ';' && !single && !double && !backtick) {
106
+ if (current.trim() !== '') statements.push(current.trim())
107
+ current = ''
108
+ continue
109
+ }
110
+ current += character
111
+ }
112
+ if (current.trim() !== '') statements.push(current.trim())
113
+ return statements
114
+ }
115
+
116
+ /**
117
+ * Validate one statement as read-only.
118
+ *
119
+ * @returns the statement to run (single trailing semicolon removed).
120
+ */
121
+ export function assertReadOnly(sql) {
122
+ const text = String(sql ?? '')
123
+ if (text.length > MAX_SQL_BYTES) throw new ReadOnlyViolation('sql-too-large')
124
+ const statements = splitStatements(text)
125
+ if (statements.length === 0) throw new ReadOnlyViolation('empty-sql')
126
+ if (statements.length > 1) throw new ReadOnlyViolation('multiple-statements')
127
+ const statement = statements[0]
128
+ const first = /^[A-Za-z]+/.exec(significantSql(statement))
129
+ if (first === null) throw new ReadOnlyViolation('unrecognized-sql')
130
+ const verb = first[0].toLowerCase()
131
+ if (!ALLOWED_VERBS.has(verb)) throw new ReadOnlyViolation(`forbidden-verb:${verb}`)
132
+ const body = significantSql(statement).toLowerCase()
133
+ if (/\binto\s+(out|dump)file\b/.test(body)) throw new ReadOnlyViolation('write-file')
134
+ // `SHOW CREATE TABLE`, `SHOW INDEX`, `EXPLAIN` and `DESC` cannot write, so their
135
+ // bodies are not scanned for write verbs — `create` is the whole point of the
136
+ // statement the DDL viewer sends.
137
+ if (verb === 'show' || verb === 'desc' || verb === 'describe' || verb === 'explain') return statement
138
+ // A read-only transaction still allows a `SELECT` that writes through a
139
+ // function, and `WITH ... DELETE` parses as `WITH`, so the write verbs are
140
+ // refused anywhere in the statement rather than only at the front.
141
+ if (/\b(insert|update|delete|replace|drop|alter|truncate|create|rename|grant|revoke|call|load|lock|unlock|handler|do)\b/.test(body)) {
142
+ throw new ReadOnlyViolation('write-keyword')
143
+ }
144
+ // Row locks are a write of sorts: they block other sessions until this one ends.
145
+ if (/\bfor\s+update\b|\block\s+in\s+share\s+mode\b/.test(body)) throw new ReadOnlyViolation('locking-select')
146
+ return statement
147
+ }
148
+
149
+ /**
150
+ * Remove a trailing top-level LIMIT, so a count covers the whole result set.
151
+ *
152
+ * The scanner tracks quotes, comments and parenthesis depth: a LIMIT inside a
153
+ * string, a comment or a subquery must be kept. Only a LIMIT that ends the
154
+ * statement (after trimming) is dropped.
155
+ */
156
+ export function stripTrailingLimit(statement) {
157
+ const text = String(statement ?? '')
158
+ let depth = 0
159
+ let quote = ''
160
+ let lineComment = false
161
+ let blockComment = false
162
+ let lastLimit = -1
163
+ for (let index = 0; index < text.length; index += 1) {
164
+ const char = text[index]
165
+ const next = text[index + 1]
166
+ if (lineComment === true) {
167
+ if (char === '\n') lineComment = false
168
+ continue
169
+ }
170
+ if (blockComment === true) {
171
+ if (char === '*' && next === '/') {
172
+ blockComment = false
173
+ index += 1
174
+ }
175
+ continue
176
+ }
177
+ if (quote !== '') {
178
+ if (char === '\\') {
179
+ index += 1
180
+ continue
181
+ }
182
+ if (char === quote) {
183
+ if (next === quote) {
184
+ index += 1
185
+ continue
186
+ }
187
+ quote = ''
188
+ }
189
+ continue
190
+ }
191
+ if (char === '-' && next === '-') {
192
+ lineComment = true
193
+ index += 1
194
+ continue
195
+ }
196
+ if (char === '#') {
197
+ lineComment = true
198
+ continue
199
+ }
200
+ if (char === '/' && next === '*') {
201
+ blockComment = true
202
+ index += 1
203
+ continue
204
+ }
205
+ if (char === '\'' || char === '"' || char === '`') {
206
+ quote = char
207
+ continue
208
+ }
209
+ if (char === '(') {
210
+ depth += 1
211
+ continue
212
+ }
213
+ if (char === ')') {
214
+ depth = Math.max(0, depth - 1)
215
+ continue
216
+ }
217
+ if (depth !== 0 || !/[A-Za-z]/.test(char)) continue
218
+ if (index > 0 && /[A-Za-z0-9_$]/.test(text[index - 1])) continue
219
+ let end = index
220
+ while (end < text.length && /[A-Za-z]/.test(text[end])) end += 1
221
+ if (text.slice(index, end).toLowerCase() === 'limit') lastLimit = index
222
+ index = end - 1
223
+ }
224
+ if (lastLimit < 0) return text
225
+ const tail = text.slice(lastLimit)
226
+ if (!/^limit\s+\d+(\s*(,\s*\d+|offset\s+\d+))?\s*$/i.test(tail)) return text
227
+ return text.slice(0, lastLimit).replace(/\s+$/, '')
228
+ }
229
+
230
+ /** Append a LIMIT to a bare SELECT so MySQL itself stops early. */
231
+ export function withRowLimit(statement, limit) {
232
+ const trimmed = statement.replace(/;\s*$/, '').trim()
233
+ if (!/^(select|with|table)\b/i.test(trimmed)) return trimmed
234
+ // Every trailing LIMIT form counts: a paged statement ends in
235
+ // `LIMIT n OFFSET m`, and appending another LIMIT turns a valid query into
236
+ // `… LIMIT n OFFSET m LIMIT n+1` (ER_PARSE_ERROR).
237
+ if (/\blimit\s+[0-9]+\s*(,\s*[0-9]+)?(\s+offset\s+[0-9]+)?\s*$/i.test(trimmed)) return trimmed
238
+ return `${trimmed} LIMIT ${limit}`
239
+ }
240
+
241
+ /** One value a result cell may carry; MySQL can return types JSON cannot. */
242
+ function cellValue(value) {
243
+ if (value === null || value === undefined) return null
244
+ const type = typeof value
245
+ if (type === 'string' || type === 'number' || type === 'boolean') return value
246
+ if (type === 'bigint') return value.toString()
247
+ if (value instanceof Date) {
248
+ // Local wall-clock text is what a SQL client shows, and it round-trips back
249
+ // into MySQL unchanged; an ISO string would move the value by the offset.
250
+ const pad = (number, size = 2) => String(number).padStart(size, '0')
251
+ const date = `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`
252
+ const clock = `${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`
253
+ const millis = value.getMilliseconds() === 0 ? '' : `.${pad(value.getMilliseconds(), 3)}`
254
+ return `${date} ${clock}${millis}`
255
+ }
256
+ if (Buffer.isBuffer(value)) return `0x${value.toString('hex')}`
257
+ if (Array.isArray(value)) return value.map(cellValue)
258
+ if (type === 'object') {
259
+ try {
260
+ return JSON.stringify(value)
261
+ } catch (error) {
262
+ void error
263
+ return String(value)
264
+ }
265
+ }
266
+ return String(value)
267
+ }
268
+
269
+ /** Normalize one driver row into a plain array of cells. */
270
+ function rowValues(row, columns) {
271
+ if (Array.isArray(row)) return row.map(cellValue)
272
+ return columns.map((column) => cellValue(row[column]))
273
+ }
274
+
275
+ /** Key a pool by everything that changes its identity. */
276
+ function poolKey(target) {
277
+ return `${target.host}:${target.port}|${target.user}|${target.database ?? ''}`
278
+ }
279
+
280
+ export class DataGateway {
281
+ constructor(config = {}) {
282
+ this.config = config
283
+ this.targets = new Map()
284
+ this.pools = new Map()
285
+ /** Round-trip counters, surfaced in the panel's log line. */
286
+ this.statementCount = 0
287
+ }
288
+
289
+ /** Replace the addressable targets; new ids win, old pools are dropped lazily. */
290
+ setTargets(targets) {
291
+ this.targets = targets instanceof Map ? targets : new Map(Object.entries(targets ?? {}))
292
+ for (const [key, pool] of this.pools) {
293
+ const stillUsed = [...this.targets.values()].some((target) => poolKey(target) === key)
294
+ if (stillUsed) continue
295
+ this.pools.delete(key)
296
+ pool.end().catch(() => undefined)
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Register extra targets without dropping the pools the current tree uses.
302
+ *
303
+ * The AI fallback resolves an address the configuration scan never saw, and its
304
+ * connection must be usable by the tab that later opens it; a full `setTargets`
305
+ * replacement would close the pools behind every already-open console.
306
+ */
307
+ addTargets(entries) {
308
+ if (entries === null || entries === undefined || typeof entries !== 'object') return
309
+ for (const [id, target] of entries instanceof Map ? entries : Object.entries(entries)) {
310
+ if (typeof id !== 'string' || id === '' || target === null || typeof target !== 'object') continue
311
+ this.targets.set(id, target)
312
+ }
313
+ }
314
+
315
+ /** Drop targets and the pools only they used (removed manual connections). */
316
+ removeTargets(ids) {
317
+ const pools = new Set()
318
+ for (const id of Array.isArray(ids) ? ids : []) {
319
+ const target = this.targets.get(String(id))
320
+ if (target === undefined) continue
321
+ pools.add(poolKey(target))
322
+ this.targets.delete(String(id))
323
+ }
324
+ for (const key of pools) {
325
+ const stillUsed = [...this.targets.values()].some((target) => poolKey(target) === key)
326
+ if (stillUsed) continue
327
+ const pool = this.pools.get(key)
328
+ if (pool === undefined) continue
329
+ this.pools.delete(key)
330
+ pool.end().catch(() => undefined)
331
+ }
332
+ }
333
+
334
+ targetOf(id) {
335
+ const key = String(id ?? '')
336
+ const direct = this.targets.get(key)
337
+ if (direct !== undefined) return direct
338
+ // A schema revealed by "全部库" was never configured, so its id is the
339
+ // instance id plus the schema name. Resolving it on demand keeps an open tab
340
+ // usable across a rediscovery that replaced the whole target map.
341
+ const separator = key.indexOf('~')
342
+ if (separator > 0) {
343
+ const instance = this.targets.get(key.slice(0, separator))
344
+ if (instance !== undefined) {
345
+ const derived = { ...instance, id: key, database: key.slice(separator + 1) }
346
+ this.targets.set(key, derived)
347
+ return derived
348
+ }
349
+ }
350
+ const error = new Error('unknown-target')
351
+ error.code = 'unknown-target'
352
+ throw error
353
+ }
354
+
355
+ poolFor(target) {
356
+ const key = poolKey(target)
357
+ const existing = this.pools.get(key)
358
+ if (existing !== undefined) return existing
359
+ const pool = createPool({
360
+ host: target.host,
361
+ port: target.port,
362
+ user: target.user,
363
+ password: target.password,
364
+ database: target.database,
365
+ connectTimeout: Math.max(2000, Number(this.config.connectTimeoutMs ?? 8000)),
366
+ connectionLimit: Math.max(1, Number(this.config.connectionLimit ?? 4)),
367
+ charset: 'utf8mb4',
368
+ // Every new socket starts read-only, before any statement the viewer sends.
369
+ connectAttributes: { program_name: 'dsh-data-window' },
370
+ })
371
+ pool.on('connection', (connection) => {
372
+ connection.query('SET SESSION TRANSACTION READ ONLY', () => undefined)
373
+ const timeout = Number(this.config.statementTimeoutMs ?? 60000)
374
+ if (Number.isFinite(timeout) && timeout > 0) {
375
+ connection.query(`SET SESSION max_execution_time = ${Math.floor(timeout)}`, () => undefined)
376
+ }
377
+ })
378
+ this.pools.set(key, pool)
379
+ return pool
380
+ }
381
+
382
+ /** Run one statement and return table-shaped rows. */
383
+ async run(id, sql, options = {}) {
384
+ const target = this.targetOf(id)
385
+ const statement = assertReadOnly(sql)
386
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number(options.limit ?? DEFAULT_LIMIT)))
387
+ // One row past the ceiling is how the response knows it was truncated: an exact
388
+ // `limit` rows may be the whole table, and claiming a truncation that did not
389
+ // happen is worse than asking for one extra row.
390
+ const prepared = withRowLimit(statement, limit + 1)
391
+ const pool = this.poolFor(target)
392
+ const startedAt = Date.now()
393
+ this.statementCount += 1
394
+ try {
395
+ const [rows, fields] = await pool.query({ sql: prepared, timeout: Number(this.config.statementTimeoutMs ?? 60000) })
396
+ const elapsedMs = Date.now() - startedAt
397
+ if (!Array.isArray(rows)) {
398
+ // DML-shaped metadata (an affected-row count) can only come from a statement
399
+ // the whitelist let through; report it instead of pretending it is a table.
400
+ return { kind: 'ok', sql: prepared, elapsedMs, affectedRows: Number(rows?.affectedRows ?? 0), columns: [], rows: [], rowCount: 0 }
401
+ }
402
+ const columns = (fields ?? []).map((field) => ({
403
+ name: field.name,
404
+ type: String(field.columnType ?? ''),
405
+ flags: Number(field.flags ?? 0),
406
+ // The protocol reports TEXT and BLOB under one type code; the character set
407
+ // is what separates them (63 is the binary collation).
408
+ charset: Number(field.characterSet ?? 0),
409
+ }))
410
+ const names = columns.length > 0 ? columns.map((column) => column.name) : Object.keys(rows[0] ?? {})
411
+ const allValues = rows.map((row) => rowValues(row, names))
412
+ const truncated = allValues.length > limit
413
+ const values = truncated ? allValues.slice(0, limit) : allValues
414
+ return {
415
+ kind: 'rows',
416
+ sql: statement,
417
+ elapsedMs,
418
+ columns: names.map((name, index) => ({
419
+ name,
420
+ type: columns[index]?.type ?? '',
421
+ flags: columns[index]?.flags ?? 0,
422
+ charset: columns[index]?.charset ?? 0,
423
+ })),
424
+ rows: values,
425
+ rowCount: values.length,
426
+ truncated,
427
+ limit,
428
+ }
429
+ } catch (error) {
430
+ const wrapped = new Error(error?.message ?? String(error))
431
+ wrapped.code = error?.code ?? 'query-failed'
432
+ wrapped.elapsedMs = Date.now() - startedAt
433
+ wrapped.sql = prepared
434
+ throw wrapped
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Every schema on one instance, minus the ones nobody browses.
440
+ *
441
+ * Each schema comes back with the id the browser must use later, which is the
442
+ * instance id plus the schema name: discovery only registers the schemas the
443
+ * project's own configuration named.
444
+ */
445
+ async listDatabases(id) {
446
+ const target = this.targetOf(id)
447
+ const result = await this.run(id, 'SHOW DATABASES', { limit: MAX_LIMIT })
448
+ const databases = []
449
+ for (const row of result.rows) {
450
+ const name = String(row[0] ?? '')
451
+ if (name === '' || SYSTEM_SCHEMAS.has(name.toLowerCase())) continue
452
+ const derivedId = `${target.id}~${name}`
453
+ this.targets.set(derivedId, { ...target, id: derivedId, database: name })
454
+ databases.push({ name, id: derivedId })
455
+ }
456
+ return { databases, total: result.rowCount, scanned: result.elapsedMs }
457
+ }
458
+
459
+ /** Tables and views of one schema with their comment and estimated size. */
460
+ async listTables(id) {
461
+ const target = this.targetOf(id)
462
+ if (typeof target.database !== 'string') {
463
+ const error = new Error('database-required')
464
+ error.code = 'database-required'
465
+ throw error
466
+ }
467
+ const result = await this.run(
468
+ id,
469
+ `SELECT TABLE_NAME, TABLE_TYPE, COALESCE(TABLE_COMMENT, ''), COALESCE(TABLE_ROWS, 0), COALESCE(ENGINE, '')
470
+ FROM information_schema.TABLES
471
+ WHERE TABLE_SCHEMA = ${sqlString(target.database)}
472
+ ORDER BY TABLE_NAME`,
473
+ { limit: MAX_LIMIT },
474
+ )
475
+ return {
476
+ tables: result.rows.map((row) => ({
477
+ name: String(row[0] ?? ''),
478
+ kind: String(row[1] ?? '').toUpperCase() === 'VIEW' ? 'view' : 'table',
479
+ comment: String(row[2] ?? ''),
480
+ rows: Number(row[3] ?? 0),
481
+ engine: String(row[4] ?? ''),
482
+ })),
483
+ elapsedMs: result.elapsedMs,
484
+ }
485
+ }
486
+
487
+ /** Columns of one table, in declaration order. */
488
+ async listColumns(id, table) {
489
+ const target = this.targetOf(id)
490
+ const result = await this.run(
491
+ id,
492
+ `SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COALESCE(COLUMN_KEY, ''), COLUMN_DEFAULT, COALESCE(EXTRA, ''), COALESCE(COLUMN_COMMENT, '')
493
+ FROM information_schema.COLUMNS
494
+ WHERE TABLE_SCHEMA = ${sqlString(target.database)} AND TABLE_NAME = ${sqlString(table)}
495
+ ORDER BY ORDINAL_POSITION`,
496
+ { limit: MAX_LIMIT },
497
+ )
498
+ return {
499
+ columns: result.rows.map((row) => ({
500
+ name: String(row[0] ?? ''),
501
+ type: String(row[1] ?? ''),
502
+ nullable: String(row[2] ?? '').toUpperCase() === 'YES',
503
+ key: String(row[3] ?? ''),
504
+ defaultValue: row[4] === null ? null : String(row[4]),
505
+ extra: String(row[5] ?? ''),
506
+ comment: String(row[6] ?? ''),
507
+ })),
508
+ }
509
+ }
510
+
511
+ /** Whether one schema contains a table; used by the code-workspace bridge. */
512
+ async hasTable(id, schema, table) {
513
+ const result = await this.run(
514
+ id,
515
+ `SELECT 1 FROM information_schema.TABLES
516
+ WHERE TABLE_SCHEMA = ${sqlString(schema)} AND TABLE_NAME = ${sqlString(table)}
517
+ LIMIT 1`,
518
+ { limit: 1 },
519
+ )
520
+ return result.rowCount > 0
521
+ }
522
+
523
+ /**
524
+ * Count the rows of one statement without touching its filters.
525
+ *
526
+ * The statement is wrapped, so WHERE/GROUP BY/LIMIT inside it still apply. SHOW
527
+ * and EXPLAIN cannot live in a derived table and are refused as unsupported.
528
+ */
529
+ async countRows(id, sql) {
530
+ const statement = assertReadOnly(sql)
531
+ // A trailing LIMIT belongs to the preview, not to the data set: counting the
532
+ // wrapped statement with LIMIT would just return the limit back.
533
+ const normalized = stripTrailingLimit(statement.trim().replace(/;+\s*$/, ''))
534
+ if (!/^(select|with)\b/i.test(normalized)) {
535
+ const error = new Error('count-unsupported')
536
+ error.code = 'count-unsupported'
537
+ throw error
538
+ }
539
+ const result = await this.run(id, `SELECT COUNT(*) AS total FROM (${normalized}) AS dw_count`, { limit: 1 })
540
+ return {
541
+ total: Number(result.rows?.[0]?.[0] ?? 0),
542
+ elapsedMs: result.elapsedMs,
543
+ sql: result.sql,
544
+ }
545
+ }
546
+
547
+ /**
548
+ * Every table and column of one schema in one round trip.
549
+ *
550
+ * The SQL editor suggests table and column names; one map call per database
551
+ * beats a `columns` call per referenced table, and it is what lets the editor
552
+ * suggest columns of tables the tree has never expanded.
553
+ */
554
+ async schemaMap(id) {
555
+ const target = this.targetOf(id)
556
+ if (typeof target.database !== 'string') {
557
+ const error = new Error('database-required')
558
+ error.code = 'database-required'
559
+ throw error
560
+ }
561
+ const result = await this.run(
562
+ id,
563
+ `SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE
564
+ FROM information_schema.COLUMNS
565
+ WHERE TABLE_SCHEMA = ${sqlString(target.database)}
566
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`,
567
+ { limit: MAX_LIMIT },
568
+ )
569
+ const tables = new Map()
570
+ for (const row of result.rows) {
571
+ const name = String(row[0] ?? '')
572
+ if (name === '') continue
573
+ let table = tables.get(name)
574
+ if (table === undefined) {
575
+ table = { name, columns: [] }
576
+ tables.set(name, table)
577
+ }
578
+ table.columns.push({ name: String(row[1] ?? ''), type: String(row[2] ?? '') })
579
+ }
580
+ return {
581
+ database: target.database,
582
+ tables: [...tables.values()],
583
+ truncated: result.truncated,
584
+ elapsedMs: result.elapsedMs,
585
+ }
586
+ }
587
+
588
+ /** The DDL of one table, plus its indexes. */
589
+ async showCreate(id, table) {
590
+ const target = this.targetOf(id)
591
+ const schema = typeof target.database === 'string' ? target.database : undefined
592
+ const qualified = `${schema === undefined ? '' : `${quoteIdentifier(schema)}.`}${quoteIdentifier(table)}`
593
+ const create = await this.run(id, `SHOW CREATE TABLE ${qualified}`, { limit: 10 })
594
+ const ddl = String(create.rows[0]?.[1] ?? '')
595
+ const columns = await this.listColumns(id, table).catch(() => ({ columns: [] }))
596
+ return {
597
+ table,
598
+ database: schema ?? '',
599
+ ddl,
600
+ statementTime: create.elapsedMs,
601
+ // `SHOW CREATE TABLE` already embeds indexes, so no second round trip is
602
+ // needed; the column list is what the panel shows above the DDL.
603
+ columns: columns.columns,
604
+ }
605
+ }
606
+
607
+ /** Cheap liveness check for one instance. */
608
+ async ping(id) {
609
+ const target = this.targetOf(id)
610
+ const startedAt = Date.now()
611
+ const result = await this.run(id, 'SELECT VERSION() AS server_version, DATABASE() AS database_name, CURRENT_USER() AS current_user_name', { limit: 1 })
612
+ const row = result.rows[0] ?? []
613
+ return {
614
+ host: target.host,
615
+ port: target.port,
616
+ env: target.env,
617
+ version: String(row[0] ?? ''),
618
+ database: row[1] === null ? null : String(row[1]),
619
+ currentUser: String(row[2] ?? ''),
620
+ elapsedMs: Date.now() - startedAt,
621
+ }
622
+ }
623
+
624
+ /** Tell the driver to stop serving this target. */
625
+ async forget(id) {
626
+ const target = this.targets.get(String(id ?? ''))
627
+ if (target === undefined) return false
628
+ const key = poolKey(target)
629
+ const pool = this.pools.get(key)
630
+ this.pools.delete(key)
631
+ if (pool !== undefined) await pool.end().catch(() => undefined)
632
+ return true
633
+ }
634
+
635
+ async close() {
636
+ const pools = [...this.pools.values()]
637
+ this.pools.clear()
638
+ await Promise.all(pools.map((pool) => pool.end().catch(() => undefined)))
639
+ }
640
+ }
641
+
642
+ /** Quote one identifier for a statement this module builds itself. */
643
+ export function quoteIdentifier(value) {
644
+ return `\`${String(value).replace(/`/g, '``')}\``
645
+ }
646
+
647
+ /** Quote one literal for a statement this module builds itself. */
648
+ export function sqlString(value) {
649
+ return `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
650
+ }