forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.test.ts
1088 lines (997 loc) · 36.6 KB
/
autocomplete.test.ts
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { suggest } from './autocomplete';
import { scalarFunctionDefinitions } from '../definitions/generated/scalar_functions';
import { timeUnitsToSuggest } from '../definitions/literals';
import { commandDefinitions as unmodifiedCommandDefinitions } from '../definitions/commands';
import { getSafeInsertText, TIME_SYSTEM_PARAMS, TRIGGER_SUGGESTION_COMMAND } from './factories';
import { getAstAndSyntaxErrors } from '@kbn/esql-ast';
import {
policies,
getFunctionSignaturesByReturnType,
getFieldNamesByType,
createCustomCallbackMocks,
createCompletionContext,
getPolicyFields,
PartialSuggestionWithText,
TIME_PICKER_SUGGESTION,
setup,
attachTriggerCommand,
SuggestOptions,
fields,
} from './__tests__/helpers';
import { METADATA_FIELDS } from '../shared/constants';
import { ESQL_STRING_TYPES } from '../shared/esql_types';
import { getRecommendedQueries } from './recommended_queries/templates';
import { getDateHistogramCompletionItem } from './commands/stats/util';
const commandDefinitions = unmodifiedCommandDefinitions.filter(({ hidden }) => !hidden);
const getRecommendedQueriesSuggestions = (fromCommand: string, timeField?: string) =>
getRecommendedQueries({
fromCommand,
timeField,
});
describe('autocomplete', () => {
type TestArgs = [
string,
Array<string | PartialSuggestionWithText>,
string?,
Parameters<typeof createCustomCallbackMocks>?
];
const _testSuggestionsFn = (
{ only, skip }: { only?: boolean; skip?: boolean } = {},
statement: string,
expected: Array<string | PartialSuggestionWithText>,
triggerCharacter?: string,
customCallbacksArgs: Parameters<typeof createCustomCallbackMocks> = [
undefined,
undefined,
undefined,
]
) => {
const testFn = only ? test.only : skip ? test.skip : test;
testFn(statement, async () => {
const callbackMocks = createCustomCallbackMocks(...customCallbacksArgs);
const { assertSuggestions } = await setup();
await assertSuggestions(statement, expected, { callbacks: callbackMocks, triggerCharacter });
});
};
// Enrich the function to work with .only and .skip as regular test function
//
// DO NOT CHANGE THE NAME OF THIS FUNCTION WITHOUT ALSO CHANGING
// THE LINTER RULE IN packages/kbn-eslint-config/typescript.js
//
const testSuggestions = Object.assign(_testSuggestionsFn.bind(null, {}), {
skip: (...args: TestArgs) => {
return _testSuggestionsFn({ skip: true }, ...args);
},
only: (...args: TestArgs) => {
return _testSuggestionsFn({ only: true }, ...args);
},
});
// const sourceCommands = ['row', 'from', 'show', 'metrics']; Uncomment when metrics is being released
const sourceCommands = ['row', 'from', 'show'];
describe('New command', () => {
const recommendedQuerySuggestions = getRecommendedQueriesSuggestions('FROM logs*', 'dateField');
testSuggestions('/', [
...sourceCommands.map((name) => name.toUpperCase() + ' $0'),
...recommendedQuerySuggestions.map((q) => q.queryString),
]);
const commands = commandDefinitions
.filter(({ name }) => !sourceCommands.includes(name))
.map(({ name, types }) => {
if (types && types.length) {
const cmds: string[] = [];
for (const type of types) {
const cmd = type.name.toUpperCase() + ' ' + name.toUpperCase() + ' $0';
cmds.push(cmd);
}
return cmds;
} else {
return name.toUpperCase() + ' $0';
}
})
.flat();
testSuggestions('from a | /', commands);
testSuggestions('from a metadata _id | /', commands);
testSuggestions('from a | eval var0 = a | /', commands);
testSuggestions('from a metadata _id | eval var0 = a | /', commands);
});
describe('limit', () => {
testSuggestions('from a | limit /', ['10 ', '100 ', '1000 ']);
testSuggestions('from a | limit 4 /', ['| ']);
});
describe('mv_expand', () => {
testSuggestions('from a | mv_expand /', getFieldNamesByType('any'));
testSuggestions('from a | mv_expand a /', ['| ']);
});
describe('rename', () => {
testSuggestions('from a | rename /', getFieldNamesByType('any'));
testSuggestions('from a | rename keywordField /', ['AS $0'], ' ');
testSuggestions('from a | rename keywordField as /', ['var0']);
});
for (const command of ['keep', 'drop']) {
describe(command, () => {
testSuggestions(`from a | ${command} /`, getFieldNamesByType('any'));
testSuggestions(
`from a | ${command} keywordField, /`,
getFieldNamesByType('any').filter((name) => name !== 'keywordField')
);
testSuggestions(
`from a | ${command} keywordField,/`,
getFieldNamesByType('any').filter((name) => name !== 'keywordField'),
','
);
testSuggestions(
`from a_index | eval round(doubleField) + 1 | eval \`round(doubleField) + 1\` + 1 | eval \`\`\`round(doubleField) + 1\`\` + 1\` + 1 | eval \`\`\`\`\`\`\`round(doubleField) + 1\`\`\`\` + 1\`\` + 1\` + 1 | eval \`\`\`\`\`\`\`\`\`\`\`\`\`\`\`round(doubleField) + 1\`\`\`\`\`\`\`\` + 1\`\`\`\` + 1\`\` + 1\` + 1 | ${command} /`,
[
...getFieldNamesByType('any'),
'`round(doubleField) + 1`',
'```round(doubleField) + 1`` + 1`',
'```````round(doubleField) + 1```` + 1`` + 1`',
'```````````````round(doubleField) + 1```````` + 1```` + 1`` + 1`',
'```````````````````````````````round(doubleField) + 1```````````````` + 1```````` + 1```` + 1`` + 1`',
],
undefined,
[
[
...fields,
// the following non-field columns will come over the wire as part of the response
{
name: 'round(doubleField) + 1',
type: 'double',
},
{
name: '`round(doubleField) + 1` + 1',
type: 'double',
},
{
name: '```round(doubleField) + 1`` + 1` + 1',
type: 'double',
},
{
name: '```````round(doubleField) + 1```` + 1`` + 1` + 1',
type: 'double',
},
{
name: '```````````````round(doubleField) + 1```````` + 1```` + 1`` + 1` + 1',
type: 'double',
},
],
]
);
it('should not suggest already-used fields and variables', async () => {
const { suggest: suggestTest } = await setup();
const getSuggestions = async (query: string, opts?: SuggestOptions) =>
(await suggestTest(query, opts)).map((value) => value.text);
expect(
await getSuggestions('from a_index | EVAL foo = 1 | KEEP /', {
callbacks: { getColumnsFor: () => [...fields, { name: 'foo', type: 'integer' }] },
})
).toContain('foo');
expect(
await getSuggestions('from a_index | EVAL foo = 1 | KEEP foo, /', {
callbacks: { getColumnsFor: () => [...fields, { name: 'foo', type: 'integer' }] },
})
).not.toContain('foo');
expect(await getSuggestions('from a_index | KEEP /')).toContain('doubleField');
expect(await getSuggestions('from a_index | KEEP doubleField, /')).not.toContain(
'doubleField'
);
});
});
}
// @TODO: get updated eval block from main
describe('values suggestions', () => {
testSuggestions('FROM "i/"', []);
testSuggestions('FROM "index/"', []);
testSuggestions('FROM " a/"', []);
testSuggestions('FROM "foo b/"', []);
testSuggestions('FROM a | WHERE tags == " /"', [], ' ');
testSuggestions('FROM a | WHERE tags == """ /"""', [], ' ');
testSuggestions('FROM a | WHERE tags == "a/"', []);
testSuggestions('FROM a | EVAL tags == " /"', [], ' ');
testSuggestions('FROM a | EVAL tags == "a"/', []);
testSuggestions('FROM a | STATS tags == " /"', [], ' ');
testSuggestions('FROM a | STATS tags == "a/"', []);
testSuggestions('FROM a | GROK "a/" "%{WORD:firstWord}"', []);
testSuggestions('FROM a | DISSECT "a/" "%{WORD:firstWord}"', []);
});
describe('callbacks', () => {
it('should send the columns query without the last command', async () => {
const callbackMocks = createCustomCallbackMocks(undefined, undefined, undefined);
const statement = 'from a | drop keywordField | eval var0 = abs(doubleField) ';
const triggerOffset = statement.lastIndexOf(' ');
const context = createCompletionContext(statement[triggerOffset]);
await suggest(
statement,
triggerOffset + 1,
context,
async (text) => (text ? getAstAndSyntaxErrors(text) : { ast: [], errors: [] }),
callbackMocks
);
expect(callbackMocks.getColumnsFor).toHaveBeenCalledWith({
query: 'from a | drop keywordField',
});
});
it('should send the fields query aware of the location', async () => {
const callbackMocks = createCustomCallbackMocks(undefined, undefined, undefined);
const statement = 'from a | drop | eval var0 = abs(doubleField) ';
const triggerOffset = statement.lastIndexOf('p') + 1; // drop <here>
const context = createCompletionContext(statement[triggerOffset]);
await suggest(
statement,
triggerOffset + 1,
context,
async (text) => (text ? getAstAndSyntaxErrors(text) : { ast: [], errors: [] }),
callbackMocks
);
expect(callbackMocks.getColumnsFor).toHaveBeenCalledWith({ query: 'from a' });
});
});
/**
* Monaco asks for suggestions in at least two different scenarios.
* 1. When the user types a non-whitespace character (e.g. 'FROM k') - this is the Invoke trigger kind
* 2. When the user types a character we've registered as a trigger character (e.g. ',') - this is the Trigger character trigger kind
*
* Historically we had good support for the trigger character trigger kind, but not for the Invoke trigger kind. That led
* to bad experiences like a list of sources not showing up when the user types 'FROM kib'. There they had to delete "kib"
* and press <space> to trigger suggestions via a trigger character.
*
* See https://microsoft.github.io/monaco-editor/typedoc/enums/languages.CompletionTriggerKind.html for more details
*/
describe('Invoke trigger kind (all commands)', () => {
// source command
let recommendedQuerySuggestions = getRecommendedQueriesSuggestions('FROM logs*', 'dateField');
testSuggestions('f/', [
...sourceCommands.map((cmd) => `${cmd.toUpperCase()} $0`),
...recommendedQuerySuggestions.map((q) => q.queryString),
]);
const commands = commandDefinitions
.filter(({ name }) => !sourceCommands.includes(name))
.map(({ name, types }) => {
if (types && types.length) {
const cmds: string[] = [];
for (const type of types) {
const cmd = type.name.toUpperCase() + ' ' + name.toUpperCase() + ' $0';
cmds.push(cmd);
}
return cmds;
} else {
return name.toUpperCase() + ' $0';
}
})
.flat();
// pipe command
testSuggestions('FROM k | E/', commands);
describe('function arguments', () => {
// function argument
testSuggestions('FROM kibana_sample_data_logs | EVAL TRIM(e/)', [
...getFieldNamesByType(['text', 'keyword']),
...getFunctionSignaturesByReturnType(
'eval',
['text', 'keyword'],
{ scalar: true },
undefined,
['trim']
),
]);
// subsequent function argument
const expectedDateDiff2ndArgSuggestions = [
TIME_PICKER_SUGGESTION,
...TIME_SYSTEM_PARAMS.map((t) => `${t}, `),
...getFieldNamesByType(['date', 'date_nanos']).map((name) => `${name}, `),
...getFunctionSignaturesByReturnType('eval', ['date', 'date_nanos'], { scalar: true }).map(
(s) => ({
...s,
text: `${s.text},`,
})
),
];
testSuggestions('FROM a | EVAL DATE_DIFF("day", /)', expectedDateDiff2ndArgSuggestions);
// trigger character case for comparison
testSuggestions('FROM a | EVAL DATE_DIFF("day", /)', expectedDateDiff2ndArgSuggestions, ' ');
});
// FROM source
testSuggestions('FROM k/', ['index1', 'index2'], undefined, [
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]);
// FROM source METADATA
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('', 'dateField');
testSuggestions('FROM index1 M/', ['METADATA $0']);
// FROM source METADATA field
testSuggestions('FROM index1 METADATA _/', METADATA_FIELDS);
// EVAL argument
testSuggestions('FROM index1 | EVAL b/', [
'var0 = ',
...getFieldNamesByType('any'),
...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }),
]);
testSuggestions('FROM index1 | EVAL var0 = f/', [
...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }),
]);
// DISSECT field
testSuggestions(
'FROM index1 | DISSECT b/',
getFieldNamesByType(ESQL_STRING_TYPES).map((name) => `${name} `)
);
// DROP (first field)
testSuggestions('FROM index1 | DROP f/', getFieldNamesByType('any'));
// DROP (subsequent field)
testSuggestions('FROM index1 | DROP field1, f/', getFieldNamesByType('any'));
// ENRICH policy
testSuggestions(
'FROM index1 | ENRICH p/',
policies.map(({ name }) => getSafeInsertText(name) + ' ')
);
// ENRICH policy ON
testSuggestions('FROM index1 | ENRICH policy O/', ['ON ', 'WITH ', '| ']);
// ENRICH policy ON field
testSuggestions(
'FROM index1 | ENRICH policy ON f/',
getFieldNamesByType('any').map((name) => `${name} `)
);
// ENRICH policy WITH policyfield
testSuggestions('FROM index1 | ENRICH policy WITH v/', [
'var0 = ',
...getPolicyFields('policy'),
]);
testSuggestions('FROM index1 | ENRICH policy WITH \tv/', [
'var0 = ',
...getPolicyFields('policy'),
]);
// GROK field
testSuggestions(
'FROM index1 | GROK f/',
getFieldNamesByType(ESQL_STRING_TYPES).map((field) => `${field} `),
undefined
);
// KEEP (first field)
testSuggestions('FROM index1 | KEEP f/', getFieldNamesByType('any'));
// KEEP (subsequent fields)
testSuggestions(
'FROM index1 | KEEP booleanField, f/',
getFieldNamesByType('any').filter((name) => name !== 'booleanField')
);
// LIMIT argument
// Here we actually test that the invoke trigger kind does NOT work
// the assumption is that it isn't very useful to see literal suggestions when already typing a number
// I'm not sure if this is true or not, but it's the current behavior
testSuggestions('FROM a | LIMIT 1/', ['| ']);
// MV_EXPAND field
testSuggestions('FROM index1 | MV_EXPAND f/', getFieldNamesByType('any'));
// RENAME field
testSuggestions('FROM index1 | RENAME f/', getFieldNamesByType('any'));
// RENAME field AS
testSuggestions('FROM index1 | RENAME field A/', ['AS $0']);
// RENAME field AS var0
testSuggestions('FROM index1 | RENAME field AS v/', ['var0']);
// STATS argument
testSuggestions('FROM index1 | STATS f/', [
'var0 = ',
...getFunctionSignaturesByReturnType('stats', 'any', {
scalar: true,
agg: true,
grouping: true,
}),
]);
// STATS argument BY
testSuggestions('FROM index1 | STATS AVG(booleanField) B/', ['BY ', ', ', '| ']);
// STATS argument BY expression
testSuggestions('FROM index1 | STATS field BY f/', [
'var0 = ',
getDateHistogramCompletionItem(),
...getFunctionSignaturesByReturnType('stats', 'any', { grouping: true, scalar: true }),
...getFieldNamesByType('any').map((field) => `${field} `),
]);
// WHERE argument
testSuggestions('FROM index1 | WHERE f/', [
...getFieldNamesByType('any').map((field) => `${field} `),
...getFunctionSignaturesByReturnType('where', 'any', { scalar: true }),
]);
// WHERE argument comparison
testSuggestions(
'FROM index1 | WHERE keywordField i/',
getFunctionSignaturesByReturnType(
'where',
'boolean',
{
operators: true,
},
undefined,
['and', 'or', 'not']
)
);
// WHERE function <suggest>
testSuggestions(
'FROM index1 | WHERE ABS(integerField) i/',
getFunctionSignaturesByReturnType(
'where',
'any',
{
operators: true,
skipAssign: true,
},
['integer'],
['and', 'or', 'not']
)
);
});
describe('advancing the cursor and opening the suggestion menu automatically ✨', () => {
/**
* NOTE: Monaco uses an Invoke trigger kind when the show suggestions action is triggered (e.g. accepting the "FROM" suggestion)
*/
const attachAsSnippet = (s: PartialSuggestionWithText): PartialSuggestionWithText => ({
...s,
asSnippet: true,
});
let recommendedQuerySuggestions = getRecommendedQueriesSuggestions('FROM logs*', 'dateField');
// Source command
testSuggestions('F/', [
...['FROM $0', 'ROW $0', 'SHOW $0'].map(attachTriggerCommand).map(attachAsSnippet),
...recommendedQuerySuggestions.map((q) => q.queryString),
]);
const commands = commandDefinitions
.filter(({ name }) => !sourceCommands.includes(name))
.map(({ name, types }) => {
if (types && types.length) {
const cmds: string[] = [];
for (const type of types) {
const cmd = type.name.toUpperCase() + ' ' + name.toUpperCase() + ' $0';
cmds.push(cmd);
}
return cmds;
} else {
return name.toUpperCase() + ' $0';
}
})
.flat();
// Pipe command
testSuggestions(
'FROM a | E/',
commands.map((name) => attachTriggerCommand(name)).map(attachAsSnippet) // TODO consider making this check more fundamental
);
describe('function arguments', () => {
// literalSuggestions parameter
const dateDiffFirstParamSuggestions =
scalarFunctionDefinitions.find(({ name }) => name === 'date_diff')?.signatures[0]
.params?.[0].literalSuggestions ?? [];
testSuggestions(
'FROM a | EVAL DATE_DIFF(/)',
dateDiffFirstParamSuggestions.map((s) => `"${s}", `).map(attachTriggerCommand)
);
// field parameter
const expectedStringSuggestionsWhenMoreArgsAreNeeded = [
...getFieldNamesByType(ESQL_STRING_TYPES)
.map((field) => `${field}, `)
.map(attachTriggerCommand),
...getFunctionSignaturesByReturnType(
'eval',
ESQL_STRING_TYPES,
{ scalar: true },
undefined,
['replace']
).map((s) => ({
...s,
text: `${s.text},`,
})),
];
testSuggestions('FROM a | EVAL REPLACE(/)', expectedStringSuggestionsWhenMoreArgsAreNeeded);
// subsequent parameter
testSuggestions(
'FROM a | EVAL REPLACE(keywordField, /)',
expectedStringSuggestionsWhenMoreArgsAreNeeded
);
// final parameter — should not advance!
testSuggestions('FROM a | EVAL REPLACE(keywordField, keywordField, /)', [
...getFieldNamesByType(ESQL_STRING_TYPES).map((field) => ({
text: field,
command: undefined,
})),
...getFunctionSignaturesByReturnType(
'eval',
ESQL_STRING_TYPES,
{ scalar: true },
undefined,
['replace']
),
]);
// Trigger character because this is how it will actually be... the user will press
// space-bar... this may change if we fix the tokenization of timespan literals
// such that "2 days" is a single monaco token
testSuggestions(
'FROM a | EVAL DATE_TRUNC(2 /)',
[...timeUnitsToSuggest.map((s) => `${s.name}, `).map(attachTriggerCommand), ','],
' '
);
});
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('', 'dateField');
// PIPE (|)
testSuggestions('FROM a /', [
attachTriggerCommand('| '),
',',
attachAsSnippet(attachTriggerCommand('METADATA $0')),
...recommendedQuerySuggestions.map((q) => q.queryString),
]);
// Assignment
testSuggestions(`FROM a | ENRICH policy on b with /`, [
attachTriggerCommand('var0 = '),
...getPolicyFields('policy'),
]);
// FROM source
describe('sources', () => {
testSuggestions(
'FROM /',
[
{ text: 'index1', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index2', command: TRIGGER_SUGGESTION_COMMAND },
],
undefined,
[
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]
);
testSuggestions(
'FROM index/',
[
{ text: 'index1', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index2', command: TRIGGER_SUGGESTION_COMMAND },
],
undefined,
[
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]
);
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('index1', 'dateField');
testSuggestions(
'FROM index1/',
[
{ text: 'index1 | ', filterText: 'index1', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index1, ', filterText: 'index1', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index1 METADATA ', filterText: 'index1', command: TRIGGER_SUGGESTION_COMMAND },
...recommendedQuerySuggestions.map((q) => q.queryString),
],
undefined,
[
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]
);
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('index2', 'dateField');
testSuggestions(
'FROM index1, index2/',
[
{ text: 'index2 | ', filterText: 'index2', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index2, ', filterText: 'index2', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'index2 METADATA ', filterText: 'index2', command: TRIGGER_SUGGESTION_COMMAND },
...recommendedQuerySuggestions.map((q) => q.queryString),
],
undefined,
[
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]
);
// This is a source name that contains a special character
// meaning that Monaco by default will only set the replacement
// range to cover "bar" and not "foo$bar". We have to make sure
// we're setting it ourselves.
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('foo$bar', 'dateField');
testSuggestions(
'FROM foo$bar/',
[
{
text: 'foo$bar | ',
filterText: 'foo$bar',
command: TRIGGER_SUGGESTION_COMMAND,
rangeToReplace: { start: 6, end: 13 },
},
{
text: 'foo$bar, ',
filterText: 'foo$bar',
command: TRIGGER_SUGGESTION_COMMAND,
rangeToReplace: { start: 6, end: 13 },
},
{
text: 'foo$bar METADATA ',
filterText: 'foo$bar',
asSnippet: false, // important because the text includes "$"
command: TRIGGER_SUGGESTION_COMMAND,
rangeToReplace: { start: 6, end: 13 },
},
...recommendedQuerySuggestions.map((q) => q.queryString),
],
undefined,
[, [{ name: 'foo$bar', hidden: false }]]
);
// This is an identifier that matches multiple sources
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('i*', 'dateField');
testSuggestions(
'FROM i*/',
[
{ text: 'i* | ', filterText: 'i*', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'i*, ', filterText: 'i*', command: TRIGGER_SUGGESTION_COMMAND },
{ text: 'i* METADATA ', filterText: 'i*', command: TRIGGER_SUGGESTION_COMMAND },
...recommendedQuerySuggestions.map((q) => q.queryString),
],
undefined,
[
,
[
{ name: 'index1', hidden: false },
{ name: 'index2', hidden: false },
],
]
);
});
recommendedQuerySuggestions = getRecommendedQueriesSuggestions('', 'dateField');
// FROM source METADATA
testSuggestions('FROM index1 M/', [attachAsSnippet(attachTriggerCommand('METADATA $0'))]);
describe('ENRICH', () => {
testSuggestions(
'FROM a | ENRICH /',
policies.map((p) => `${getSafeInsertText(p.name)} `).map(attachTriggerCommand)
);
testSuggestions(
'FROM a | ENRICH pol/',
policies
.map((p) => `${getSafeInsertText(p.name)} `)
.map(attachTriggerCommand)
.map((s) => ({ ...s, rangeToReplace: { start: 17, end: 20 } }))
);
testSuggestions('FROM a | ENRICH policy /', ['ON ', 'WITH ', '| '].map(attachTriggerCommand));
testSuggestions(
'FROM a | ENRICH policy ON /',
getFieldNamesByType('any')
.map((name) => `${name} `)
.map(attachTriggerCommand)
);
testSuggestions(
'FROM a | ENRICH policy ON @timestamp /',
['WITH ', '| '].map(attachTriggerCommand)
);
// nothing fancy with this field list
testSuggestions('FROM a | ENRICH policy ON @timestamp WITH /', [
'var0 = ',
...getPolicyFields('policy'),
]);
describe('replacement range', () => {
testSuggestions('FROM a | ENRICH policy ON @timestamp WITH othe/', [
'var0 = ',
...getPolicyFields('policy').map((name) => ({
text: name,
command: undefined,
rangeToReplace: { start: 43, end: 47 },
})),
]);
testSuggestions(
'FROM a | ENRICH policy ON @timestamp WITH var0 = othe/',
getPolicyFields('policy').map((name) => ({
text: name,
command: undefined,
rangeToReplace: { start: 50, end: 54 },
}))
);
});
});
// LIMIT number
testSuggestions('FROM a | LIMIT /', ['10 ', '100 ', '1000 '].map(attachTriggerCommand));
// STATS argument
testSuggestions(
'FROM a | STATS /',
[
'var0 = ',
...getFunctionSignaturesByReturnType('stats', 'any', {
scalar: true,
agg: true,
grouping: true,
}).map(attachAsSnippet),
].map(attachTriggerCommand)
);
// STATS argument BY
testSuggestions('FROM a | STATS AVG(numberField) /', [
', ',
attachTriggerCommand('BY '),
attachTriggerCommand('| '),
]);
// STATS argument BY field
const allByCompatibleFunctions = getFunctionSignaturesByReturnType(
'stats',
'any',
{
scalar: true,
grouping: true,
},
undefined,
undefined,
'by'
);
testSuggestions('FROM a | STATS AVG(numberField) BY /', [
getDateHistogramCompletionItem(),
attachTriggerCommand('var0 = '),
...getFieldNamesByType('any')
.map((field) => `${field} `)
.map(attachTriggerCommand),
...allByCompatibleFunctions,
]);
// STATS argument BY assignment (checking field suggestions)
testSuggestions('FROM a | STATS AVG(numberField) BY var0 = /', [
getDateHistogramCompletionItem(),
...getFieldNamesByType('any')
.map((field) => `${field} `)
.map(attachTriggerCommand),
...allByCompatibleFunctions,
]);
// WHERE argument (field suggestions)
testSuggestions('FROM a | WHERE /', [
...getFieldNamesByType('any')
.map((field) => `${field} `)
.map(attachTriggerCommand),
...getFunctionSignaturesByReturnType('where', 'any', { scalar: true }).map(attachAsSnippet),
]);
// WHERE argument comparison
testSuggestions(
'FROM a | WHERE keywordField /',
getFunctionSignaturesByReturnType(
'where',
'boolean',
{
operators: true,
},
['keyword']
).map((s) => (s.text.toLowerCase().includes('null') ? s : attachTriggerCommand(s)))
);
describe('field lists', () => {
describe('METADATA <field>', () => {
// METADATA field
testSuggestions('FROM a METADATA /', METADATA_FIELDS.map(attachTriggerCommand));
testSuggestions('FROM a METADATA _i/', METADATA_FIELDS.map(attachTriggerCommand));
testSuggestions(
'FROM a METADATA _id/',
[
{ filterText: '_id', text: '_id, ' },
{ filterText: '_id', text: '_id | ' },
].map(attachTriggerCommand)
);
testSuggestions(
'FROM a METADATA _id, /',
METADATA_FIELDS.filter((field) => field !== '_id').map(attachTriggerCommand)
);
testSuggestions(
'FROM a METADATA _id, _ignored/',
[
{ filterText: '_ignored', text: '_ignored, ' },
{ filterText: '_ignored', text: '_ignored | ' },
].map(attachTriggerCommand)
);
// comma if there's even one more field
testSuggestions('FROM a METADATA _id, _ignored, _index, _source/', [
{ filterText: '_source', text: '_source | ', command: TRIGGER_SUGGESTION_COMMAND },
{ filterText: '_source', text: '_source, ', command: TRIGGER_SUGGESTION_COMMAND },
]);
// no comma if there are no more fields
testSuggestions(
'FROM a METADATA _id, _ignored, _index, _source, _index_mode, _score, _version/',
[{ filterText: '_version', text: '_version | ', command: TRIGGER_SUGGESTION_COMMAND }]
);
});
describe.each(['KEEP', 'DROP'])('%s <field>', (commandName) => {
// KEEP field
testSuggestions(
`FROM a | ${commandName} /`,
getFieldNamesByType('any').map(attachTriggerCommand)
);
testSuggestions(
`FROM a | ${commandName} d/`,
getFieldNamesByType('any')
.map<PartialSuggestionWithText>((text) => ({
text,
rangeToReplace: { start: 15, end: 16 },
}))
.map(attachTriggerCommand)
);
testSuggestions(
`FROM a | ${commandName} doubleFiel/`,
getFieldNamesByType('any').map(attachTriggerCommand)
);
testSuggestions(
`FROM a | ${commandName} doubleField/`,
['doubleField, ', 'doubleField | ']
.map((text) => ({
text,
filterText: 'doubleField',
rangeToReplace: { start: 15, end: 26 },
}))
.map(attachTriggerCommand)
);
testSuggestions('FROM a | KEEP doubleField /', ['| ', ',']);
// Let's get funky with the field names
testSuggestions(
`FROM a | ${commandName} @timestamp/`,
['@timestamp, ', '@timestamp | ']
.map((text) => ({
text,
filterText: '@timestamp',
rangeToReplace: { start: 15, end: 25 },
}))
.map(attachTriggerCommand),
undefined,
[
[
{ name: '@timestamp', type: 'date' },
{ name: 'utc_stamp', type: 'date' },
],
]
);
testSuggestions(
`FROM a | ${commandName} foo.bar/`,
['foo.bar, ', 'foo.bar | ']
.map((text) => ({
text,
filterText: 'foo.bar',
rangeToReplace: { start: 15, end: 22 },
}))
.map(attachTriggerCommand),
undefined,
[
[
{ name: 'foo.bar', type: 'double' },
{ name: 'baz', type: 'date' },
],
]
);
describe('escaped field names', () => {
testSuggestions(
`FROM a | ${commandName} \`foo.bar\`/`,
['`foo.bar`, ', '`foo.bar` | '],
undefined,
[
[
{ name: 'foo.bar', type: 'double' },
{ name: 'baz', type: 'date' }, // added so that we get a comma suggestion
],
]
);
testSuggestions(
`FROM a | ${commandName} \`foo\`\`\`\`bar\`\`baz\`/`,
['`foo````bar``baz`, ', '`foo````bar``baz` | '],
undefined,
[
[
{ name: 'foo``bar`baz', type: 'double' },
{ name: 'baz', type: 'date' }, // added so that we get a comma suggestion
],
]
);
testSuggestions(`FROM a | ${commandName} \`any#Char$Field\`/`, [
'`any#Char$Field`, ',
'`any#Char$Field` | ',
]);
// @todo enable this test when we can use AST to support this case
testSuggestions.skip(
`FROM a | ${commandName} \`foo\`.\`bar\`/`,
['`foo`.`bar`, ', '`foo`.`bar` | '],
undefined,
[[{ name: 'foo.bar', type: 'double' }]]
);
});
// Subsequent fields
testSuggestions(
`FROM a | ${commandName} doubleField, dateFiel/`,
getFieldNamesByType('any')
.filter((s) => s !== 'doubleField')
.map(attachTriggerCommand)
);
testSuggestions(`FROM a | ${commandName} doubleField, dateField/`, [
'dateField, ',
'dateField | ',
]);