dsh-data-window 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +111 -0
- package/CHANGELOG.md +239 -0
- package/LICENSE +21 -0
- package/README.md +146 -2
- package/client.js +7779 -0
- package/cordis.patch.yml +4 -0
- package/docs/BRIDGE.md +100 -0
- package/docs/DESIGN.md +417 -0
- package/docs/DETAIL.md +220 -0
- package/docs/screenshots/ddl.png +0 -0
- package/docs/screenshots/workbench.png +0 -0
- package/icon.svg +30 -0
- package/index.js +180 -0
- package/locale/en.json +286 -0
- package/locale/zh.json +286 -0
- package/package.json +68 -4
- package/src/client/00-css.js +993 -0
- package/src/client/05-icons.js +137 -0
- package/src/client/05-theme.js +107 -0
- package/src/client/06-shortcuts.js +89 -0
- package/src/client/07-bridge.js +193 -0
- package/src/client/10-core.js +1352 -0
- package/src/client/20-tree.js +281 -0
- package/src/client/25-sql.js +631 -0
- package/src/client/30-editor.js +537 -0
- package/src/client/40-results.js +556 -0
- package/src/client/45-export.js +219 -0
- package/src/client/50-panel.js +761 -0
- package/src/client/60-settings.js +180 -0
- package/src/client/63-schema.js +186 -0
- package/src/client/64-manual.js +350 -0
- package/src/client/65-ai.js +320 -0
- package/src/client/66-optimize.js +98 -0
- package/src/client/90-apply.js +183 -0
- package/src/host/ai.js +721 -0
- package/src/host/cache.js +157 -0
- package/src/host/catalog.js +161 -0
- package/src/host/consoles.js +116 -0
- package/src/host/discovery.js +603 -0
- package/src/host/manual.js +276 -0
- package/src/host/mysql.js +650 -0
- package/src/host/remembered.js +225 -0
- package/src/host/rpc.js +487 -0
- package/src/host/shared.js +172 -0
- package/src/host/yaml.js +335 -0
|
@@ -0,0 +1,1352 @@
|
|
|
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
|
+
if (node.kind === 'table' || node.kind === 'view') {
|
|
826
|
+
const tab = state.tabs.find((entry) => entry.kind === 'ddl' && entry.dbId === node.dbId && entry.table === node.table)
|
|
827
|
+
if (tab !== undefined) await store.refreshDdl(tab.id)
|
|
828
|
+
}
|
|
829
|
+
pushLog('info', t('log.refreshedStructure', { name: node.label }))
|
|
830
|
+
},
|
|
831
|
+
|
|
832
|
+
/** Forget one node's cached children so the next expand re-reads them. */
|
|
833
|
+
retryNode(node) {
|
|
834
|
+
if (node === null || node === undefined) return
|
|
835
|
+
const children = new Map(state.children)
|
|
836
|
+
children.delete(node.key)
|
|
837
|
+
const loadState = new Map(state.loadState)
|
|
838
|
+
loadState.delete(node.key)
|
|
839
|
+
patch({ children, loadState })
|
|
840
|
+
void store.ensureChildren(node)
|
|
841
|
+
},
|
|
842
|
+
|
|
843
|
+
/** Load the children a node needs, once. */
|
|
844
|
+
async ensureChildren(node) {
|
|
845
|
+
if (node === null || node === undefined) return
|
|
846
|
+
if (node.kind === 'env') return
|
|
847
|
+
// Databases are an explicit choice made in the schema picker, not a list the
|
|
848
|
+
// tree fills in on expand: expanding an instance only reveals what was picked.
|
|
849
|
+
if (node.kind === 'instance') return
|
|
850
|
+
if (node.kind !== 'database' && node.kind !== 'table' && node.kind !== 'view') return
|
|
851
|
+
if (Array.isArray(state.children.get(node.key))) return
|
|
852
|
+
if (state.loadState.get(node.key) === 'loading') return
|
|
853
|
+
const loadState = new Map(state.loadState)
|
|
854
|
+
loadState.set(node.key, 'loading')
|
|
855
|
+
patch({ loadState })
|
|
856
|
+
try {
|
|
857
|
+
if (node.kind === 'database') {
|
|
858
|
+
const value = await call('tables', { id: node.dbId })
|
|
859
|
+
const children = (value.tables ?? []).map((table) => ({
|
|
860
|
+
key: dwNodeKey('tbl', node.dbId, table.name),
|
|
861
|
+
kind: table.kind === 'view' ? 'view' : 'table',
|
|
862
|
+
label: table.name,
|
|
863
|
+
detail: table.comment !== '' ? table.comment : table.rows > 0 ? dwRowCount(table.rows) : '',
|
|
864
|
+
dbId: node.dbId,
|
|
865
|
+
database: node.database,
|
|
866
|
+
env: node.env,
|
|
867
|
+
instanceLabel: node.instanceLabel,
|
|
868
|
+
table: table.name,
|
|
869
|
+
info: table,
|
|
870
|
+
}))
|
|
871
|
+
const nextChildren = new Map(state.children)
|
|
872
|
+
nextChildren.set(node.key, children)
|
|
873
|
+
const nextState = new Map(state.loadState)
|
|
874
|
+
nextState.set(node.key, 'ready')
|
|
875
|
+
patch({ children: nextChildren, loadState: nextState })
|
|
876
|
+
pushLog('info', t('log.tables', { database: node.database, count: children.length, ms: dwDuration(value.elapsedMs) }))
|
|
877
|
+
return
|
|
878
|
+
}
|
|
879
|
+
const value = await call('columns', { id: node.dbId, table: node.table })
|
|
880
|
+
const children = (value.columns ?? []).map((column) => ({
|
|
881
|
+
key: dwNodeKey('col', node.dbId, node.table, column.name),
|
|
882
|
+
kind: 'column',
|
|
883
|
+
label: column.name,
|
|
884
|
+
detail: column.type,
|
|
885
|
+
column,
|
|
886
|
+
dbId: node.dbId,
|
|
887
|
+
database: node.database,
|
|
888
|
+
env: node.env,
|
|
889
|
+
instanceLabel: node.instanceLabel,
|
|
890
|
+
table: node.table,
|
|
891
|
+
}))
|
|
892
|
+
const nextChildren = new Map(state.children)
|
|
893
|
+
nextChildren.set(node.key, children)
|
|
894
|
+
const nextState = new Map(state.loadState)
|
|
895
|
+
nextState.set(node.key, 'ready')
|
|
896
|
+
patch({ children: nextChildren, loadState: nextState })
|
|
897
|
+
} catch (error) {
|
|
898
|
+
// A failure stays a load state, not a fake child row: a child would make
|
|
899
|
+
// every later expand a no-op and only a restart could clear it.
|
|
900
|
+
const nextState = new Map(state.loadState)
|
|
901
|
+
nextState.set(node.key, 'error')
|
|
902
|
+
patch({ loadState: nextState })
|
|
903
|
+
pushLog('error', t('log.loadFailed', { name: node.label, message: dwExplainFailure(t, error) }))
|
|
904
|
+
}
|
|
905
|
+
},
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* Load the table/column map the editor completes against.
|
|
909
|
+
*
|
|
910
|
+
* Failure is silent: suggestions degrade to keywords instead of turning a
|
|
911
|
+
* focus event into an error banner.
|
|
912
|
+
*/
|
|
913
|
+
async loadSchema(dbId) {
|
|
914
|
+
if (typeof dbId !== 'string' || dbId === '') return
|
|
915
|
+
if (state.schemas?.has(dbId)) return
|
|
916
|
+
try {
|
|
917
|
+
const value = await call('schema', { id: dbId })
|
|
918
|
+
const schemas = new Map(state.schemas ?? [])
|
|
919
|
+
schemas.set(dbId, value)
|
|
920
|
+
patch({ schemas })
|
|
921
|
+
} catch (error) {
|
|
922
|
+
void error
|
|
923
|
+
}
|
|
924
|
+
},
|
|
925
|
+
|
|
926
|
+
/** Reveal every schema on one instance, not only the configured ones. */
|
|
927
|
+
/** Select one row; a table also becomes the target of the DDL shortcut. */
|
|
928
|
+
select(node) {
|
|
929
|
+
patch({ selected: node?.key ?? '', selectedNode: node ?? null })
|
|
930
|
+
},
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* Open (or focus) the SQL workbench of one database.
|
|
934
|
+
*
|
|
935
|
+
* @returns the tab, so a caller may seed a statement only when the console is
|
|
936
|
+
* still empty.
|
|
937
|
+
*/
|
|
938
|
+
openDatabase(node) {
|
|
939
|
+
if (node === null || node === undefined || node.dbId === undefined) return undefined
|
|
940
|
+
const id = `sql:${node.dbId}`
|
|
941
|
+
const existing = state.tabs.find((tab) => tab.id === id)
|
|
942
|
+
if (existing !== undefined) {
|
|
943
|
+
patch({ activeTab: id })
|
|
944
|
+
scheduleConsoles()
|
|
945
|
+
if (node.configured === false) void store.rememberDatabase(node)
|
|
946
|
+
return existing
|
|
947
|
+
}
|
|
948
|
+
const tab = {
|
|
949
|
+
id,
|
|
950
|
+
kind: 'sql',
|
|
951
|
+
title: node.database,
|
|
952
|
+
env: node.env ?? '',
|
|
953
|
+
subtitle: [node.env, node.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
|
|
954
|
+
dbId: node.dbId,
|
|
955
|
+
database: node.database,
|
|
956
|
+
instanceLabel: node.instanceLabel ?? '',
|
|
957
|
+
// An empty console, so the placeholder explains what to do; a canned
|
|
958
|
+
// statement would be overwritten by the user's first keystroke anyway.
|
|
959
|
+
sql: '',
|
|
960
|
+
result: undefined,
|
|
961
|
+
error: '',
|
|
962
|
+
running: false,
|
|
963
|
+
}
|
|
964
|
+
patch({ tabs: [...state.tabs, tab], activeTab: id })
|
|
965
|
+
scheduleConsoles()
|
|
966
|
+
// Opening a schema that is not part of the configuration makes it part of the
|
|
967
|
+
// workspace: the next discovery lists it next to the configured databases.
|
|
968
|
+
if (node.configured === false) void store.rememberDatabase(node)
|
|
969
|
+
return tab
|
|
970
|
+
},
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* Put a statement in a workbench without destroying what the user typed.
|
|
974
|
+
*
|
|
975
|
+
* A tree action ("open table data") must never cost the user an unsaved
|
|
976
|
+
* query, so an occupied console gets a second tab instead.
|
|
977
|
+
*/
|
|
978
|
+
/**
|
|
979
|
+
* Open one table's own console and append its base query.
|
|
980
|
+
*
|
|
981
|
+
* Requirement: one window per table per workspace. Double-clicking the same
|
|
982
|
+
* table again focuses that window and appends one more statement at the bottom
|
|
983
|
+
* instead of stacking numbered consoles; the user's text is only ever extended,
|
|
984
|
+
* never replaced.
|
|
985
|
+
*/
|
|
986
|
+
seedStatement(node, sql) {
|
|
987
|
+
if (node === null || node === undefined || node.dbId === undefined || node.table === undefined) return
|
|
988
|
+
const statement = String(sql ?? '').trim()
|
|
989
|
+
if (statement === '') return
|
|
990
|
+
const id = `sql:${node.dbId}:tbl:${node.table}`
|
|
991
|
+
const existing = state.tabs.find((tab) => tab.id === id)
|
|
992
|
+
if (existing !== undefined) {
|
|
993
|
+
const current = String(existing.sql ?? '').replace(/\s+$/, '')
|
|
994
|
+
patch({
|
|
995
|
+
tabs: state.tabs.map((tab) => (tab.id === id
|
|
996
|
+
? { ...tab, sql: current === '' ? statement : `${current}\n\n${statement}`, result: undefined, error: '' }
|
|
997
|
+
: tab)),
|
|
998
|
+
})
|
|
999
|
+
store.setActiveTab(id)
|
|
1000
|
+
scheduleConsoles()
|
|
1001
|
+
return
|
|
1002
|
+
}
|
|
1003
|
+
const tab = {
|
|
1004
|
+
id,
|
|
1005
|
+
kind: 'sql',
|
|
1006
|
+
title: String(node.table),
|
|
1007
|
+
env: node.env ?? '',
|
|
1008
|
+
subtitle: [node.env, node.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
|
|
1009
|
+
dbId: node.dbId,
|
|
1010
|
+
database: node.database,
|
|
1011
|
+
instanceLabel: node.instanceLabel ?? '',
|
|
1012
|
+
sql: statement,
|
|
1013
|
+
result: undefined,
|
|
1014
|
+
error: '',
|
|
1015
|
+
}
|
|
1016
|
+
patch({ tabs: [...state.tabs, tab], activeTab: id })
|
|
1017
|
+
scheduleConsoles()
|
|
1018
|
+
},
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* Open a console from the code workspace with a statement already pasted.
|
|
1022
|
+
*
|
|
1023
|
+
* Keyed by the caller's title, so jumping to the same mapper method twice
|
|
1024
|
+
* focuses the same tab. Only appends: the user's existing text is never
|
|
1025
|
+
* replaced, and the same block is not pasted twice.
|
|
1026
|
+
*/
|
|
1027
|
+
openSqlConsole(input) {
|
|
1028
|
+
const sql = String(input?.sql ?? '').trim()
|
|
1029
|
+
if (sql === '' || typeof input?.dbId !== 'string' || input.dbId === '') return undefined
|
|
1030
|
+
const title = String(input.title ?? '').trim() || 'SQL'
|
|
1031
|
+
const id = `sql:${input.dbId}:code:${encodeURIComponent(title)}`
|
|
1032
|
+
const block = `-- ${title}\n${sql}`
|
|
1033
|
+
const existing = state.tabs.find((tab) => tab.id === id)
|
|
1034
|
+
if (existing !== undefined) {
|
|
1035
|
+
const current = String(existing.sql ?? '').replace(/\s+$/, '')
|
|
1036
|
+
const next = current === '' ? block : current.includes(block) ? current : `${current}\n\n${block}`
|
|
1037
|
+
patch({ tabs: state.tabs.map((tab) => (tab.id === id ? { ...tab, sql: next } : tab)) })
|
|
1038
|
+
store.setActiveTab(id)
|
|
1039
|
+
scheduleConsoles()
|
|
1040
|
+
return state.tabs.find((tab) => tab.id === id)
|
|
1041
|
+
}
|
|
1042
|
+
const tab = {
|
|
1043
|
+
id,
|
|
1044
|
+
kind: 'sql',
|
|
1045
|
+
title,
|
|
1046
|
+
env: input.env ?? '',
|
|
1047
|
+
subtitle: [input.env, input.instanceLabel].filter((part) => typeof part === 'string' && part !== '').join(' · '),
|
|
1048
|
+
dbId: input.dbId,
|
|
1049
|
+
database: input.database ?? '',
|
|
1050
|
+
instanceLabel: input.instanceLabel ?? '',
|
|
1051
|
+
sql: block,
|
|
1052
|
+
result: undefined,
|
|
1053
|
+
error: '',
|
|
1054
|
+
}
|
|
1055
|
+
patch({ tabs: [...state.tabs, tab], activeTab: id })
|
|
1056
|
+
scheduleConsoles()
|
|
1057
|
+
// Opening a schema that is not part of the configuration makes it part of the
|
|
1058
|
+
// workspace: the next discovery lists it next to the configured databases.
|
|
1059
|
+
if (node.configured === false) void store.rememberDatabase(node)
|
|
1060
|
+
return tab
|
|
1061
|
+
},
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* Open the DDL of one table.
|
|
1065
|
+
*
|
|
1066
|
+
* Requirement: the create statement is one keystroke away. The tab is keyed by
|
|
1067
|
+
* table, so asking twice focuses the same document instead of stacking copies.
|
|
1068
|
+
*/
|
|
1069
|
+
async openDdl(node) {
|
|
1070
|
+
if (node === null || node === undefined || node.table === undefined) return
|
|
1071
|
+
const id = `ddl:${node.dbId}:${node.table}`
|
|
1072
|
+
const existing = state.tabs.find((tab) => tab.id === id)
|
|
1073
|
+
if (existing !== undefined) {
|
|
1074
|
+
patch({ activeTab: id })
|
|
1075
|
+
if (existing.loading !== true && existing.ddl !== '') return
|
|
1076
|
+
await store.refreshDdl(id)
|
|
1077
|
+
return
|
|
1078
|
+
}
|
|
1079
|
+
const tab = {
|
|
1080
|
+
id,
|
|
1081
|
+
kind: 'ddl',
|
|
1082
|
+
title: node.table,
|
|
1083
|
+
env: node.env ?? '',
|
|
1084
|
+
subtitle: [node.env, node.database].filter((part) => typeof part === 'string' && part !== '').join(' · '),
|
|
1085
|
+
dbId: node.dbId,
|
|
1086
|
+
database: node.database,
|
|
1087
|
+
instanceLabel: node.instanceLabel ?? '',
|
|
1088
|
+
table: node.table,
|
|
1089
|
+
ddl: '',
|
|
1090
|
+
columns: [],
|
|
1091
|
+
loading: true,
|
|
1092
|
+
error: '',
|
|
1093
|
+
}
|
|
1094
|
+
patch({ tabs: [...state.tabs, tab], activeTab: id })
|
|
1095
|
+
await store.refreshDdl(id)
|
|
1096
|
+
},
|
|
1097
|
+
|
|
1098
|
+
/** Re-read one DDL tab (a schema change is exactly why the tab exists). */
|
|
1099
|
+
async refreshDdl(id) {
|
|
1100
|
+
const tab = state.tabs.find((entry) => entry.id === id)
|
|
1101
|
+
if (tab === undefined || tab.kind !== 'ddl') return
|
|
1102
|
+
patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: true, error: '' } : entry)) })
|
|
1103
|
+
try {
|
|
1104
|
+
const value = await call('ddl', { id: tab.dbId, table: tab.table })
|
|
1105
|
+
patch({
|
|
1106
|
+
tabs: state.tabs.map((entry) => (entry.id === id
|
|
1107
|
+
? { ...entry, ddl: value.ddl ?? '', columns: value.columns ?? [], loading: false, error: '' }
|
|
1108
|
+
: entry)),
|
|
1109
|
+
})
|
|
1110
|
+
pushLog('info', t('log.ddl', { table: tab.table, ms: dwDuration(value.statementTime) }))
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: false, error: dwExplainFailure(t, error) } : entry)) })
|
|
1113
|
+
pushLog('error', t('log.loadFailed', { name: tab.table, message: dwExplainFailure(t, error) }))
|
|
1114
|
+
}
|
|
1115
|
+
},
|
|
1116
|
+
|
|
1117
|
+
/** Close one tab and pick a neighbour. */
|
|
1118
|
+
closeTab(id) {
|
|
1119
|
+
const index = state.tabs.findIndex((tab) => tab.id === id)
|
|
1120
|
+
if (index < 0) return
|
|
1121
|
+
const tabs = state.tabs.filter((tab) => tab.id !== id)
|
|
1122
|
+
let activeTab = state.activeTab
|
|
1123
|
+
if (activeTab === id) {
|
|
1124
|
+
const neighbour = tabs[index] ?? tabs[index - 1]
|
|
1125
|
+
activeTab = neighbour?.id ?? ''
|
|
1126
|
+
}
|
|
1127
|
+
patch({ tabs, activeTab })
|
|
1128
|
+
// Closing a console is deliberate: drop it from storage now, not later.
|
|
1129
|
+
flushConsoles()
|
|
1130
|
+
},
|
|
1131
|
+
|
|
1132
|
+
setActiveTab(id) {
|
|
1133
|
+
patch({ activeTab: id })
|
|
1134
|
+
scheduleConsoles()
|
|
1135
|
+
},
|
|
1136
|
+
|
|
1137
|
+
setTabSql(id, sql) {
|
|
1138
|
+
patch({ tabs: state.tabs.map((tab) => (tab.id === id ? { ...tab, sql } : tab)) })
|
|
1139
|
+
scheduleConsoles()
|
|
1140
|
+
},
|
|
1141
|
+
|
|
1142
|
+
setLimit(limit) {
|
|
1143
|
+
patch({ limit })
|
|
1144
|
+
},
|
|
1145
|
+
|
|
1146
|
+
setLogOpen(open) {
|
|
1147
|
+
patch({ logOpen: open })
|
|
1148
|
+
},
|
|
1149
|
+
|
|
1150
|
+
/** Run the active tab's statement. */
|
|
1151
|
+
/**
|
|
1152
|
+
* Count every row of the statement that produced the current result.
|
|
1153
|
+
*
|
|
1154
|
+
* Deliberately on demand: COUNT(*) on a large table is a second full scan, so
|
|
1155
|
+
* it runs when the user presses the refresh button, not after every query.
|
|
1156
|
+
*/
|
|
1157
|
+
async refreshTotal(id) {
|
|
1158
|
+
const tab = state.tabs.find((entry) => entry.id === id)
|
|
1159
|
+
if (tab === undefined || tab.kind !== 'sql' || tab.counting === true) return
|
|
1160
|
+
const sql = String(tab.lastStatement ?? tab.sql ?? '').trim()
|
|
1161
|
+
if (sql === '') return
|
|
1162
|
+
patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, counting: true, countError: '' } : entry)) })
|
|
1163
|
+
try {
|
|
1164
|
+
const value = await call('count', { id: tab.dbId, sql })
|
|
1165
|
+
if (typeof value.sql === 'string' && value.sql !== '') pushLog('sql', value.sql)
|
|
1166
|
+
pushLog('info', t('log.count', {
|
|
1167
|
+
rows: dwRowCount(value.total),
|
|
1168
|
+
ms: dwDuration(value.elapsedMs),
|
|
1169
|
+
}))
|
|
1170
|
+
patch({
|
|
1171
|
+
tabs: state.tabs.map((entry) => (entry.id === id
|
|
1172
|
+
? { ...entry, counting: false, totalCount: Number(value.total ?? 0), countError: '' }
|
|
1173
|
+
: entry)),
|
|
1174
|
+
})
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
pushLog('error', dwExplainFailure(t, error))
|
|
1177
|
+
patch({
|
|
1178
|
+
tabs: state.tabs.map((entry) => (entry.id === id
|
|
1179
|
+
? { ...entry, counting: false, countError: dwExplainFailure(t, error) }
|
|
1180
|
+
: entry)),
|
|
1181
|
+
})
|
|
1182
|
+
}
|
|
1183
|
+
},
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* Run the workbench statement, or just the text the user selected.
|
|
1187
|
+
*
|
|
1188
|
+
* DataGrip runs the selection; running the whole buffer while the user has a
|
|
1189
|
+
* fragment selected sends several statements to MySQL, which answers with a
|
|
1190
|
+
* confusing ER_PARSE_ERROR at the second one.
|
|
1191
|
+
*/
|
|
1192
|
+
async runActiveTab(statement) {
|
|
1193
|
+
const tab = state.tabs.find((entry) => entry.id === state.activeTab)
|
|
1194
|
+
if (tab === undefined || tab.kind !== 'sql' || tab.running === true) return
|
|
1195
|
+
const override = typeof statement === 'string' ? statement.trim() : ''
|
|
1196
|
+
const sql = override !== '' ? override : String(tab.sql ?? '').trim()
|
|
1197
|
+
if (DW_SQL_EMPTY.test(sql)) {
|
|
1198
|
+
pushLog('warn', t('log.noStatement'))
|
|
1199
|
+
return
|
|
1200
|
+
}
|
|
1201
|
+
// A trailing LIMIT makes the result a page: the pager re-runs the statement
|
|
1202
|
+
// with another OFFSET instead of asking the user to edit the SQL. Only
|
|
1203
|
+
// SELECT/WITH statements are paged — `SHOW … LIMIT` has no OFFSET form.
|
|
1204
|
+
const page = /^\s*(select|with)\b/i.test(sql) ? dwSqlPage(sql) : undefined
|
|
1205
|
+
// Every executed statement goes to the run log, failures included: the log is
|
|
1206
|
+
// the console history, not just a success report.
|
|
1207
|
+
pushLog('sql', sql)
|
|
1208
|
+
patch({
|
|
1209
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id
|
|
1210
|
+
? { ...entry, running: true, error: '', counting: false, totalCount: undefined, countError: '' }
|
|
1211
|
+
: entry)),
|
|
1212
|
+
})
|
|
1213
|
+
try {
|
|
1214
|
+
const value = await call('query', {
|
|
1215
|
+
id: tab.dbId,
|
|
1216
|
+
sql,
|
|
1217
|
+
// The statement's own LIMIT is the page capacity; the row cap must not cut
|
|
1218
|
+
// a page short, or "returned fewer rows" would be mistaken for the end.
|
|
1219
|
+
limit: page === undefined ? state.limit : Math.max(state.limit, page.size),
|
|
1220
|
+
})
|
|
1221
|
+
const returned = Array.isArray(value.rows) ? value.rows.length : Number(value.rowCount ?? 0)
|
|
1222
|
+
patch({
|
|
1223
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id
|
|
1224
|
+
? {
|
|
1225
|
+
...entry,
|
|
1226
|
+
running: false,
|
|
1227
|
+
result: value,
|
|
1228
|
+
error: '',
|
|
1229
|
+
lastStatement: sql,
|
|
1230
|
+
// Cell edits belong to the rows on screen; a new result replaces them.
|
|
1231
|
+
edits: undefined,
|
|
1232
|
+
page: page === undefined ? undefined : { base: page.base, size: page.size, offset: page.offset, hasMore: returned >= page.size },
|
|
1233
|
+
}
|
|
1234
|
+
: entry)),
|
|
1235
|
+
})
|
|
1236
|
+
pushLog('info', t('log.query', {
|
|
1237
|
+
database: tab.database,
|
|
1238
|
+
rows: value.rowCount,
|
|
1239
|
+
ms: dwDuration(value.elapsedMs),
|
|
1240
|
+
truncated: value.truncated === true ? t('log.truncatedSuffix', { limit: value.limit }) : '',
|
|
1241
|
+
}))
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
const message = dwExplainFailure(t, error)
|
|
1244
|
+
patch({
|
|
1245
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: false, error: message } : entry)),
|
|
1246
|
+
})
|
|
1247
|
+
pushLog('error', message)
|
|
1248
|
+
}
|
|
1249
|
+
},
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* Move one page inside the current statement's LIMIT.
|
|
1253
|
+
*
|
|
1254
|
+
* The editor's text is never rewritten: the page statement is derived from the
|
|
1255
|
+
* stored base and sent directly. A next page that comes back empty ends the
|
|
1256
|
+
* paging without replacing the page the user is reading, so only "previous"
|
|
1257
|
+
* remains possible.
|
|
1258
|
+
*/
|
|
1259
|
+
async goToPage(direction) {
|
|
1260
|
+
const tab = state.tabs.find((entry) => entry.id === state.activeTab)
|
|
1261
|
+
if (tab === undefined || tab.kind !== 'sql' || tab.running === true || tab.page === undefined) return
|
|
1262
|
+
const { base, size, offset, hasMore } = tab.page
|
|
1263
|
+
const forward = direction === 'next'
|
|
1264
|
+
if (forward && hasMore !== true) return
|
|
1265
|
+
const target = forward ? offset + size : Math.max(0, offset - size)
|
|
1266
|
+
if (!forward && target === offset) return
|
|
1267
|
+
const sql = `${base}\nLIMIT ${size} OFFSET ${target}`
|
|
1268
|
+
patch({
|
|
1269
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: true, error: '' } : entry)),
|
|
1270
|
+
})
|
|
1271
|
+
try {
|
|
1272
|
+
const value = await call('query', { id: tab.dbId, sql, limit: Math.max(state.limit, size) })
|
|
1273
|
+
const returned = Array.isArray(value.rows) ? value.rows.length : 0
|
|
1274
|
+
if (forward && returned === 0) {
|
|
1275
|
+
patch({
|
|
1276
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id
|
|
1277
|
+
? { ...entry, running: false, page: { ...tab.page, hasMore: false } }
|
|
1278
|
+
: entry)),
|
|
1279
|
+
})
|
|
1280
|
+
pushLog('info', t('log.pageEnd'))
|
|
1281
|
+
return
|
|
1282
|
+
}
|
|
1283
|
+
patch({
|
|
1284
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id
|
|
1285
|
+
? {
|
|
1286
|
+
...entry,
|
|
1287
|
+
running: false,
|
|
1288
|
+
result: value,
|
|
1289
|
+
error: '',
|
|
1290
|
+
edits: undefined,
|
|
1291
|
+
page: { base, size, offset: target, hasMore: returned >= size },
|
|
1292
|
+
}
|
|
1293
|
+
: entry)),
|
|
1294
|
+
})
|
|
1295
|
+
pushLog('info', t('log.page', { page: Math.floor(target / size) + 1, rows: value.rowCount, ms: dwDuration(value.elapsedMs) }))
|
|
1296
|
+
} catch (error) {
|
|
1297
|
+
const message = dwExplainFailure(t, error)
|
|
1298
|
+
patch({
|
|
1299
|
+
tabs: state.tabs.map((entry) => (entry.id === tab.id ? { ...entry, running: false, error: message } : entry)),
|
|
1300
|
+
})
|
|
1301
|
+
pushLog('error', message)
|
|
1302
|
+
}
|
|
1303
|
+
},
|
|
1304
|
+
|
|
1305
|
+
/**
|
|
1306
|
+
* Record one edited cell.
|
|
1307
|
+
*
|
|
1308
|
+
* Edits are a local draft for building an UPDATE statement — nothing is sent to
|
|
1309
|
+
* the server, and the value is dropped as soon as the result changes.
|
|
1310
|
+
*/
|
|
1311
|
+
setCellEdit(tabId, rowIndex, columnIndex, columnName, value) {
|
|
1312
|
+
const tab = state.tabs.find((entry) => entry.id === tabId)
|
|
1313
|
+
if (tab === undefined || tab.kind !== 'sql' || tab.result === undefined) return
|
|
1314
|
+
const row = (Array.isArray(tab.result.rows) ? tab.result.rows : [])[rowIndex]
|
|
1315
|
+
if (row === undefined) return
|
|
1316
|
+
const original = row[columnIndex]
|
|
1317
|
+
const edits = { ...(tab.edits ?? {}) }
|
|
1318
|
+
const rowEdits = { ...(edits[rowIndex] ?? {}) }
|
|
1319
|
+
const unchanged = original === null
|
|
1320
|
+
? value === null || value === 'NULL'
|
|
1321
|
+
: String(original) === String(value)
|
|
1322
|
+
if (unchanged) delete rowEdits[columnName]
|
|
1323
|
+
else rowEdits[columnName] = value
|
|
1324
|
+
if (Object.keys(rowEdits).length === 0) delete edits[rowIndex]
|
|
1325
|
+
else edits[rowIndex] = rowEdits
|
|
1326
|
+
patch({
|
|
1327
|
+
tabs: state.tabs.map((entry) => (entry.id === tabId
|
|
1328
|
+
? { ...entry, edits: Object.keys(edits).length === 0 ? undefined : edits }
|
|
1329
|
+
: entry)),
|
|
1330
|
+
})
|
|
1331
|
+
},
|
|
1332
|
+
|
|
1333
|
+
/** Throw away the draft edits of one result. */
|
|
1334
|
+
clearCellEdits(tabId) {
|
|
1335
|
+
patch({
|
|
1336
|
+
tabs: state.tabs.map((entry) => (entry.id === tabId ? { ...entry, edits: undefined } : entry)),
|
|
1337
|
+
})
|
|
1338
|
+
},
|
|
1339
|
+
|
|
1340
|
+
async nextPage() {
|
|
1341
|
+
await store.goToPage('next')
|
|
1342
|
+
},
|
|
1343
|
+
|
|
1344
|
+
async prevPage() {
|
|
1345
|
+
await store.goToPage('prev')
|
|
1346
|
+
},
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
return store
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
export { DW_NS, DW_PANEL_ID, DW_DEFAULT_LIMIT, DW_ROOT_KEY, dwMakeTranslator, dwRpc, dwNodeKey, dwCreateStore, dwDuration, dwRowCount, dwExplainFailure, DW_SQL_EMPTY }
|