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,1320 @@
1
+ /**
2
+ * Store, translator and Host RPC for the database window.
3
+ *
4
+ * One store instance is created in `apply` and shared by the panel and the sidebar
5
+ * entry, so opening the panel from either place shows the same workspace. Every
6
+ * read goes through `getSnapshot`, which keeps the React tree a pure function of
7
+ * one plain object — the panel never keeps a second copy of the tree.
8
+ *
9
+ * Two rules the store owns, because no component can enforce them safely:
10
+ *
11
+ * - the window follows the workspace the shell is showing, unless the user
12
+ * deliberately picked another directory;
13
+ * - a workbench that already holds the user's SQL is never overwritten by a tree
14
+ * action.
15
+ */
16
+
17
+ /** Persisted manual workspace, so a reload reopens where the user left it. */
18
+ const DW_ROOT_KEY = 'dsh-data-window:root'
19
+
20
+ /** Locale namespace, shared with `locale/*.json`. */
21
+ const DW_NS = 'dsh-data-window'
22
+
23
+ /** Keyed main-panel id of the database window. */
24
+ const DW_PANEL_ID = 'dsh-data-window:database'
25
+
26
+ /** Rows kept in the run log before the oldest is dropped. */
27
+ const DW_LOG_LIMIT = 400
28
+
29
+ /** How many rows the panel asks for until the Host reports its configured default. */
30
+ const DW_DEFAULT_LIMIT = 200
31
+
32
+ /** Monotonic suffix for second and later consoles of one database. */
33
+ let dwStatementSequence = 0
34
+
35
+ /** The bytes that read like a statement, so "is this the user's SQL" is decidable. */
36
+ const DW_SQL_EMPTY = /^\s*(?:--[^\n]*\n?)*\s*$/
37
+
38
+ /**
39
+ * Build the plugin's translator.
40
+ *
41
+ * The framework's `t` echoes the key back for a locale the bundle has no
42
+ * dictionary for, and a raw key in the UI is never acceptable, so the bundle's own
43
+ * dictionaries are the guaranteed last resort.
44
+ */
45
+ function dwMakeTranslator(ctx, boundT) {
46
+ const localeId = () => {
47
+ try {
48
+ const snapshot = ctx?.locale?.getSnapshot?.()
49
+ if (typeof snapshot?.active === 'string' && snapshot.active !== '') return snapshot.active
50
+ } catch (error) {
51
+ void error
52
+ }
53
+ if (typeof document !== 'undefined' && typeof document.documentElement?.lang === 'string') {
54
+ return document.documentElement.lang
55
+ }
56
+ return typeof navigator !== 'undefined' && typeof navigator.language === 'string' ? navigator.language : ''
57
+ }
58
+ const dictionary = () => (/^zh/i.test(localeId()) ? DW_TEXT_ZH : DW_TEXT_EN)
59
+ const translate = (key, values) => {
60
+ let template
61
+ if (typeof boundT === 'function') {
62
+ const value = boundT(key)
63
+ if (typeof value === 'string' && value !== '' && value !== key) template = value
64
+ }
65
+ if (template === undefined) {
66
+ const table = dictionary()
67
+ const value = table[key]
68
+ template = typeof value === 'string' ? value : key
69
+ }
70
+ if (values === undefined) return template
71
+ return template.replace(/\{(\w+)\}/g, (match, name) => {
72
+ const replacement = values[name]
73
+ return replacement === undefined || replacement === null ? match : String(replacement)
74
+ })
75
+ }
76
+ translate.localeId = localeId
77
+ return translate
78
+ }
79
+
80
+ /** Call the Host route once. */
81
+ async function dwRpc(action, payload = {}) {
82
+ const base = typeof document !== 'undefined' && typeof document.baseURI === 'string' ? document.baseURI : 'http://dsh.internal/'
83
+ const response = await fetch(new URL('dsh-data/rpc', base).href, {
84
+ method: 'POST',
85
+ headers: { 'content-type': 'application/json' },
86
+ body: JSON.stringify({ action, ...payload }),
87
+ })
88
+ let body
89
+ try {
90
+ body = await response.json()
91
+ } catch (error) {
92
+ void error
93
+ throw new Error(`${action}: HTTP ${response.status}`)
94
+ }
95
+ if (body?.ok !== true) {
96
+ const failure = new Error(body?.error?.message ?? `${action} failed`)
97
+ failure.code = body?.error?.code ?? 'request-failed'
98
+ throw failure
99
+ }
100
+ return body.value
101
+ }
102
+
103
+ /** The instance behind a database id; a schema found through "all databases" is `<instance>~<name>`. */
104
+ function dwInstanceIdOf(dbId) {
105
+ const text = String(dbId ?? '')
106
+ const separator = text.indexOf('~')
107
+ return separator > 0 && text.startsWith('i:') ? text.slice(0, separator) : ''
108
+ }
109
+
110
+ /** Compose one tree-node key; every level of the tree is addressable. */
111
+ function dwNodeKey(kind, ...parts) {
112
+ return [kind, ...parts].join(':')
113
+ }
114
+
115
+ /** Format a duration for the log and the result bar. */
116
+ function dwDuration(milliseconds) {
117
+ const value = Number(milliseconds)
118
+ if (!Number.isFinite(value)) return ''
119
+ if (value < 1000) return `${Math.round(value)} ms`
120
+ return `${(value / 1000).toFixed(2)} s`
121
+ }
122
+
123
+ /** Format a row count the way a SQL client does. */
124
+ function dwRowCount(count) {
125
+ const value = Number(count)
126
+ if (!Number.isFinite(value)) return '0'
127
+ if (value < 10000) return String(value)
128
+ if (value < 1000000) return `${(value / 1000).toFixed(1)}k`
129
+ return `${(value / 1000000).toFixed(2)}M`
130
+ }
131
+
132
+ /** One line for the run log. */
133
+ function dwLogEntry(level, text) {
134
+ return { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, at: new Date(), level, text }
135
+ }
136
+
137
+ /**
138
+ * Turn a Host failure into a sentence.
139
+ *
140
+ * The read-only gate answers with codes such as `write-keyword`, and a user who is
141
+ * stopped by the one rule this window enforces deserves an explanation rather than
142
+ * an enum.
143
+ */
144
+ function dwExplainFailure(translate, error) {
145
+ const code = String(error?.code ?? '')
146
+ const detail = String(error?.message ?? '')
147
+ const known = {
148
+ 'read-only-violation': 'error.readOnly',
149
+ 'unknown-target': 'error.hostRestarted',
150
+ 'database-required': 'error.databaseRequired',
151
+ 'ER_NO_SUCH_TABLE': 'error.noSuchTable',
152
+ 'ER_BAD_FIELD_ERROR': 'error.badField',
153
+ 'ER_ACCESS_DENIED_ERROR': 'error.accessDenied',
154
+ 'ETIMEDOUT': 'error.timeout',
155
+ 'ECONNREFUSED': 'error.refused',
156
+ 'ENOTFOUND': 'error.unresolved',
157
+ 'ER_QUERY_INTERRUPTED': 'error.interrupted',
158
+ 'manual-connect-failed': 'error.manualConnectFailed',
159
+ 'saved-connection-missing': 'error.savedConnectionMissing',
160
+ }
161
+ const key = known[code]
162
+ if (key !== undefined) {
163
+ const text = translate(key)
164
+ if (text !== key) return `${text}${detail === '' ? '' : `(${detail})`}`
165
+ }
166
+ return detail === '' ? code : `${code}: ${detail}`
167
+ }
168
+
169
+ /**
170
+ * Merge AI-resolved environments into the rule-based ones.
171
+ *
172
+ * The two sources may describe the same host; instances and databases are merged
173
+ * by identity so a workspace never shows the same database twice.
174
+ */
175
+ function dwMergeEnvironments(existing, added) {
176
+ const output = (Array.isArray(existing) ? existing : []).map((environment) => ({
177
+ ...environment,
178
+ instances: [...(Array.isArray(environment?.instances) ? environment.instances : [])],
179
+ }))
180
+ for (const environment of Array.isArray(added) ? added : []) {
181
+ if (environment === null || typeof environment !== 'object') continue
182
+ const incoming = Array.isArray(environment.instances) ? environment.instances : []
183
+ const current = output.find((entry) => entry.env === environment.env)
184
+ if (current === undefined) {
185
+ output.push({ ...environment, instances: [...incoming] })
186
+ continue
187
+ }
188
+ for (const instance of incoming) {
189
+ const known = current.instances.find((entry) => entry.id === instance.id)
190
+ if (known === undefined) {
191
+ current.instances.push(instance)
192
+ continue
193
+ }
194
+ if (!Array.isArray(known.databases)) known.databases = []
195
+ for (const database of Array.isArray(instance.databases) ? instance.databases : []) {
196
+ if (known.databases.some((entry) => entry.name === database.name)) continue
197
+ known.databases.push(database)
198
+ }
199
+ }
200
+ current.databaseCount = current.instances.reduce((total, instance) => total + (Array.isArray(instance.databases) ? instance.databases.length : 0), 0)
201
+ }
202
+ return output
203
+ }
204
+
205
+ /** Read the persisted manual workspace, tolerating a blocked storage. */
206
+ function dwStoredRoot() {
207
+ try {
208
+ return globalThis.localStorage?.getItem(DW_ROOT_KEY) ?? ''
209
+ } catch (error) {
210
+ void error
211
+ return ''
212
+ }
213
+ }
214
+
215
+ /** Persist (or clear) the manual workspace. */
216
+ function dwPersistRoot(root) {
217
+ try {
218
+ if (root === '') globalThis.localStorage?.removeItem(DW_ROOT_KEY)
219
+ else globalThis.localStorage?.setItem(DW_ROOT_KEY, root)
220
+ } catch (error) {
221
+ void error
222
+ }
223
+ }
224
+
225
+ /** Legacy local-storage prefix, read once to migrate consoles to the Host. */
226
+ const DW_CONSOLE_KEY = 'dsh-data-window:consoles'
227
+
228
+ /** Client-side preferences edited in the plugin's settings section. */
229
+ const DW_PREFS_KEY = 'dsh-data-window:prefs'
230
+
231
+ /** Read the display preferences, tolerating a blocked storage. */
232
+ function dwReadPrefs() {
233
+ const fallback = { autoHideSidebar: true, defaultLimit: 0, shortcutOpen: null, aiModel: null }
234
+ try {
235
+ const parsed = JSON.parse(globalThis.localStorage?.getItem(DW_PREFS_KEY) ?? '{}')
236
+ const limit = Number(parsed?.defaultLimit)
237
+ const raw = parsed?.shortcutOpen
238
+ const shortcutOpen = raw !== null && raw !== undefined && typeof raw.code === 'string' && raw.code !== ''
239
+ ? {
240
+ code: raw.code,
241
+ modifiers: (Array.isArray(raw.modifiers) ? raw.modifiers : []).filter((name) => ['meta', 'ctrl', 'alt', 'shift'].includes(name)),
242
+ }
243
+ : null
244
+ const rawModel = parsed?.aiModel
245
+ const aiModel = rawModel !== null && rawModel !== undefined
246
+ && typeof rawModel.provider === 'string' && rawModel.provider !== ''
247
+ && typeof rawModel.model === 'string' && rawModel.model !== ''
248
+ ? {
249
+ provider: rawModel.provider,
250
+ model: rawModel.model,
251
+ name: typeof rawModel.name === 'string' && rawModel.name !== '' ? rawModel.name : rawModel.model,
252
+ }
253
+ : null
254
+ return {
255
+ autoHideSidebar: parsed?.autoHideSidebar !== false,
256
+ defaultLimit: Number.isFinite(limit) && limit > 0 ? limit : 0,
257
+ shortcutOpen,
258
+ aiModel,
259
+ }
260
+ } catch (error) {
261
+ return fallback
262
+ }
263
+ }
264
+
265
+ /** Merge and persist display preferences. */
266
+ function dwWritePrefs(changes) {
267
+ const next = { ...dwReadPrefs(), ...changes }
268
+ try {
269
+ globalThis.localStorage?.setItem(DW_PREFS_KEY, JSON.stringify(next))
270
+ } catch (error) {
271
+ void error
272
+ }
273
+ return next
274
+ }
275
+
276
+ /** Restore the SQL consoles saved for one workspace. */
277
+ function dwReadConsoles(root) {
278
+ const empty = { tabs: [], activeTab: '' }
279
+ if (typeof root !== 'string' || root === '') return empty
280
+ try {
281
+ const raw = globalThis.localStorage?.getItem(`${DW_CONSOLE_KEY}:${root}`)
282
+ if (raw === null || raw === undefined) return empty
283
+ const parsed = JSON.parse(raw)
284
+ const tabs = (Array.isArray(parsed?.tabs) ? parsed.tabs : [])
285
+ .filter((tab) => tab !== null && typeof tab === 'object' && typeof tab.id === 'string' && typeof tab.dbId === 'string')
286
+ .map((tab) => ({
287
+ id: tab.id,
288
+ kind: 'sql',
289
+ title: String(tab.title ?? tab.database ?? ''),
290
+ env: String(tab.env ?? ''),
291
+ subtitle: String(tab.subtitle ?? ''),
292
+ dbId: tab.dbId,
293
+ database: String(tab.database ?? ''),
294
+ instanceLabel: String(tab.instanceLabel ?? ''),
295
+ sql: String(tab.sql ?? ''),
296
+ result: undefined,
297
+ error: '',
298
+ running: false,
299
+ }))
300
+ const activeTab = tabs.some((tab) => tab.id === parsed?.activeTab) ? parsed.activeTab : (tabs[0]?.id ?? '')
301
+ return { tabs, activeTab }
302
+ } catch (error) {
303
+ return empty
304
+ }
305
+ }
306
+
307
+
308
+ function dwCreateStore(translate) {
309
+ const t = typeof translate === 'function' ? translate : (key) => key
310
+
311
+ let state = {
312
+ // workspace
313
+ root: '',
314
+ detected: '',
315
+ manual: false,
316
+ // Loaded once, so a workspace picked by hand wins from the first paint instead
317
+ // of losing a race against the shell's own detection.
318
+ preferred: dwStoredRoot(),
319
+ phase: 'idle',
320
+ refreshing: false,
321
+ project: null,
322
+ environments: [],
323
+ warnings: [],
324
+ discoveryError: '',
325
+ discoveryMs: 0,
326
+ fromCache: false,
327
+ settings: null,
328
+ /** True while an AI fallback scan is running; the dialog owns the result. */
329
+ aiRunning: false,
330
+ // tree
331
+ filter: '',
332
+ expanded: new Set(),
333
+ loadState: new Map(),
334
+ children: new Map(),
335
+ selected: '',
336
+ selectedNode: null,
337
+ // workbench
338
+ tabs: [],
339
+ activeTab: '',
340
+ // Table/column maps for the editor's completion, one per database.
341
+ schemas: new Map(),
342
+ limit: DW_DEFAULT_LIMIT,
343
+ // log
344
+ logOpen: false,
345
+ log: [dwLogEntry('info', t('log.ready'))],
346
+ }
347
+
348
+ const listeners = new Set()
349
+ const getState = () => state
350
+ const subscribe = (listener) => {
351
+ listeners.add(listener)
352
+ return () => listeners.delete(listener)
353
+ }
354
+ const emit = () => {
355
+ for (const listener of [...listeners]) listener()
356
+ }
357
+ const patch = (changes) => {
358
+ state = { ...state, ...changes }
359
+ emit()
360
+ }
361
+
362
+
363
+ const pushLog = (level, text) => {
364
+ const next = [...state.log, dwLogEntry(level, text)]
365
+ patch({ log: next.length > DW_LOG_LIMIT ? next.slice(next.length - DW_LOG_LIMIT) : next })
366
+ }
367
+
368
+ /** Run one Host call, retrying once after a rediscovery when the Host forgot us. */
369
+ const call = async (action, payload) => {
370
+ try {
371
+ return await dwRpc(action, payload)
372
+ } catch (error) {
373
+ if (error?.code !== 'unknown-target' || state.root === '') throw error
374
+ pushLog('warn', t('log.hostRestarted'))
375
+ await store.loadDiscovery({ refresh: true, quiet: true })
376
+ return await dwRpc(action, payload)
377
+ }
378
+ }
379
+
380
+ // SQL is the user's work: the Host keeps one snapshot per workspace so switching
381
+ // workspaces or restarting DSH does not throw the statement away. Writes are
382
+ // debounced because they happen on every keystroke; results are never saved.
383
+ const consoleSnapshot = () => ({
384
+ activeTab: state.activeTab,
385
+ tabs: state.tabs
386
+ .filter((tab) => tab.kind === 'sql' && typeof tab.dbId === 'string')
387
+ .map((tab) => ({
388
+ id: tab.id,
389
+ title: tab.title,
390
+ env: tab.env,
391
+ subtitle: tab.subtitle,
392
+ dbId: tab.dbId,
393
+ database: tab.database,
394
+ instanceLabel: tab.instanceLabel,
395
+ sql: String(tab.sql ?? ''),
396
+ })),
397
+ })
398
+
399
+ const saveConsoles = async () => {
400
+ const root = state.root
401
+ if (root === '') return
402
+ try {
403
+ await call('saveConsoles', { root, value: consoleSnapshot() })
404
+ } catch (error) {
405
+ void error
406
+ }
407
+ }
408
+
409
+ let consoleTimer = null
410
+ const scheduleConsoles = () => {
411
+ if (consoleTimer !== null) clearTimeout(consoleTimer)
412
+ consoleTimer = setTimeout(() => {
413
+ consoleTimer = null
414
+ void saveConsoles()
415
+ }, 250)
416
+ }
417
+ const flushConsoles = () => {
418
+ if (consoleTimer !== null) {
419
+ clearTimeout(consoleTimer)
420
+ consoleTimer = null
421
+ }
422
+ void saveConsoles()
423
+ }
424
+
425
+ /** Merge a saved snapshot into whatever is already open, never clobbering it. */
426
+ const applyConsoles = (root, saved) => {
427
+ if (state.root !== root) return
428
+ const existing = new Set(state.tabs.map((tab) => tab.id))
429
+ const restored = (Array.isArray(saved?.tabs) ? saved.tabs : [])
430
+ .filter((tab) => tab !== null && typeof tab.id === 'string' && typeof tab.dbId === 'string' && !existing.has(tab.id))
431
+ .map((tab) => ({
432
+ id: tab.id,
433
+ kind: 'sql',
434
+ title: String(tab.title ?? ''),
435
+ env: String(tab.env ?? ''),
436
+ subtitle: String(tab.subtitle ?? ''),
437
+ dbId: tab.dbId,
438
+ database: String(tab.database ?? ''),
439
+ instanceLabel: String(tab.instanceLabel ?? ''),
440
+ sql: String(tab.sql ?? ''),
441
+ result: undefined,
442
+ error: '',
443
+ running: false,
444
+ }))
445
+ if (restored.length === 0) return
446
+ const sequence = restored.reduce((max, tab) => {
447
+ const match = /:(\d+)$/.exec(tab.id)
448
+ return match === null ? max : Math.max(max, Number(match[1]))
449
+ }, 0)
450
+ if (sequence > dwStatementSequence) dwStatementSequence = sequence
451
+ const tabs = [...restored, ...state.tabs]
452
+ const activeTab = state.activeTab === '' && tabs.some((tab) => tab.id === saved.activeTab) ? saved.activeTab : state.activeTab
453
+ patch({ tabs, activeTab })
454
+ }
455
+
456
+ const loadConsoles = async (root) => {
457
+ const local = dwReadConsoles(root)
458
+ let saved = null
459
+ try {
460
+ saved = await call('consoles', { root })
461
+ } catch (error) {
462
+ void error
463
+ }
464
+ if (saved !== null && Array.isArray(saved.tabs) && saved.tabs.length > 0) {
465
+ applyConsoles(root, saved)
466
+ return
467
+ }
468
+ // One-time migration: snapshots written by the localStorage build move to the
469
+ // Host the first time their workspace opens.
470
+ if (local.tabs.length === 0) return
471
+ applyConsoles(root, local)
472
+ try {
473
+ await call('saveConsoles', { root, value: { activeTab: local.activeTab, tabs: local.tabs } })
474
+ globalThis.localStorage?.removeItem(`${DW_CONSOLE_KEY}:${root}`)
475
+ } catch (error) {
476
+ void error
477
+ }
478
+ }
479
+
480
+ const store = {
481
+ getState,
482
+ subscribe,
483
+ patch,
484
+ pushLog,
485
+ call,
486
+ t,
487
+
488
+ /** What the overlay tracker last resolved, so a remount keeps the project. */
489
+ detectedRoot() {
490
+ return state.detected
491
+ },
492
+
493
+ /**
494
+ * Record the workspace the shell is showing.
495
+ *
496
+ * The window follows it unless the user picked another directory, which is the
497
+ * whole point of requirement 1: switching workspace switches the database
498
+ * window, and the previous project's tree and tabs are not kept.
499
+ */
500
+ setDetectedRoot(root) {
501
+ const next = typeof root === 'string' ? root : ''
502
+ if (next === '') return
503
+ if (state.detected !== next) patch({ detected: next })
504
+ if (state.preferred !== '') {
505
+ // A stored choice outlives a reload. It is applied as a manual pick, which
506
+ // is what keeps the follow-workspace button meaningful.
507
+ if (state.root !== state.preferred) {
508
+ patch({ manual: true })
509
+ store.setRoot(state.preferred)
510
+ }
511
+ return
512
+ }
513
+ if (state.root !== next) store.setRoot(next)
514
+ },
515
+
516
+ /** Drop a manual pick and follow the shell's workspace again. */
517
+ followDetected() {
518
+ dwPersistRoot('')
519
+ patch({ manual: false, preferred: '' })
520
+ if (state.detected !== '' && state.detected !== state.root) store.setRoot(state.detected)
521
+ },
522
+
523
+ /** Follow a workspace chosen by hand instead of the shell's. */
524
+ setManualRoot(root) {
525
+ const next = typeof root === 'string' ? root : ''
526
+ if (next === '') return
527
+ dwPersistRoot(next)
528
+ patch({ manual: true, preferred: next })
529
+ store.setRoot(next)
530
+ },
531
+
532
+ /** Show the panel with nothing loaded yet. */
533
+ reset() {
534
+ flushConsoles()
535
+ patch({
536
+ root: '',
537
+ manual: false,
538
+ phase: 'idle',
539
+ refreshing: false,
540
+ project: null,
541
+ environments: [],
542
+ warnings: [],
543
+ discoveryError: '',
544
+ filter: '',
545
+ expanded: new Set(),
546
+ loadState: new Map(),
547
+ children: new Map(),
548
+ selected: '',
549
+ selectedNode: null,
550
+ tabs: [],
551
+ activeTab: '',
552
+ schemas: new Map(),
553
+ })
554
+ },
555
+
556
+ /**
557
+ * Point the window at one workspace.
558
+ *
559
+ * A changed root resets the tree and the workbench: another project's databases
560
+ * have nothing to do with this one.
561
+ */
562
+ setRoot(root) {
563
+ const next = typeof root === 'string' ? root : ''
564
+ if (next === state.root) return
565
+ flushConsoles()
566
+ if (next === '') {
567
+ store.reset()
568
+ return
569
+ }
570
+ patch({
571
+ root: next,
572
+ phase: 'loading',
573
+ project: null,
574
+ environments: [],
575
+ warnings: [],
576
+ discoveryError: '',
577
+ filter: '',
578
+ expanded: new Set(),
579
+ loadState: new Map(),
580
+ children: new Map(),
581
+ selected: '',
582
+ selectedNode: null,
583
+ tabs: [],
584
+ activeTab: '',
585
+ schemas: new Map(),
586
+ })
587
+ void loadConsoles(next)
588
+ void store.loadDiscovery({ refresh: false })
589
+ void store.loadSettings()
590
+ },
591
+
592
+ /** One Host round trip for the tunables the panel mirrors. */
593
+ async loadSettings() {
594
+ try {
595
+ const settings = await dwRpc('config')
596
+ const configured = Number(settings?.defaultLimit)
597
+ const preferred = dwReadPrefs().defaultLimit
598
+ const limit = preferred > 0 ? preferred : (Number.isFinite(configured) && configured > 0 ? configured : state.limit)
599
+ patch({ settings, limit })
600
+ } catch (error) {
601
+ void error
602
+ }
603
+ },
604
+
605
+ /** Read the workspace's configuration through the Host. */
606
+ async loadDiscovery(options = {}) {
607
+ const root = state.root
608
+ if (root === '') return
609
+ const refreshing = options.refresh === true
610
+ patch({
611
+ phase: state.environments.length === 0 ? 'loading' : state.phase,
612
+ refreshing,
613
+ discoveryError: '',
614
+ })
615
+ const startedAt = Date.now()
616
+ try {
617
+ const discovery = await dwRpc('discover', { root, refresh: refreshing })
618
+ if (state.root !== root) return
619
+ const environments = Array.isArray(discovery.environments) ? discovery.environments : []
620
+ const defaultEnv = discovery.defaultEnv ?? environments[0]?.env
621
+ const focus = Array.isArray(discovery.focus?.envs) ? discovery.focus.envs : []
622
+ const focusInstances = Array.isArray(discovery.focus?.instances) ? discovery.focus.instances : []
623
+ const base = refreshing ? new Set() : new Set(state.expanded)
624
+ for (const environment of environments) {
625
+ // Manual environments are the ones the user just created, so they open
626
+ // expanded; the shared tree also opens the environments this workspace
627
+ // contributes (or its default one when the Host reports no focus).
628
+ if (environment.env === defaultEnv || environment.manual === true) base.add(dwNodeKey('env', environment.env))
629
+ }
630
+ for (const env of focus) {
631
+ if (typeof env === 'string' && env !== '') base.add(dwNodeKey('env', env))
632
+ }
633
+ // Expanding the environment alone still hides the database behind a closed
634
+ // instance row; the workspace's own instances open too, so its databases are
635
+ // visible the moment the window appears.
636
+ for (const instanceId of focusInstances) {
637
+ if (typeof instanceId === 'string' && instanceId !== '') base.add(dwNodeKey('inst', instanceId))
638
+ }
639
+ patch({
640
+ phase: environments.length === 0 ? 'empty' : 'ready',
641
+ refreshing: false,
642
+ project: discovery.project ?? null,
643
+ environments,
644
+ warnings: Array.isArray(discovery.warnings) ? discovery.warnings : [],
645
+ discoveryMs: Date.now() - startedAt,
646
+ fromCache: discovery.cached === true,
647
+ expanded: base,
648
+ // A reload replaces the metadata too: keeping a cached table list after
649
+ // the user asked for a reload is exactly the stale tree they asked about.
650
+ children: refreshing ? new Map() : state.children,
651
+ loadState: refreshing ? new Map() : state.loadState,
652
+ })
653
+ if (options.quiet !== true) {
654
+ const databases = environments.reduce((total, environment) => total + (environment.databaseCount ?? 0), 0)
655
+ pushLog('info', t('log.discovered', {
656
+ envs: environments.length,
657
+ databases,
658
+ cached: discovery.cached === true ? t('log.cachedSuffix') : '',
659
+ }))
660
+ }
661
+ } catch (error) {
662
+ if (state.root !== root) return
663
+ patch({ phase: 'error', refreshing: false, discoveryError: dwExplainFailure(t, error) })
664
+ pushLog('error', t('log.discoverFailed', { message: dwExplainFailure(t, error) }))
665
+ }
666
+ },
667
+
668
+ /**
669
+ * Ask the Host to read the workspace with one model.
670
+ *
671
+ * The Host resolves the credential from the file the model cited and proves
672
+ * the address with a real connection, so whatever comes back is already safe
673
+ * to render; anything unproven stays a warning.
674
+ */
675
+ async runAiDiscovery(selection) {
676
+ const root = state.root
677
+ if (root === '') return { ok: false, error: t('aiNoWorkspace') }
678
+ const provider = String(selection?.provider ?? '')
679
+ const model = String(selection?.model ?? '')
680
+ if (provider === '' || model === '') return { ok: false, error: t('aiNeedModel') }
681
+ if (state.aiRunning === true) return { ok: false, error: t('aiBusy') }
682
+ patch({ aiRunning: true })
683
+ pushLog('info', t('log.aiStart', { model: selection?.name ?? model }))
684
+ const startedAt = Date.now()
685
+ try {
686
+ const value = await dwRpc('aiDiscover', { root, provider, model })
687
+ if (state.root !== root) return { ok: false, error: '' }
688
+ const environments = dwMergeEnvironments(state.environments, value?.environments)
689
+ const expanded = new Set(state.expanded)
690
+ for (const environment of Array.isArray(value?.environments) ? value.environments : []) {
691
+ expanded.add(dwNodeKey('env', environment.env))
692
+ }
693
+ patch({
694
+ aiRunning: false,
695
+ environments,
696
+ expanded,
697
+ phase: environments.length === 0 ? 'empty' : 'ready',
698
+ warnings: [...new Set([...state.warnings, ...(Array.isArray(value?.warnings) ? value.warnings : [])])],
699
+ })
700
+ pushLog('info', t('log.aiDone', {
701
+ accepted: Number(value?.accepted ?? 0),
702
+ candidates: Number(value?.candidates ?? 0),
703
+ ms: dwDuration(Number(value?.elapsedMs ?? Date.now() - startedAt)),
704
+ }))
705
+ return { ok: true, value }
706
+ } catch (error) {
707
+ if (state.root !== root) return { ok: false, error: '' }
708
+ patch({ aiRunning: false })
709
+ const message = dwExplainFailure(t, error)
710
+ pushLog('error', t('log.aiFailed', { message }))
711
+ return { ok: false, error: message }
712
+ }
713
+ },
714
+
715
+ /** Keep a database the user opened from an instance's full list. */
716
+ async rememberDatabase(node) {
717
+ const root = state.root
718
+ const instanceId = dwInstanceIdOf(node?.dbId)
719
+ const database = String(node?.database ?? '')
720
+ if (root === '' || instanceId === '' || database === '') return
721
+ try {
722
+ const value = await dwRpc('rememberDatabase', { root, instanceId, database })
723
+ if (value?.remembered === true) pushLog('info', t('log.remembered', { database }))
724
+ } catch (error) {
725
+ // Remembering is a convenience: a workspace that cannot write its store
726
+ // still keeps the database open in this session.
727
+ void error
728
+ }
729
+ },
730
+
731
+ /** Drop a remembered database and re-read the tree without it. */
732
+ async forgetDatabase(node) {
733
+ const root = state.root
734
+ const instanceId = dwInstanceIdOf(node?.dbId)
735
+ const database = String(node?.database ?? '')
736
+ if (root === '' || instanceId === '' || database === '') return
737
+ try {
738
+ await dwRpc('forgetDatabase', { root, instanceId, database })
739
+ pushLog('info', t('log.forgotDatabase', { database }))
740
+ await store.loadDiscovery({ quiet: true })
741
+ } catch (error) {
742
+ pushLog('error', t('log.forgetDatabaseFailed', { message: dwExplainFailure(t, error) }))
743
+ }
744
+ },
745
+
746
+ /** Delete a whole manually added environment, then re-read the tree. */
747
+ async removeManualEnvironment(label) {
748
+ const root = state.root
749
+ const name = String(label ?? '').trim()
750
+ if (root === '' || name === '') return
751
+ try {
752
+ await dwRpc('removeManualEnvironment', { root, from: name })
753
+ pushLog('info', t('log.removedEnvironment', { name }))
754
+ await store.loadDiscovery({ quiet: true })
755
+ } catch (error) {
756
+ pushLog('error', t('log.removeEnvironmentFailed', { message: dwExplainFailure(t, error) }))
757
+ }
758
+ },
759
+
760
+ /** Remove one manually added connection, then re-read the tree. */
761
+ async removeManual(entryId) {
762
+ const root = state.root
763
+ if (root === '' || typeof entryId !== 'string' || entryId === '') return
764
+ try {
765
+ await dwRpc('manualRemove', { root, id: entryId })
766
+ pushLog('info', t('log.manualRemoved'))
767
+ await store.loadDiscovery({ quiet: true })
768
+ } catch (error) {
769
+ pushLog('error', t('log.manualRemoveFailed', { message: dwExplainFailure(t, error) }))
770
+ }
771
+ },
772
+
773
+ /** Expand or collapse one tree node, loading its children on first open. */
774
+ async toggleNode(node) {
775
+ if (node === null || node === undefined) return
776
+ const expanded = new Set(state.expanded)
777
+ if (expanded.has(node.key)) {
778
+ expanded.delete(node.key)
779
+ patch({ expanded })
780
+ return
781
+ }
782
+ expanded.add(node.key)
783
+ patch({ expanded })
784
+ await store.ensureChildren(node)
785
+ },
786
+
787
+ /** Add keys to the expansion set without toggling them. */
788
+ expand(...keys) {
789
+ const expanded = new Set(state.expanded)
790
+ for (const key of keys) if (typeof key === 'string' && key !== '') expanded.add(key)
791
+ patch({ expanded })
792
+ },
793
+
794
+ /**
795
+ * Re-read one node's structure from the server.
796
+ *
797
+ * Connection: the inventory comes from discovery, so the workspace scan runs
798
+ * again. Database/table: drop the cached children, expand the row and fetch the
799
+ * new list (tables or columns), so a structure changed outside the window shows
800
+ * up without reloading the panel. An open DDL tab is refreshed too.
801
+ */
802
+ async refreshNode(node) {
803
+ if (node === null || node === undefined) return
804
+ if (node.kind === 'instance') {
805
+ patch({ children: new Map(), loadState: new Map(), schemas: new Map() })
806
+ pushLog('info', t('log.refreshingConnection', { name: node.label }))
807
+ await store.loadDiscovery({ refresh: true })
808
+ return
809
+ }
810
+ if (node.kind !== 'database' && node.kind !== 'table' && node.kind !== 'view') return
811
+ const children = new Map(state.children)
812
+ children.delete(node.key)
813
+ const loadState = new Map(state.loadState)
814
+ loadState.delete(node.key)
815
+ const expanded = new Set(state.expanded)
816
+ expanded.add(node.key)
817
+ patch({ children, loadState, expanded })
818
+ // Completion is built from a per-database map that goes stale with the tables.
819
+ const schemas = new Map(state.schemas ?? [])
820
+ schemas.delete(node.dbId)
821
+ patch({ schemas })
822
+ void store.loadSchema(node.dbId)
823
+ await store.ensureChildren(node)
824
+ if (state.loadState.get(node.key) === 'error') return
825
+ pushLog('info', t('log.refreshedStructure', { name: node.label }))
826
+ },
827
+
828
+ /** Forget one node's cached children so the next expand re-reads them. */
829
+ retryNode(node) {
830
+ if (node === null || node === undefined) return
831
+ const children = new Map(state.children)
832
+ children.delete(node.key)
833
+ const loadState = new Map(state.loadState)
834
+ loadState.delete(node.key)
835
+ patch({ children, loadState })
836
+ void store.ensureChildren(node)
837
+ },
838
+
839
+ /** Load the children a node needs, once. */
840
+ async ensureChildren(node) {
841
+ if (node === null || node === undefined) return
842
+ if (node.kind === 'env') return
843
+ // Databases are an explicit choice made in the schema picker, not a list the
844
+ // tree fills in on expand: expanding an instance only reveals what was picked.
845
+ if (node.kind === 'instance') return
846
+ if (node.kind !== 'database' && node.kind !== 'table' && node.kind !== 'view') return
847
+ if (Array.isArray(state.children.get(node.key))) return
848
+ if (state.loadState.get(node.key) === 'loading') return
849
+ const loadState = new Map(state.loadState)
850
+ loadState.set(node.key, 'loading')
851
+ patch({ loadState })
852
+ try {
853
+ if (node.kind === 'database') {
854
+ const value = await call('tables', { id: node.dbId })
855
+ const children = (value.tables ?? []).map((table) => ({
856
+ key: dwNodeKey('tbl', node.dbId, table.name),
857
+ kind: table.kind === 'view' ? 'view' : 'table',
858
+ label: table.name,
859
+ detail: table.comment !== '' ? table.comment : table.rows > 0 ? dwRowCount(table.rows) : '',
860
+ dbId: node.dbId,
861
+ database: node.database,
862
+ env: node.env,
863
+ instanceLabel: node.instanceLabel,
864
+ table: table.name,
865
+ info: table,
866
+ }))
867
+ const nextChildren = new Map(state.children)
868
+ nextChildren.set(node.key, children)
869
+ const nextState = new Map(state.loadState)
870
+ nextState.set(node.key, 'ready')
871
+ patch({ children: nextChildren, loadState: nextState })
872
+ pushLog('info', t('log.tables', { database: node.database, count: children.length, ms: dwDuration(value.elapsedMs) }))
873
+ return
874
+ }
875
+ const value = await call('columns', { id: node.dbId, table: node.table })
876
+ const children = (value.columns ?? []).map((column) => ({
877
+ key: dwNodeKey('col', node.dbId, node.table, column.name),
878
+ kind: 'column',
879
+ label: column.name,
880
+ detail: column.type,
881
+ column,
882
+ dbId: node.dbId,
883
+ database: node.database,
884
+ env: node.env,
885
+ instanceLabel: node.instanceLabel,
886
+ table: node.table,
887
+ }))
888
+ const nextChildren = new Map(state.children)
889
+ nextChildren.set(node.key, children)
890
+ const nextState = new Map(state.loadState)
891
+ nextState.set(node.key, 'ready')
892
+ patch({ children: nextChildren, loadState: nextState })
893
+ } catch (error) {
894
+ // A failure stays a load state, not a fake child row: a child would make
895
+ // every later expand a no-op and only a restart could clear it.
896
+ const nextState = new Map(state.loadState)
897
+ nextState.set(node.key, 'error')
898
+ patch({ loadState: nextState })
899
+ pushLog('error', t('log.loadFailed', { name: node.label, message: dwExplainFailure(t, error) }))
900
+ }
901
+ },
902
+
903
+ /**
904
+ * Load the table/column map the editor completes against.
905
+ *
906
+ * Failure is silent: suggestions degrade to keywords instead of turning a
907
+ * focus event into an error banner.
908
+ */
909
+ async loadSchema(dbId) {
910
+ if (typeof dbId !== 'string' || dbId === '') return
911
+ if (state.schemas?.has(dbId)) return
912
+ try {
913
+ const value = await call('schema', { id: dbId })
914
+ const schemas = new Map(state.schemas ?? [])
915
+ schemas.set(dbId, value)
916
+ patch({ schemas })
917
+ } catch (error) {
918
+ void error
919
+ }
920
+ },
921
+
922
+ /** Reveal every schema on one instance, not only the configured ones. */
923
+ /** Select one row; a table also becomes the target of the DDL shortcut. */
924
+ select(node) {
925
+ patch({ selected: node?.key ?? '', selectedNode: node ?? null })
926
+ },
927
+
928
+ /**
929
+ * Open (or focus) the SQL workbench of one database.
930
+ *
931
+ * @returns the tab, so a caller may seed a statement only when the console is
932
+ * still empty.
933
+ */
934
+ openDatabase(node) {
935
+ if (node === null || node === undefined || node.dbId === undefined) return undefined
936
+ const id = `sql:${node.dbId}`
937
+ const existing = state.tabs.find((tab) => tab.id === id)
938
+ if (existing !== undefined) {
939
+ patch({ activeTab: id })
940
+ scheduleConsoles()
941
+ if (node.configured === false) void store.rememberDatabase(node)
942
+ return existing
943
+ }
944
+ const tab = {
945
+ id,
946
+ kind: 'sql',
947
+ title: node.database,
948
+ env: node.env ?? '',
949
+ subtitle: [node.env, node.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
950
+ dbId: node.dbId,
951
+ database: node.database,
952
+ instanceLabel: node.instanceLabel ?? '',
953
+ // An empty console, so the placeholder explains what to do; a canned
954
+ // statement would be overwritten by the user's first keystroke anyway.
955
+ sql: '',
956
+ result: undefined,
957
+ error: '',
958
+ running: false,
959
+ }
960
+ patch({ tabs: [...state.tabs, tab], activeTab: id })
961
+ scheduleConsoles()
962
+ // Opening a schema that is not part of the configuration makes it part of the
963
+ // workspace: the next discovery lists it next to the configured databases.
964
+ if (node.configured === false) void store.rememberDatabase(node)
965
+ return tab
966
+ },
967
+
968
+ /**
969
+ * Put a statement in a workbench without destroying what the user typed.
970
+ *
971
+ * A tree action ("open table data") must never cost the user an unsaved
972
+ * query, so an occupied console gets a second tab instead.
973
+ */
974
+ /**
975
+ * Open one table's own console and append its base query.
976
+ *
977
+ * Requirement: one window per table per workspace. Double-clicking the same
978
+ * table again focuses that window and appends one more statement at the bottom
979
+ * instead of stacking numbered consoles; the user's text is only ever extended,
980
+ * never replaced.
981
+ */
982
+ seedStatement(node, sql) {
983
+ if (node === null || node === undefined || node.dbId === undefined || node.table === undefined) return
984
+ const statement = String(sql ?? '').trim()
985
+ if (statement === '') return
986
+ const id = `sql:${node.dbId}:tbl:${node.table}`
987
+ const existing = state.tabs.find((tab) => tab.id === id)
988
+ if (existing !== undefined) {
989
+ const current = String(existing.sql ?? '').replace(/\s+$/, '')
990
+ patch({
991
+ tabs: state.tabs.map((tab) => (tab.id === id
992
+ ? { ...tab, sql: current === '' ? statement : `${current}\n\n${statement}`, result: undefined, error: '' }
993
+ : tab)),
994
+ })
995
+ store.setActiveTab(id)
996
+ scheduleConsoles()
997
+ return
998
+ }
999
+ const tab = {
1000
+ id,
1001
+ kind: 'sql',
1002
+ title: String(node.table),
1003
+ env: node.env ?? '',
1004
+ subtitle: [node.env, node.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
1005
+ dbId: node.dbId,
1006
+ database: node.database,
1007
+ instanceLabel: node.instanceLabel ?? '',
1008
+ sql: statement,
1009
+ result: undefined,
1010
+ error: '',
1011
+ }
1012
+ patch({ tabs: [...state.tabs, tab], activeTab: id })
1013
+ scheduleConsoles()
1014
+ },
1015
+
1016
+ /**
1017
+ * Open a console from the code workspace with a statement already pasted.
1018
+ *
1019
+ * Keyed by the caller's title, so jumping to the same mapper method twice
1020
+ * focuses the same tab. Only appends: the user's existing text is never
1021
+ * replaced, and the same block is not pasted twice.
1022
+ */
1023
+ openSqlConsole(input) {
1024
+ const sql = String(input?.sql ?? '').trim()
1025
+ if (sql === '' || typeof input?.dbId !== 'string' || input.dbId === '') return undefined
1026
+ const title = String(input.title ?? '').trim() || 'SQL'
1027
+ const id = `sql:${input.dbId}:code:${encodeURIComponent(title)}`
1028
+ const block = `-- ${title}\n${sql}`
1029
+ const existing = state.tabs.find((tab) => tab.id === id)
1030
+ if (existing !== undefined) {
1031
+ const current = String(existing.sql ?? '').replace(/\s+$/, '')
1032
+ const next = current === '' ? block : current.includes(block) ? current : `${current}\n\n${block}`
1033
+ patch({ tabs: state.tabs.map((tab) => (tab.id === id ? { ...tab, sql: next } : tab)) })
1034
+ store.setActiveTab(id)
1035
+ scheduleConsoles()
1036
+ return state.tabs.find((tab) => tab.id === id)
1037
+ }
1038
+ const tab = {
1039
+ id,
1040
+ kind: 'sql',
1041
+ title,
1042
+ env: input.env ?? '',
1043
+ subtitle: [input.env, input.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
1044
+ dbId: input.dbId,
1045
+ database: input.database ?? '',
1046
+ instanceLabel: input.instanceLabel ?? '',
1047
+ sql: block,
1048
+ result: undefined,
1049
+ error: '',
1050
+ }
1051
+ patch({ tabs: [...state.tabs, tab], activeTab: id })
1052
+ scheduleConsoles()
1053
+ // Opening a schema that is not part of the configuration makes it part of the
1054
+ // workspace: the next discovery lists it next to the configured databases.
1055
+ if (node.configured === false) void store.rememberDatabase(node)
1056
+ return tab
1057
+ },
1058
+
1059
+ /** Close one or more tabs and keep the active selection on a neighbour. */
1060
+ closeTabs(ids) {
1061
+ const removing = new Set(Array.isArray(ids) ? ids : [])
1062
+ if (removing.size === 0) return
1063
+ const tabs = state.tabs.filter((tab) => !removing.has(tab.id))
1064
+ let activeTab = state.activeTab
1065
+ if (removing.has(activeTab)) {
1066
+ const index = state.tabs.findIndex((tab) => tab.id === activeTab)
1067
+ const neighbour = state.tabs.slice(index + 1).find((tab) => !removing.has(tab.id))
1068
+ ?? state.tabs.slice(0, index).reverse().find((tab) => !removing.has(tab.id))
1069
+ activeTab = neighbour?.id ?? ''
1070
+ }
1071
+ patch({ tabs, activeTab })
1072
+ // Closing a console is deliberate: drop it from storage now, not later.
1073
+ flushConsoles()
1074
+ },
1075
+
1076
+ closeTab(id) {
1077
+ store.closeTabs([id])
1078
+ },
1079
+
1080
+ closeOtherTabs(id) {
1081
+ store.closeTabs(state.tabs.filter((tab) => tab.id !== id).map((tab) => tab.id))
1082
+ },
1083
+
1084
+ closeAllTabs() {
1085
+ store.closeTabs(state.tabs.map((tab) => tab.id))
1086
+ },
1087
+
1088
+ closeTabsToLeft(id) {
1089
+ const index = state.tabs.findIndex((tab) => tab.id === id)
1090
+ if (index <= 0) return
1091
+ store.closeTabs(state.tabs.slice(0, index).map((tab) => tab.id))
1092
+ },
1093
+
1094
+ closeTabsToRight(id) {
1095
+ const index = state.tabs.findIndex((tab) => tab.id === id)
1096
+ if (index < 0) return
1097
+ store.closeTabs(state.tabs.slice(index + 1).map((tab) => tab.id))
1098
+ },
1099
+
1100
+ setActiveTab(id) {
1101
+ patch({ activeTab: id })
1102
+ scheduleConsoles()
1103
+ },
1104
+
1105
+ setTabSql(id, sql) {
1106
+ patch({ tabs: state.tabs.map((tab) => (tab.id === id ? { ...tab, sql } : tab)) })
1107
+ scheduleConsoles()
1108
+ },
1109
+
1110
+ setLimit(limit) {
1111
+ patch({ limit })
1112
+ },
1113
+
1114
+ setLogOpen(open) {
1115
+ patch({ logOpen: open })
1116
+ },
1117
+
1118
+ /** Run the active tab's statement. */
1119
+ /**
1120
+ * Count every row of the statement that produced the current result.
1121
+ *
1122
+ * Deliberately on demand: COUNT(*) on a large table is a second full scan, so
1123
+ * it runs when the user presses the refresh button, not after every query.
1124
+ */
1125
+ async refreshTotal(id) {
1126
+ const tab = state.tabs.find((entry) => entry.id === id)
1127
+ if (tab === undefined || tab.kind !== 'sql' || tab.counting === true) return
1128
+ const sql = String(tab.lastStatement ?? tab.sql ?? '').trim()
1129
+ if (sql === '') return
1130
+ patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, counting: true, countError: '' } : entry)) })
1131
+ try {
1132
+ const value = await call('count', { id: tab.dbId, sql })
1133
+ if (typeof value.sql === 'string' && value.sql !== '') pushLog('sql', value.sql)
1134
+ pushLog('info', t('log.count', {
1135
+ rows: dwRowCount(value.total),
1136
+ ms: dwDuration(value.elapsedMs),
1137
+ }))
1138
+ patch({
1139
+ tabs: state.tabs.map((entry) => (entry.id === id
1140
+ ? { ...entry, counting: false, totalCount: Number(value.total ?? 0), countError: '' }
1141
+ : entry)),
1142
+ })
1143
+ } catch (error) {
1144
+ pushLog('error', dwExplainFailure(t, error))
1145
+ patch({
1146
+ tabs: state.tabs.map((entry) => (entry.id === id
1147
+ ? { ...entry, counting: false, countError: dwExplainFailure(t, error) }
1148
+ : entry)),
1149
+ })
1150
+ }
1151
+ },
1152
+
1153
+ /**
1154
+ * Run the workbench statement, or just the text the user selected.
1155
+ *
1156
+ * DataGrip runs the selection; running the whole buffer while the user has a
1157
+ * fragment selected sends several statements to MySQL, which answers with a
1158
+ * confusing ER_PARSE_ERROR at the second one.
1159
+ */
1160
+ async runActiveTab(statement) {
1161
+ const tab = state.tabs.find((entry) => entry.id === state.activeTab)
1162
+ if (tab === undefined || tab.kind !== 'sql' || tab.running === true) return
1163
+ const override = typeof statement === 'string' ? statement.trim() : ''
1164
+ const sql = override !== '' ? override : String(tab.sql ?? '').trim()
1165
+ if (DW_SQL_EMPTY.test(sql)) {
1166
+ pushLog('warn', t('log.noStatement'))
1167
+ return
1168
+ }
1169
+ // A trailing LIMIT makes the result a page: the pager re-runs the statement
1170
+ // with another OFFSET instead of asking the user to edit the SQL. Only
1171
+ // SELECT/WITH statements are paged — `SHOW … LIMIT` has no OFFSET form.
1172
+ const page = /^\s*(select|with)\b/i.test(sql) ? dwSqlPage(sql) : undefined
1173
+ // Every executed statement goes to the run log, failures included: the log is
1174
+ // the console history, not just a success report.
1175
+ pushLog('sql', sql)
1176
+ patch({
1177
+ tabs: state.tabs.map((entry) => (entry.id === tab.id
1178
+ ? { ...entry, running: true, error: '', counting: false, totalCount: undefined, countError: '' }
1179
+ : entry)),
1180
+ })
1181
+ try {
1182
+ const value = await call('query', {
1183
+ id: tab.dbId,
1184
+ sql,
1185
+ // The statement's own LIMIT is the page capacity; the row cap must not cut
1186
+ // a page short, or "returned fewer rows" would be mistaken for the end.
1187
+ limit: page === undefined ? state.limit : Math.max(state.limit, page.size),
1188
+ })
1189
+ const returned = Array.isArray(value.rows) ? value.rows.length : Number(value.rowCount ?? 0)
1190
+ patch({
1191
+ tabs: state.tabs.map((entry) => (entry.id === tab.id
1192
+ ? {
1193
+ ...entry,
1194
+ running: false,
1195
+ result: value,
1196
+ error: '',
1197
+ lastStatement: sql,
1198
+ // Cell edits belong to the rows on screen; a new result replaces them.
1199
+ edits: undefined,
1200
+ page: page === undefined ? undefined : { base: page.base, size: page.size, offset: page.offset, hasMore: returned >= page.size },
1201
+ }
1202
+ : entry)),
1203
+ })
1204
+ pushLog('info', t('log.query', {
1205
+ database: tab.database,
1206
+ rows: value.rowCount,
1207
+ ms: dwDuration(value.elapsedMs),
1208
+ truncated: value.truncated === true ? t('log.truncatedSuffix', { limit: value.limit }) : '',
1209
+ }))
1210
+ } catch (error) {
1211
+ const message = dwExplainFailure(t, error)
1212
+ patch({
1213
+ tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: false, error: message } : entry)),
1214
+ })
1215
+ pushLog('error', message)
1216
+ }
1217
+ },
1218
+
1219
+ /**
1220
+ * Move one page inside the current statement's LIMIT.
1221
+ *
1222
+ * The editor's text is never rewritten: the page statement is derived from the
1223
+ * stored base and sent directly. A next page that comes back empty ends the
1224
+ * paging without replacing the page the user is reading, so only "previous"
1225
+ * remains possible.
1226
+ */
1227
+ async goToPage(direction) {
1228
+ const tab = state.tabs.find((entry) => entry.id === state.activeTab)
1229
+ if (tab === undefined || tab.kind !== 'sql' || tab.running === true || tab.page === undefined) return
1230
+ const { base, size, offset, hasMore } = tab.page
1231
+ const forward = direction === 'next'
1232
+ if (forward && hasMore !== true) return
1233
+ const target = forward ? offset + size : Math.max(0, offset - size)
1234
+ if (!forward && target === offset) return
1235
+ const sql = `${base}\nLIMIT ${size} OFFSET ${target}`
1236
+ patch({
1237
+ tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: true, error: '' } : entry)),
1238
+ })
1239
+ try {
1240
+ const value = await call('query', { id: tab.dbId, sql, limit: Math.max(state.limit, size) })
1241
+ const returned = Array.isArray(value.rows) ? value.rows.length : 0
1242
+ if (forward && returned === 0) {
1243
+ patch({
1244
+ tabs: state.tabs.map((entry) => (entry.id === tab.id
1245
+ ? { ...entry, running: false, page: { ...tab.page, hasMore: false } }
1246
+ : entry)),
1247
+ })
1248
+ pushLog('info', t('log.pageEnd'))
1249
+ return
1250
+ }
1251
+ patch({
1252
+ tabs: state.tabs.map((entry) => (entry.id === tab.id
1253
+ ? {
1254
+ ...entry,
1255
+ running: false,
1256
+ result: value,
1257
+ error: '',
1258
+ edits: undefined,
1259
+ page: { base, size, offset: target, hasMore: returned >= size },
1260
+ }
1261
+ : entry)),
1262
+ })
1263
+ pushLog('info', t('log.page', { page: Math.floor(target / size) + 1, rows: value.rowCount, ms: dwDuration(value.elapsedMs) }))
1264
+ } catch (error) {
1265
+ const message = dwExplainFailure(t, error)
1266
+ patch({
1267
+ tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: false, error: message } : entry)),
1268
+ })
1269
+ pushLog('error', message)
1270
+ }
1271
+ },
1272
+
1273
+ /**
1274
+ * Record one edited cell.
1275
+ *
1276
+ * Edits are a local draft for building an UPDATE statement — nothing is sent to
1277
+ * the server, and the value is dropped as soon as the result changes.
1278
+ */
1279
+ setCellEdit(tabId, rowIndex, columnIndex, columnName, value) {
1280
+ const tab = state.tabs.find((entry) => entry.id === tabId)
1281
+ if (tab === undefined || tab.kind !== 'sql' || tab.result === undefined) return
1282
+ const row = (Array.isArray(tab.result.rows) ? tab.result.rows : [])[rowIndex]
1283
+ if (row === undefined) return
1284
+ const original = row[columnIndex]
1285
+ const edits = { ...(tab.edits ?? {}) }
1286
+ const rowEdits = { ...(edits[rowIndex] ?? {}) }
1287
+ const unchanged = original === null
1288
+ ? value === null || value === 'NULL'
1289
+ : String(original) === String(value)
1290
+ if (unchanged) delete rowEdits[columnName]
1291
+ else rowEdits[columnName] = value
1292
+ if (Object.keys(rowEdits).length === 0) delete edits[rowIndex]
1293
+ else edits[rowIndex] = rowEdits
1294
+ patch({
1295
+ tabs: state.tabs.map((entry) => (entry.id === tabId
1296
+ ? { ...entry, edits: Object.keys(edits).length === 0 ? undefined : edits }
1297
+ : entry)),
1298
+ })
1299
+ },
1300
+
1301
+ /** Throw away the draft edits of one result. */
1302
+ clearCellEdits(tabId) {
1303
+ patch({
1304
+ tabs: state.tabs.map((entry) => (entry.id === tabId ? { ...entry, edits: undefined } : entry)),
1305
+ })
1306
+ },
1307
+
1308
+ async nextPage() {
1309
+ await store.goToPage('next')
1310
+ },
1311
+
1312
+ async prevPage() {
1313
+ await store.goToPage('prev')
1314
+ },
1315
+ }
1316
+
1317
+ return store
1318
+ }
1319
+
1320
+ export { DW_NS, DW_PANEL_ID, DW_DEFAULT_LIMIT, DW_ROOT_KEY, dwMakeTranslator, dwRpc, dwNodeKey, dwCreateStore, dwDuration, dwRowCount, dwExplainFailure, DW_SQL_EMPTY }