This repository has been archived by the owner on Dec 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSQLEditor.tsx
437 lines (393 loc) · 15.2 KB
/
SQLEditor.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import { CodeEditor, Monaco, monacoTypes } from '@grafana/ui';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { getStatementPosition } from '../standardSql/getStatementPosition';
import { getStandardSuggestions } from '../standardSql/getStandardSuggestions';
import { initSuggestionsKindRegistry, SuggestionKindRegistryItem } from '../standardSql/suggestionsKindRegistry';
import {
CompletionItemInsertTextRule,
CompletionItemKind,
CompletionItemPriority,
CustomSuggestion,
PositionContext,
SQLCompletionItemProvider,
StatementPosition,
SuggestionKind,
} from '../types';
import { getSuggestionKinds } from '../utils/getSuggestionKind';
import { linkedTokenBuilder } from '../utils/linkedTokenBuilder';
import { defaultTableNameParser, getTableToken } from '../utils/tokenUtils';
import { TRIGGER_SUGGEST } from '../utils/commands';
import { v4 } from 'uuid';
import { Registry } from '@grafana/data';
import {
FunctionsRegistryItem,
MacrosRegistryItem,
OperatorsRegistryItem,
SQLMonarchLanguage,
StatementPositionResolversRegistryItem,
SuggestionsRegistryItem,
} from '../standardSql/types';
import { initStandardSuggestions } from '../standardSql/standardSuggestionsRegistry';
import { initStatementPositionResolvers } from '../standardSql/statementPositionResolversRegistry';
import { sqlEditorLog } from '../utils/debugger';
import standardSQLLanguageDefinition from '../standardSql/definition';
import { getStandardSQLCompletionProvider } from '../standardSql/standardSQLCompletionItemProvider';
const STANDARD_SQL_LANGUAGE = 'sql';
export interface LanguageDefinition extends monacoTypes.languages.ILanguageExtensionPoint {
loader?: (module: any) => Promise<{
language: SQLMonarchLanguage;
conf: monacoTypes.languages.LanguageConfiguration;
}>;
// Provides API for customizing the autocomplete
completionProvider?: (m: Monaco, language: SQLMonarchLanguage) => SQLCompletionItemProvider;
// Function that returns a formatted query
formatter?: (q: string) => string;
}
interface SQLEditorProps {
query: string;
/**
* Use for inspecting the query as it changes. I.e. for validation.
*/
onChange?: (q: string, processQuery: boolean) => void;
onBlur?: (text: string) => void;
language?: LanguageDefinition;
children?: (props: { formatQuery: () => void }) => React.ReactNode;
width?: number;
height?: number;
}
interface LanguageRegistries {
functions: Registry<FunctionsRegistryItem>;
operators: Registry<OperatorsRegistryItem>;
suggestionKinds: Registry<SuggestionKindRegistryItem>;
positionResolvers: Registry<StatementPositionResolversRegistryItem>;
macros: Registry<MacrosRegistryItem>;
}
const LANGUAGES_CACHE = new Map<string, LanguageRegistries>();
const INSTANCE_CACHE = new Map<string, Registry<SuggestionsRegistryItem>>();
export const SQLEditor = ({
children,
onBlur,
onChange,
query,
language = { id: STANDARD_SQL_LANGUAGE },
width,
height,
}: SQLEditorProps) => {
const monacoRef = useRef<monacoTypes.editor.IStandaloneCodeEditor | null>(null);
const langUid = useRef<string>();
// create unique language id for each SQLEditor instance
const id = useMemo(() => {
const uid = v4();
const id = `${language.id}-${uid}`;
langUid.current = id;
return id;
}, [language.id]);
useEffect(() => {
return () => {
if (langUid.current) {
INSTANCE_CACHE.delete(langUid.current);
}
sqlEditorLog(`Removing instance cache ${langUid.current}`, false, INSTANCE_CACHE);
};
}, []);
const formatQuery = useCallback(() => {
if (monacoRef.current) {
monacoRef.current.getAction('editor.action.formatDocument').run();
}
}, []);
const onSqlBlur = (text: string) => {
onChange && onChange(text, false);
onBlur && onBlur(text);
};
return (
<div style={{ width }}>
<CodeEditor
height={height || '240px'}
// -2px to compensate for borders width
width={width ? `${width - 2}px` : undefined}
language={id}
value={query}
onBlur={onSqlBlur}
showMiniMap={false}
showLineNumbers={true}
// Using onEditorDidMount instead of onBeforeEditorMount to support Grafana < 8.2.x
onEditorDidMount={(editor, m) => {
monacoRef.current = editor;
editor.onDidChangeModelContent((e) => {
const text = editor.getValue();
if (onChange) {
onChange(text, false);
}
});
editor.addCommand(m.KeyMod.CtrlCmd | m.KeyCode.Enter, () => {
const text = editor.getValue();
if (onChange) {
onChange(text, true);
}
});
editor.onKeyUp((e) => {
// keyCode 84 is . (DOT)
if (e.keyCode === 84) {
editor.trigger(TRIGGER_SUGGEST.id, TRIGGER_SUGGEST.id, {});
}
});
registerLanguageAndSuggestions(m, language, id);
}}
/>
{children && children({ formatQuery })}
</div>
);
};
// There's three ways to define Monaco language:
// 1. Leave language.id empty or set it to 'sql'. This will load a standard sql language definition, including syntax highlighting and tokenization for
// common Grafana entities such as macros and template variables
// 2. Provide a custom language and load it via the async LanguageDefinition.loader callback
// 3. Specify a language.id that exists in the Monaco language registry. A custom completion item provider can still be provided.
// If not, the standard SQL completion item provider will be used. See available languages here: https://github.com/microsoft/monaco-editor/tree/main/src/basic-languages
// If a custom language is specified, its LanguageDefinition will be merged with the LanguageDefinition for standard SQL. This allows the consumer to only
// override parts of the LanguageDefinition, such as for example the completion item provider.
const resolveLanguage = (monaco: Monaco, languageDefinitionProp: LanguageDefinition): LanguageDefinition => {
if (languageDefinitionProp?.id !== STANDARD_SQL_LANGUAGE && !languageDefinitionProp.loader) {
sqlEditorLog(`Loading language '${languageDefinitionProp?.id}' from Monaco registry`, false);
const allLangs = monaco.languages.getLanguages();
const custom = allLangs.find(({ id }) => id === languageDefinitionProp?.id);
if (!custom) {
throw Error(`Unknown Monaco language ${languageDefinitionProp?.id}`);
}
return { completionProvider: getStandardSQLCompletionProvider, ...custom, ...languageDefinitionProp };
}
return {
...standardSQLLanguageDefinition,
...languageDefinitionProp,
};
};
export const registerLanguageAndSuggestions = async (monaco: Monaco, l: LanguageDefinition, lid: string) => {
const languageDefinition = resolveLanguage(monaco, l);
if (!languageDefinition.loader) {
return;
}
const { language, conf } = await languageDefinition.loader(monaco);
monaco.languages.register({ id: lid });
monaco.languages.setMonarchTokensProvider(lid, { ...language });
monaco.languages.setLanguageConfiguration(lid, { ...conf });
if (languageDefinition.formatter) {
monaco.languages.registerDocumentFormattingEditProvider(lid, {
provideDocumentFormattingEdits: (model) => {
const formatted = l.formatter?.(model.getValue());
return [
{
range: model.getFullModelRange(),
text: formatted || '',
},
];
},
});
}
if (languageDefinition.completionProvider) {
const customProvider = languageDefinition.completionProvider(monaco, language);
extendStandardRegistries(l.id, lid, customProvider);
const languageSuggestionsRegistries = LANGUAGES_CACHE.get(l.id)!;
const instanceSuggestionsRegistry = INSTANCE_CACHE.get(lid)!;
const completionProvider: monacoTypes.languages.CompletionItemProvider['provideCompletionItems'] = async (
model,
position,
context,
token
) => {
const currentToken = linkedTokenBuilder(monaco, model, position, lid);
const statementPosition = getStatementPosition(currentToken, languageSuggestionsRegistries.positionResolvers);
const kind = getSuggestionKinds(statementPosition, languageSuggestionsRegistries.suggestionKinds);
sqlEditorLog('Statement position', false, statementPosition);
sqlEditorLog('Suggestion kinds', false, kind);
const ctx: PositionContext = {
position,
currentToken,
statementPosition,
kind,
range: monaco.Range.fromPositions(position),
};
const stdSuggestions = await getStandardSuggestions(monaco, currentToken, kind, ctx, instanceSuggestionsRegistry);
return {
suggestions: stdSuggestions,
};
};
monaco.languages.registerCompletionItemProvider(lid, {
...customProvider,
provideCompletionItems: completionProvider,
});
}
};
function extendStandardRegistries(id: string, lid: string, customProvider: SQLCompletionItemProvider) {
if (!LANGUAGES_CACHE.has(id)) {
initializeLanguageRegistries(id);
}
const languageRegistries = LANGUAGES_CACHE.get(id)!;
if (!INSTANCE_CACHE.has(lid)) {
INSTANCE_CACHE.set(
lid,
new Registry(
initStandardSuggestions(languageRegistries.functions, languageRegistries.operators, languageRegistries.macros)
)
);
}
const instanceSuggestionsRegistry = INSTANCE_CACHE.get(lid)!;
if (customProvider.supportedFunctions) {
for (const func of customProvider.supportedFunctions()) {
const exists = languageRegistries.functions.getIfExists(func.id);
if (!exists) {
languageRegistries.functions.register(func);
}
}
}
if (customProvider.supportedOperators) {
for (const op of customProvider.supportedOperators()) {
const exists = languageRegistries.operators.getIfExists(op.id);
if (!exists) {
languageRegistries.operators.register({ ...op, name: op.id });
}
}
}
if (customProvider.supportedMacros) {
for (const macro of customProvider.supportedMacros()) {
const exists = languageRegistries.macros.getIfExists(macro.id);
if (!exists) {
languageRegistries.macros.register({ ...macro, name: macro.id });
}
}
}
if (customProvider.customStatementPlacement) {
for (const placement of customProvider.customStatementPlacement()) {
const exists = languageRegistries.positionResolvers.getIfExists(placement.id);
if (!exists) {
languageRegistries.positionResolvers.register({
...placement,
id: placement.id as StatementPosition,
name: placement.id,
});
languageRegistries.suggestionKinds.register({
id: placement.id as StatementPosition,
name: placement.id,
kind: [],
});
} else {
// Allow extension to the built-in placement resolvers
const origResolve = exists.resolve;
exists.resolve = (...args) => {
const ext = placement.resolve(...args);
if (placement.overrideDefault) {
return ext;
}
const orig = origResolve(...args);
return orig || ext;
};
}
}
}
if (customProvider.customSuggestionKinds) {
for (const kind of customProvider.customSuggestionKinds()) {
kind.applyTo?.forEach((applyTo) => {
const exists = languageRegistries.suggestionKinds.getIfExists(applyTo);
if (exists) {
// avoid duplicates
if (exists.kind.indexOf(kind.id as SuggestionKind) === -1) {
exists.kind.push(kind.id as SuggestionKind);
}
}
});
if (kind.overrideDefault) {
const stbBehaviour = instanceSuggestionsRegistry.get(kind.id);
if (stbBehaviour !== undefined) {
stbBehaviour.suggestions = kind.suggestionsResolver;
continue;
}
}
instanceSuggestionsRegistry.register({
id: kind.id as SuggestionKind,
name: kind.id,
suggestions: kind.suggestionsResolver,
});
}
}
if (customProvider.schemas) {
const stbBehaviour = instanceSuggestionsRegistry.get(SuggestionKind.Schemas);
const s = stbBehaviour.suggestions;
stbBehaviour.suggestions = async (ctx, m) => {
const standardSchemas = await s(ctx, m);
if (!customProvider.schemas) {
return [...standardSchemas];
}
const customSchemas = await customProvider.schemas.resolve();
const customSchemaCompletionItems = customSchemas.map((x) => ({
label: x.name,
insertText: `${x.completion ?? x.name}.`,
command: TRIGGER_SUGGEST,
kind: CompletionItemKind.Module, // it's nice to differentiate schemas from tables
sortText: CompletionItemPriority.High,
}));
return [...standardSchemas, ...customSchemaCompletionItems];
};
}
if (customProvider.tables) {
const stbBehaviour = instanceSuggestionsRegistry.get(SuggestionKind.Tables);
const s = stbBehaviour.suggestions;
stbBehaviour.suggestions = async (ctx, m) => {
const o = await s(ctx, m);
const tableToken = getTableToken(ctx.currentToken);
const tableNameParser = customProvider.tables?.parseName ?? defaultTableNameParser;
const tableIdentifier = tableNameParser(tableToken);
const oo = ((await customProvider.tables?.resolve?.(tableIdentifier)) ?? []).map((x) => ({
label: x.name,
// if no custom completion is provided it's safe to move cursor further in the statement
insertText: `${x.completion ?? x.name}${x.completion === x.name ? ' $0' : ''}`,
insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet,
command: TRIGGER_SUGGEST,
kind: CompletionItemKind.Field,
sortText: CompletionItemPriority.MediumHigh,
}));
return [...o, ...oo];
};
}
if (customProvider.columns) {
const stbBehaviour = instanceSuggestionsRegistry.get(SuggestionKind.Columns);
const s = stbBehaviour.suggestions;
stbBehaviour.suggestions = async (ctx, m) => {
const o = await s(ctx, m);
const tableToken = getTableToken(ctx.currentToken);
let tableIdentifier;
const tableNameParser = customProvider.tables?.parseName ?? defaultTableNameParser;
if (tableToken && tableToken.value) {
tableIdentifier = tableNameParser(tableToken);
}
let oo: CustomSuggestion[] = [];
if (tableIdentifier) {
const columns = await customProvider.columns?.resolve!(tableIdentifier);
oo = columns
? columns.map<CustomSuggestion>((x) => ({
label: x.name,
insertText: x.completion ?? x.name,
kind: CompletionItemKind.Field,
sortText: CompletionItemPriority.High,
detail: x.type,
documentation: x.description,
}))
: [];
}
return [...o, ...oo];
};
}
}
/**
* Initializes language specific registries that are treated as singletons
*/
function initializeLanguageRegistries(id: string) {
if (!LANGUAGES_CACHE.has(id)) {
LANGUAGES_CACHE.set(id, {
functions: new Registry(),
operators: new Registry(),
suggestionKinds: new Registry(initSuggestionsKindRegistry),
positionResolvers: new Registry(initStatementPositionResolvers),
macros: new Registry(),
});
}
return LANGUAGES_CACHE.get(id)!;
}