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.
- package/AGENTS.md +111 -0
- package/CHANGELOG.md +267 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/client.js +8271 -0
- package/cordis.patch.yml +4 -0
- package/docs/BRIDGE.md +106 -0
- package/docs/DESIGN.md +417 -0
- package/docs/DETAIL.md +242 -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 +304 -0
- package/locale/zh.json +304 -0
- package/package.json +68 -4
- package/src/client/00-css.js +1110 -0
- package/src/client/05-icons.js +156 -0
- package/src/client/05-theme.js +107 -0
- package/src/client/06-shortcuts.js +89 -0
- package/src/client/07-bridge.js +202 -0
- package/src/client/10-core.js +1320 -0
- package/src/client/20-tree.js +293 -0
- package/src/client/25-sql.js +631 -0
- package/src/client/30-editor.js +742 -0
- package/src/client/40-results.js +556 -0
- package/src/client/45-export.js +219 -0
- package/src/client/50-panel.js +768 -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 +217 -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 +180 -0
- package/src/host/yaml.js +335 -0
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL lexer, completion and formatter.
|
|
3
|
+
*
|
|
4
|
+
* The editor is a textarea, so highlighting is an overlay of tokens and the
|
|
5
|
+
* completion list is built from the schema the Host already exposes. All three
|
|
6
|
+
* features share one lexer: a single definition of strings, comments and
|
|
7
|
+
* keywords that cannot drift apart.
|
|
8
|
+
*
|
|
9
|
+
* Nothing here touches the DOM or React; the functions are pure so they can be
|
|
10
|
+
* exercised from Node.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Words the editor colours as keywords. */
|
|
14
|
+
const DW_SQL_KEYWORDS = new Set(`select from where group by order having limit offset union all distinct join inner left right outer full cross natural on using and or not in is null like between exists case when then else end as asc desc insert into values update set delete create drop alter table index view show describe explain with recursive partition over window`.split(' '))
|
|
15
|
+
|
|
16
|
+
/** Words coloured as functions; the schema supplies the rest. */
|
|
17
|
+
const DW_SQL_FUNCTIONS = new Set(`count sum avg min max coalesce ifnull nullif concat concat_ws substr substring length lower upper trim ltrim rtrim replace round floor ceil abs cast convert date_format str_to_date now curdate curtime datediff date_add date_sub timestampdiff if group_concat json_extract json_unquote unix_timestamp from_unixtime row_number rank dense_rank lag lead`.split(' '))
|
|
18
|
+
|
|
19
|
+
/** Literals that are keywords in effect. */
|
|
20
|
+
const DW_SQL_LITERALS = new Set(['null', 'true', 'false'])
|
|
21
|
+
|
|
22
|
+
const DW_SQL_OPERATORS = ['<=>', '<=', '>=', '<>', '!=', '||', '&&', ':=', '=', '<', '>', '+', '-', '*', '/', '%', '!', '&', '|', '^', '~']
|
|
23
|
+
const DW_SQL_PUNCT = new Set(['(', ')', ',', '.', ';', '[', ']'])
|
|
24
|
+
|
|
25
|
+
/** Split SQL into tokens; whitespace is kept so highlighting reproduces it. */
|
|
26
|
+
export function dwSqlLex(text) {
|
|
27
|
+
const source = String(text ?? '')
|
|
28
|
+
const tokens = []
|
|
29
|
+
let index = 0
|
|
30
|
+
while (index < source.length) {
|
|
31
|
+
const start = index
|
|
32
|
+
const char = source[index]
|
|
33
|
+
if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
|
|
34
|
+
while (index < source.length && /[ \t\n\r]/.test(source[index])) index += 1
|
|
35
|
+
tokens.push({ type: 'space', value: source.slice(start, index), start, end: index })
|
|
36
|
+
continue
|
|
37
|
+
}
|
|
38
|
+
if (char === '-' && source[index + 1] === '-') {
|
|
39
|
+
index += 2
|
|
40
|
+
while (index < source.length && source[index] !== '\n') index += 1
|
|
41
|
+
tokens.push({ type: 'comment', value: source.slice(start, index), start, end: index })
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
if (char === '#') {
|
|
45
|
+
index += 1
|
|
46
|
+
while (index < source.length && source[index] !== '\n') index += 1
|
|
47
|
+
tokens.push({ type: 'comment', value: source.slice(start, index), start, end: index })
|
|
48
|
+
continue
|
|
49
|
+
}
|
|
50
|
+
if (char === '/' && source[index + 1] === '*') {
|
|
51
|
+
index += 2
|
|
52
|
+
while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) index += 1
|
|
53
|
+
index = Math.min(source.length, index + 2)
|
|
54
|
+
tokens.push({ type: 'comment', value: source.slice(start, index), start, end: index })
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
if (char === "'" || char === '"' || char === '`') {
|
|
58
|
+
index += 1
|
|
59
|
+
while (index < source.length) {
|
|
60
|
+
if (source[index] === '\\') {
|
|
61
|
+
index += 2
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
if (source[index] === char) {
|
|
65
|
+
if (source[index + 1] === char) {
|
|
66
|
+
index += 2
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
index += 1
|
|
70
|
+
break
|
|
71
|
+
}
|
|
72
|
+
index += 1
|
|
73
|
+
}
|
|
74
|
+
const value = source.slice(start, index)
|
|
75
|
+
const closed = value.length > 1 && value[value.length - 1] === char
|
|
76
|
+
tokens.push({ type: closed ? (char === '`' ? 'identifier' : 'string') : 'string', value, start, end: index })
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
if (/[0-9]/.test(char)) {
|
|
80
|
+
while (index < source.length && /[0-9]/.test(source[index])) index += 1
|
|
81
|
+
if (source[index] === '.') {
|
|
82
|
+
index += 1
|
|
83
|
+
while (index < source.length && /[0-9]/.test(source[index])) index += 1
|
|
84
|
+
}
|
|
85
|
+
if (/[eE]/.test(source[index] ?? '')) {
|
|
86
|
+
index += 1
|
|
87
|
+
if (/[+-]/.test(source[index] ?? '')) index += 1
|
|
88
|
+
while (index < source.length && /[0-9]/.test(source[index])) index += 1
|
|
89
|
+
}
|
|
90
|
+
tokens.push({ type: 'number', value: source.slice(start, index), start, end: index })
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
if (/[A-Za-z_$]/.test(char)) {
|
|
94
|
+
while (index < source.length && /[A-Za-z0-9_$]/.test(source[index])) index += 1
|
|
95
|
+
const value = source.slice(start, index)
|
|
96
|
+
const lower = value.toLowerCase()
|
|
97
|
+
const type = DW_SQL_LITERALS.has(lower)
|
|
98
|
+
? 'literal'
|
|
99
|
+
: DW_SQL_KEYWORDS.has(lower)
|
|
100
|
+
? 'keyword'
|
|
101
|
+
: DW_SQL_FUNCTIONS.has(lower) ? 'function' : 'identifier'
|
|
102
|
+
tokens.push({ type, value, start, end: index })
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
const operator = DW_SQL_OPERATORS.find((candidate) => source.startsWith(candidate, index))
|
|
106
|
+
if (operator !== undefined) {
|
|
107
|
+
index += operator.length
|
|
108
|
+
tokens.push({ type: 'operator', value: operator, start, end: index })
|
|
109
|
+
continue
|
|
110
|
+
}
|
|
111
|
+
index += 1
|
|
112
|
+
tokens.push({ type: DW_SQL_PUNCT.has(char) ? 'punct' : 'identifier', value: char, start, end: index })
|
|
113
|
+
}
|
|
114
|
+
return tokens
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Split one statement's outermost trailing `LIMIT` into its base and page shape.
|
|
119
|
+
*
|
|
120
|
+
* Only the limit at parenthesis depth zero counts, so `FROM (SELECT … LIMIT 5)` is
|
|
121
|
+
* left alone. Returns undefined when the statement has no paginable limit, which is
|
|
122
|
+
* what the result bar uses to hide the pager for statements that are not paged.
|
|
123
|
+
*
|
|
124
|
+
* @returns `{ base, size, offset }`: the SQL without its LIMIT, the page capacity,
|
|
125
|
+
* and the offset the statement asked for (`LIMIT 100`, `LIMIT 20, 100`, `LIMIT 100 OFFSET 20`)
|
|
126
|
+
*/
|
|
127
|
+
export function dwSqlPage(text) {
|
|
128
|
+
const source = String(text ?? '')
|
|
129
|
+
const tokens = dwSqlLex(source).filter((token) => token.type !== 'space' && token.type !== 'comment')
|
|
130
|
+
let end = tokens.length
|
|
131
|
+
while (end > 0 && tokens[end - 1].value === ';') end -= 1
|
|
132
|
+
let depth = 0
|
|
133
|
+
let limitIndex = -1
|
|
134
|
+
for (let index = 0; index < end; index += 1) {
|
|
135
|
+
const value = tokens[index].value.toLowerCase()
|
|
136
|
+
if (value === '(') depth += 1
|
|
137
|
+
else if (value === ')') depth = Math.max(0, depth - 1)
|
|
138
|
+
else if (depth === 0 && value === 'limit') limitIndex = index
|
|
139
|
+
}
|
|
140
|
+
if (limitIndex < 0) return undefined
|
|
141
|
+
const tail = tokens.slice(limitIndex + 1, end)
|
|
142
|
+
const integer = (token) => (token !== undefined && token.type === 'number' && /^\d+$/.test(token.value) ? Number(token.value) : undefined)
|
|
143
|
+
const first = integer(tail[0])
|
|
144
|
+
if (first === undefined) return undefined
|
|
145
|
+
let size = first
|
|
146
|
+
let offset = 0
|
|
147
|
+
if (tail.length === 3 && tail[1].value === ',') {
|
|
148
|
+
const second = integer(tail[2])
|
|
149
|
+
if (second === undefined) return undefined
|
|
150
|
+
// LIMIT offset, size — the first number is the offset.
|
|
151
|
+
offset = first
|
|
152
|
+
size = second
|
|
153
|
+
} else if (tail.length === 3 && tail[1].value.toLowerCase() === 'offset') {
|
|
154
|
+
const second = integer(tail[2])
|
|
155
|
+
if (second === undefined) return undefined
|
|
156
|
+
offset = second
|
|
157
|
+
} else if (tail.length !== 1) {
|
|
158
|
+
return undefined
|
|
159
|
+
}
|
|
160
|
+
if (size <= 0 || offset < 0) return undefined
|
|
161
|
+
return { base: source.slice(0, tokens[limitIndex].start).trimEnd(), size, offset }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The single table a plain `SELECT` reads, for UPDATE/INSERT generation.
|
|
166
|
+
*
|
|
167
|
+
* A join is deliberately not resolved: which table a result row belongs to is then
|
|
168
|
+
* ambiguous, and inventing one would produce an INSERT that writes to the wrong
|
|
169
|
+
* place. The caller surfaces that refusal to the user instead.
|
|
170
|
+
*/
|
|
171
|
+
export function dwSqlTargetTable(text) {
|
|
172
|
+
const source = String(text ?? '')
|
|
173
|
+
const tokens = dwSqlLex(source).filter((token) => token.type !== 'space' && token.type !== 'comment')
|
|
174
|
+
let end = tokens.length
|
|
175
|
+
while (end > 0 && tokens[end - 1].value === ';') end -= 1
|
|
176
|
+
if (end === 0 || tokens[0].value.toLowerCase() !== 'select') return undefined
|
|
177
|
+
let depth = 0
|
|
178
|
+
let fromIndex = -1
|
|
179
|
+
for (let index = 0; index < end; index += 1) {
|
|
180
|
+
const value = tokens[index].value.toLowerCase()
|
|
181
|
+
if (value === '(') depth += 1
|
|
182
|
+
else if (value === ')') depth = Math.max(0, depth - 1)
|
|
183
|
+
else if (depth === 0 && fromIndex < 0 && value === 'from') fromIndex = index
|
|
184
|
+
}
|
|
185
|
+
// The select list must be plain columns (`*`, `id`, `t.*`, `t.id`): an expression
|
|
186
|
+
// or an alias would make the result's column names unusable in an INSERT.
|
|
187
|
+
let listDepth = 0
|
|
188
|
+
let item = []
|
|
189
|
+
const items = []
|
|
190
|
+
for (let cursor = 1; cursor < fromIndex; cursor += 1) {
|
|
191
|
+
const token = tokens[cursor]
|
|
192
|
+
if (token.value === '(') listDepth += 1
|
|
193
|
+
else if (token.value === ')') listDepth = Math.max(0, listDepth - 1)
|
|
194
|
+
if (listDepth === 0 && token.value === ',') {
|
|
195
|
+
items.push(item)
|
|
196
|
+
item = []
|
|
197
|
+
continue
|
|
198
|
+
}
|
|
199
|
+
item.push(token)
|
|
200
|
+
}
|
|
201
|
+
items.push(item)
|
|
202
|
+
if (['distinct', 'all'].includes(items[0]?.[0]?.value.toLowerCase())) items[0] = items[0].slice(1)
|
|
203
|
+
for (const entry of items) {
|
|
204
|
+
const head = entry[0]
|
|
205
|
+
if (entry.length === 1 && (head.value === '*' || head.type === 'identifier')) continue
|
|
206
|
+
if (entry.length === 3 && head.type === 'identifier' && entry[1].value === '.' && (entry[2].value === '*' || entry[2].type === 'identifier')) continue
|
|
207
|
+
return undefined
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (fromIndex < 0) return undefined
|
|
211
|
+
let index = fromIndex + 1
|
|
212
|
+
const readName = () => {
|
|
213
|
+
const token = tokens[index]
|
|
214
|
+
if (token === undefined) return undefined
|
|
215
|
+
if (token.type !== 'identifier' && token.type !== 'string') return undefined
|
|
216
|
+
index += 1
|
|
217
|
+
return token.value.replace(/^`|`$/g, '')
|
|
218
|
+
}
|
|
219
|
+
const first = readName()
|
|
220
|
+
if (first === undefined) return undefined
|
|
221
|
+
let database = ''
|
|
222
|
+
let table = first
|
|
223
|
+
if (tokens[index]?.value === '.') {
|
|
224
|
+
index += 1
|
|
225
|
+
const second = readName()
|
|
226
|
+
if (second === undefined) return undefined
|
|
227
|
+
database = first
|
|
228
|
+
table = second
|
|
229
|
+
}
|
|
230
|
+
// A join or a second table makes "this row" ambiguous: refuse to generate SQL.
|
|
231
|
+
let joined = 0
|
|
232
|
+
for (let cursor = index; cursor < end; cursor += 1) {
|
|
233
|
+
const value = tokens[cursor].value.toLowerCase()
|
|
234
|
+
if (value === '(') joined += 1
|
|
235
|
+
else if (value === ')') joined = Math.max(0, joined - 1)
|
|
236
|
+
else if (joined === 0 && (value === ',' || value === 'join')) return undefined
|
|
237
|
+
}
|
|
238
|
+
return { database, table }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** One SQL literal: numbers stay bare, everything else is quoted with '' doubling. */
|
|
242
|
+
export function dwSqlLiteral(value, numeric) {
|
|
243
|
+
if (value === null || value === undefined) return 'NULL'
|
|
244
|
+
const text = String(value)
|
|
245
|
+
if (numeric === true && /^-?\d+(\.\d+)?$/.test(text.trim())) return text.trim()
|
|
246
|
+
return `'${text.replace(/'/g, "''")}'`
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Build the UPDATE a result row editor copies; it is never executed here. */
|
|
250
|
+
export function dwSqlUpdate(target, assignments, conditions) {
|
|
251
|
+
const quote = (name) => `\`${String(name).replace(/`/g, '``')}\``
|
|
252
|
+
const from = target.database === '' ? quote(target.table) : `${quote(target.database)}.${quote(target.table)}`
|
|
253
|
+
const set = assignments.map((entry) => `${quote(entry.column)} = ${dwSqlLiteral(entry.value, entry.numeric)}`).join(', ')
|
|
254
|
+
const where = conditions.map((entry) => `${quote(entry.column)} = ${dwSqlLiteral(entry.value, entry.numeric)}`).join(' AND ')
|
|
255
|
+
// No LIMIT: the WHERE is the row's primary key, so it is already unique, and
|
|
256
|
+
// `UPDATE … LIMIT` is MySQL-only syntax that would break when pasted elsewhere.
|
|
257
|
+
return `UPDATE ${from}\nSET ${set}\nWHERE ${where};`
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** MySQL's PRI_KEY_FLAG marks the columns of the primary key. */
|
|
261
|
+
export function dwIsPrimaryKey(column) {
|
|
262
|
+
return (Number(column?.flags ?? 0) & 2) === 2
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Tokens that carry meaning for completion and formatting. */
|
|
266
|
+
function dwSqlSignificant(tokens) {
|
|
267
|
+
return tokens.filter((token) => token.type !== 'space')
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Strip the backticks/quoting one identifier carries. */
|
|
271
|
+
function dwSqlUnquote(value) {
|
|
272
|
+
const text = String(value ?? '').trim()
|
|
273
|
+
if (text.length > 1 && (text[0] === '`' || text[0] === '"') && text[text.length - 1] === text[0]) {
|
|
274
|
+
return text.slice(1, -1)
|
|
275
|
+
}
|
|
276
|
+
return text
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* `db.table` → `table`, aware of per-part backticks.
|
|
281
|
+
*
|
|
282
|
+
* MySQL statements in this console usually quote both parts (`db`.`table`), so
|
|
283
|
+
* splitting on the raw string leaves a leading backtick on the table name and the
|
|
284
|
+
* schema lookup misses.
|
|
285
|
+
*/
|
|
286
|
+
function dwSqlTableName(value) {
|
|
287
|
+
const text = String(value ?? '').trim()
|
|
288
|
+
let quoted = false
|
|
289
|
+
let lastDot = -1
|
|
290
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
291
|
+
const char = text[index]
|
|
292
|
+
if (char === '`') quoted = !quoted
|
|
293
|
+
else if (char === '.' && !quoted) lastDot = index
|
|
294
|
+
}
|
|
295
|
+
return dwSqlUnquote(text.slice(lastDot + 1).trim())
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Tables and aliases the statement mentions.
|
|
300
|
+
*
|
|
301
|
+
* Only `FROM` and `JOIN` are scanned; a comma-separated FROM list is rare in this
|
|
302
|
+
* console's queries and a miss only means fewer column suggestions.
|
|
303
|
+
*/
|
|
304
|
+
export function dwSqlTableRefs(text) {
|
|
305
|
+
const refs = []
|
|
306
|
+
const seen = new Set()
|
|
307
|
+
const pattern = /\b(from|join)\s+((?:`[^`]+`|[A-Za-z0-9_$]+)(?:\.(?:`[^`]+`|[A-Za-z0-9_$]+))?)(?:\s+(?:as\s+)?(`[^`]+`|[A-Za-z_][A-Za-z0-9_$]*))?/gi
|
|
308
|
+
let match
|
|
309
|
+
while ((match = pattern.exec(String(text ?? ''))) !== null) {
|
|
310
|
+
const table = dwSqlTableName(match[2])
|
|
311
|
+
if (table === '') continue
|
|
312
|
+
let alias = match[3] === undefined ? table : dwSqlUnquote(match[3])
|
|
313
|
+
if (DW_SQL_KEYWORDS.has(alias.toLowerCase()) || alias === '') alias = table
|
|
314
|
+
const key = alias.toLowerCase()
|
|
315
|
+
if (seen.has(key)) continue
|
|
316
|
+
seen.add(key)
|
|
317
|
+
refs.push({ table, alias })
|
|
318
|
+
}
|
|
319
|
+
return refs
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The word being typed and the context around it. */
|
|
323
|
+
function dwSqlCompletionPrefix(source, caret) {
|
|
324
|
+
let start = caret
|
|
325
|
+
while (start > 0 && /[A-Za-z0-9_$`]/.test(source[start - 1])) start -= 1
|
|
326
|
+
const prefix = source.slice(start, caret).replace(/`/g, '')
|
|
327
|
+
let qualifier = ''
|
|
328
|
+
let before = source.slice(0, start).replace(/\s+$/, '')
|
|
329
|
+
if (before.endsWith('.')) {
|
|
330
|
+
const match = /([A-Za-z0-9_$`]+)\.$/.exec(before)
|
|
331
|
+
qualifier = match === null ? '' : dwSqlUnquote(match[1])
|
|
332
|
+
before = before.slice(0, -1 - qualifier.length).replace(/\s+$/, '')
|
|
333
|
+
}
|
|
334
|
+
const previous = /([A-Za-z_][A-Za-z0-9_$]*)$/.exec(before)
|
|
335
|
+
return {
|
|
336
|
+
prefix,
|
|
337
|
+
qualifier,
|
|
338
|
+
startedAfterDot: qualifier !== '',
|
|
339
|
+
previousWord: previous === null ? '' : previous[1].toLowerCase(),
|
|
340
|
+
from: start,
|
|
341
|
+
to: caret,
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Which family of suggestions a clause asks for. */
|
|
346
|
+
function dwSqlSuggestionKind(context) {
|
|
347
|
+
if (context.qualifier !== '') return 'column'
|
|
348
|
+
const word = context.previousWord
|
|
349
|
+
if (['from', 'join', 'into', 'update', 'table'].includes(word)) return 'table'
|
|
350
|
+
if (['select', 'where', 'on', 'and', 'or', 'having', 'by', 'set', 'using', 'distinct', 'case', 'when', 'then', 'else', 'order', 'group', 'value'].includes(word)) return 'column'
|
|
351
|
+
return 'any'
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Build the suggestion list for the caret.
|
|
356
|
+
*
|
|
357
|
+
* `schema` is the Host's map of the current database (`{ tables: [{ name,
|
|
358
|
+
* columns: [{ name, type }] }] }`); without it the list degrades to keywords.
|
|
359
|
+
*/
|
|
360
|
+
export function dwSqlCompletion(text, caret, schema) {
|
|
361
|
+
const source = String(text ?? '')
|
|
362
|
+
const position = Math.max(0, Math.min(Number(caret) || 0, source.length))
|
|
363
|
+
const context = dwSqlCompletionPrefix(source, position)
|
|
364
|
+
const kind = dwSqlSuggestionKind(context)
|
|
365
|
+
const prefix = context.prefix.toLowerCase()
|
|
366
|
+
const tables = Array.isArray(schema?.tables) ? schema.tables : []
|
|
367
|
+
const refs = dwSqlTableRefs(source)
|
|
368
|
+
const items = []
|
|
369
|
+
const seen = new Set()
|
|
370
|
+
|
|
371
|
+
const add = (label, type, detail) => {
|
|
372
|
+
const key = `${type}\u0000${label.toLowerCase()}`
|
|
373
|
+
if (seen.has(key)) return
|
|
374
|
+
if (prefix !== '' && !label.toLowerCase().startsWith(prefix)) return
|
|
375
|
+
if (label.toLowerCase() === prefix) return
|
|
376
|
+
seen.add(key)
|
|
377
|
+
items.push({ label, kind: type, detail })
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const tableWith = (name) => tables.find((table) => table.name.toLowerCase() === name.toLowerCase())
|
|
381
|
+
|
|
382
|
+
if (context.qualifier !== '') {
|
|
383
|
+
const ref = refs.find((entry) => entry.alias.toLowerCase() === context.qualifier.toLowerCase())
|
|
384
|
+
?? refs.find((entry) => entry.table.toLowerCase() === context.qualifier.toLowerCase())
|
|
385
|
+
const table = tableWith(ref?.table ?? context.qualifier)
|
|
386
|
+
for (const column of Array.isArray(table?.columns) ? table.columns : []) {
|
|
387
|
+
add(column.name, 'column', `${table.name}.${column.type ?? ''}`)
|
|
388
|
+
}
|
|
389
|
+
} else if (kind === 'table') {
|
|
390
|
+
for (const table of tables) add(table.name, 'table', `${table.columns?.length ?? 0} 列`)
|
|
391
|
+
for (const ref of refs) add(ref.table, 'table', '已引用')
|
|
392
|
+
} else {
|
|
393
|
+
if (kind === 'column' || kind === 'any') {
|
|
394
|
+
for (const ref of refs) {
|
|
395
|
+
const table = tableWith(ref.table)
|
|
396
|
+
for (const column of Array.isArray(table?.columns) ? table.columns : []) {
|
|
397
|
+
add(column.name, 'column', `${ref.alias === ref.table ? ref.table : `${ref.alias} → ${ref.table}`}.${column.type ?? ''}`)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (refs.length === 0) {
|
|
401
|
+
for (const table of tables) {
|
|
402
|
+
for (const column of Array.isArray(table.columns) ? table.columns : []) {
|
|
403
|
+
add(column.name, 'column', `${table.name}.${column.type ?? ''}`)
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (kind !== 'column') {
|
|
409
|
+
for (const keyword of DW_SQL_KEYWORDS) add(keyword.toUpperCase(), 'keyword', '关键字')
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
items.sort((left, right) => {
|
|
414
|
+
const weight = (item) => (item.kind === 'column' ? 0 : item.kind === 'table' ? 1 : 2)
|
|
415
|
+
if (weight(left) !== weight(right)) return weight(left) - weight(right)
|
|
416
|
+
return left.label.length - right.label.length || (left.label < right.label ? -1 : 1)
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
return {
|
|
420
|
+
items: items.slice(0, 50),
|
|
421
|
+
from: context.from,
|
|
422
|
+
to: context.to,
|
|
423
|
+
prefix: context.prefix,
|
|
424
|
+
kind,
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const DW_SQL_JOIN_PREFIXES = new Set(['left', 'right', 'inner', 'outer', 'full', 'cross', 'natural'])
|
|
429
|
+
|
|
430
|
+
/** Whether the select list starting at `index` carries a top-level comma. */
|
|
431
|
+
function dwSqlSelectListHasComma(tokens, index) {
|
|
432
|
+
let depth = 0
|
|
433
|
+
for (let cursor = index; cursor < tokens.length; cursor += 1) {
|
|
434
|
+
const value = tokens[cursor].value
|
|
435
|
+
if (value === '(') {
|
|
436
|
+
depth += 1
|
|
437
|
+
continue
|
|
438
|
+
}
|
|
439
|
+
if (value === ')') {
|
|
440
|
+
if (depth === 0) return false
|
|
441
|
+
depth -= 1
|
|
442
|
+
continue
|
|
443
|
+
}
|
|
444
|
+
const lower = value.toLowerCase()
|
|
445
|
+
if (depth === 0 && ['from', 'where', 'group', 'order', 'having', 'limit', 'union'].includes(lower)) return false
|
|
446
|
+
if (depth === 0 && value === ',') return true
|
|
447
|
+
}
|
|
448
|
+
return false
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Collapse the run of spaces/tabs one line may start with. */
|
|
452
|
+
function dwSqlIndent(level) {
|
|
453
|
+
return ' '.repeat(Math.max(0, level))
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Reindent a statement: clause keywords on their own line, one select item per
|
|
458
|
+
* line, joins and boolean operators indented one level. Keyword case and inline
|
|
459
|
+
* spacing are preserved; only line breaks and indentation move.
|
|
460
|
+
*/
|
|
461
|
+
export function dwFormatSql(text) {
|
|
462
|
+
const tokens = dwSqlSignificant(dwSqlLex(text))
|
|
463
|
+
if (tokens.length === 0) return ''
|
|
464
|
+
|
|
465
|
+
const lines = []
|
|
466
|
+
let line = ''
|
|
467
|
+
let depth = 0
|
|
468
|
+
let clause = ''
|
|
469
|
+
let selectDepth = -1
|
|
470
|
+
const parens = []
|
|
471
|
+
|
|
472
|
+
const push = (value) => {
|
|
473
|
+
line += value
|
|
474
|
+
}
|
|
475
|
+
const pushWord = (value) => {
|
|
476
|
+
const last = line[line.length - 1]
|
|
477
|
+
if (line !== '' && last !== ' ' && last !== '.' && last !== '(' && value !== '.' && value !== ')' && value !== ',' && value !== '(') {
|
|
478
|
+
line += ' '
|
|
479
|
+
}
|
|
480
|
+
line += value
|
|
481
|
+
}
|
|
482
|
+
const newlineAt = (level) => {
|
|
483
|
+
lines.push(line.trimEnd())
|
|
484
|
+
line = dwSqlIndent(level)
|
|
485
|
+
}
|
|
486
|
+
const atIndex = (index) => (tokens[index] === undefined ? '' : tokens[index].value.toLowerCase())
|
|
487
|
+
const isWord = (index) => tokens[index] !== undefined && tokens[index].type === 'identifier'
|
|
488
|
+
|
|
489
|
+
let index = 0
|
|
490
|
+
while (index < tokens.length) {
|
|
491
|
+
const token = tokens[index]
|
|
492
|
+
const lower = token.value.toLowerCase()
|
|
493
|
+
const next = atIndex(index + 1)
|
|
494
|
+
|
|
495
|
+
if (token.type === 'comment') {
|
|
496
|
+
if (line.trim() !== '') newlineAt(depth * 2)
|
|
497
|
+
push(token.value)
|
|
498
|
+
newlineAt(depth * 2)
|
|
499
|
+
index += 1
|
|
500
|
+
continue
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// Multi-word clause keywords: GROUP BY / ORDER BY / UNION ALL / JOIN prefixes.
|
|
504
|
+
if (lower === 'group' && next === 'by') {
|
|
505
|
+
newlineAt(depth * 2)
|
|
506
|
+
push(`${token.value} ${tokens[index + 1].value}`)
|
|
507
|
+
clause = 'group'
|
|
508
|
+
index += 2
|
|
509
|
+
continue
|
|
510
|
+
}
|
|
511
|
+
if (lower === 'order' && next === 'by') {
|
|
512
|
+
newlineAt(depth * 2)
|
|
513
|
+
push(`${token.value} ${tokens[index + 1].value}`)
|
|
514
|
+
clause = 'order'
|
|
515
|
+
index += 2
|
|
516
|
+
continue
|
|
517
|
+
}
|
|
518
|
+
if (lower === 'union') {
|
|
519
|
+
newlineAt(depth * 2)
|
|
520
|
+
push(token.value)
|
|
521
|
+
if (next === 'all' || next === 'distinct') {
|
|
522
|
+
push(` ${tokens[index + 1].value}`)
|
|
523
|
+
index += 2
|
|
524
|
+
} else {
|
|
525
|
+
index += 1
|
|
526
|
+
}
|
|
527
|
+
clause = 'union'
|
|
528
|
+
continue
|
|
529
|
+
}
|
|
530
|
+
if (
|
|
531
|
+
lower === 'join'
|
|
532
|
+
|| (DW_SQL_JOIN_PREFIXES.has(lower) && ['join', 'outer'].includes(next))
|
|
533
|
+
|| (DW_SQL_JOIN_PREFIXES.has(lower) && next === 'outer' && atIndex(index + 2) === 'join')
|
|
534
|
+
) {
|
|
535
|
+
newlineAt(depth * 2 + 2)
|
|
536
|
+
let consumed = 1
|
|
537
|
+
if (lower !== 'join') consumed = 2
|
|
538
|
+
if (next === 'outer' && atIndex(index + 2) === 'join') consumed = 3
|
|
539
|
+
push(tokens.slice(index, index + consumed).map((entry) => entry.value).join(' '))
|
|
540
|
+
clause = 'join'
|
|
541
|
+
index += consumed
|
|
542
|
+
continue
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (token.type === 'keyword') {
|
|
546
|
+
if (lower === 'select') {
|
|
547
|
+
newlineAt(depth * 2)
|
|
548
|
+
push(token.value)
|
|
549
|
+
clause = 'select'
|
|
550
|
+
selectDepth = depth
|
|
551
|
+
if (dwSqlSelectListHasComma(tokens, index + 1)) newlineAt(depth * 2 + 2)
|
|
552
|
+
index += 1
|
|
553
|
+
continue
|
|
554
|
+
}
|
|
555
|
+
if (['from', 'where', 'having', 'limit', 'offset'].includes(lower)) {
|
|
556
|
+
newlineAt(depth * 2)
|
|
557
|
+
push(token.value)
|
|
558
|
+
clause = lower
|
|
559
|
+
if (lower === 'from') selectDepth = -1
|
|
560
|
+
index += 1
|
|
561
|
+
continue
|
|
562
|
+
}
|
|
563
|
+
if (lower === 'on') {
|
|
564
|
+
pushWord(token.value)
|
|
565
|
+
clause = 'on'
|
|
566
|
+
index += 1
|
|
567
|
+
continue
|
|
568
|
+
}
|
|
569
|
+
if ((lower === 'and' || lower === 'or') && ['where', 'having', 'on'].includes(clause)) {
|
|
570
|
+
newlineAt(depth * 2 + 2)
|
|
571
|
+
push(token.value)
|
|
572
|
+
index += 1
|
|
573
|
+
continue
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
if (token.value === '(') {
|
|
578
|
+
push('(')
|
|
579
|
+
depth += 1
|
|
580
|
+
const subquery = atIndex(index + 1) === 'select'
|
|
581
|
+
parens.push({ subquery })
|
|
582
|
+
if (subquery) {
|
|
583
|
+
newlineAt(depth * 2)
|
|
584
|
+
push(tokens[index + 1].value)
|
|
585
|
+
clause = 'select'
|
|
586
|
+
selectDepth = depth
|
|
587
|
+
index += 2
|
|
588
|
+
continue
|
|
589
|
+
}
|
|
590
|
+
index += 1
|
|
591
|
+
continue
|
|
592
|
+
}
|
|
593
|
+
if (token.value === ')') {
|
|
594
|
+
depth = Math.max(0, depth - 1)
|
|
595
|
+
const scope = parens.pop()
|
|
596
|
+
if (scope !== undefined && scope.subquery === true) {
|
|
597
|
+
newlineAt(depth * 2)
|
|
598
|
+
}
|
|
599
|
+
push(')')
|
|
600
|
+
index += 1
|
|
601
|
+
continue
|
|
602
|
+
}
|
|
603
|
+
if (token.value === ',') {
|
|
604
|
+
push(',')
|
|
605
|
+
if (clause === 'select' && selectDepth === depth) newlineAt(depth * 2 + 2)
|
|
606
|
+
else pushWord('')
|
|
607
|
+
index += 1
|
|
608
|
+
continue
|
|
609
|
+
}
|
|
610
|
+
if (token.value === ';') {
|
|
611
|
+
push(';')
|
|
612
|
+
newlineAt(0)
|
|
613
|
+
index += 1
|
|
614
|
+
continue
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
pushWord(token.value)
|
|
618
|
+
if (token.value === '.') line = line.replace(/ $/, '')
|
|
619
|
+
index += 1
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
lines.push(line.trimEnd())
|
|
623
|
+
return lines
|
|
624
|
+
.map((entry) => entry.replace(/\s+$/, ''))
|
|
625
|
+
.filter((entry, position, all) => entry !== '' || (position > 0 && position < all.length - 1))
|
|
626
|
+
.join('\n')
|
|
627
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
628
|
+
.trim()
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export { DW_SQL_KEYWORDS, DW_SQL_FUNCTIONS }
|