-
Notifications
You must be signed in to change notification settings - Fork 697
Expand file tree
/
Copy pathtest_completion_engine.py
More file actions
1860 lines (1480 loc) · 64.7 KB
/
Copy pathtest_completion_engine.py
File metadata and controls
1860 lines (1480 loc) · 64.7 KB
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
# type: ignore
from types import SimpleNamespace
import pytest
import sqlparse
from sqlparse import tokens
from sqlparse.sql import Statement, Token
from mycli.packages import completion_engine, special
from mycli.packages.completion_engine import (
DSN_SUBCOMMANDS,
_aliases,
_build_suggest_context,
_charset_suggestion,
_emit_binary_or_comma,
_emit_blank_token,
_emit_character_set,
_emit_collation,
_emit_column_for_tables,
_emit_database,
_emit_lparen,
_emit_none_token,
_emit_nothing,
_emit_on,
_emit_procedure,
_emit_relation_like,
_emit_relation_name,
_emit_select_like,
_emit_show,
_emit_star,
_emit_to,
_emit_user,
_emit_where_token,
_enum_value_suggestion,
_find_doubled_backticks,
_is_single_or_double_quoted,
_is_where_or_having,
_keyword_and_special_suggestions,
_keyword_suggestions,
_normalize_token_value,
_parent_name,
_parse_suggestion_statement,
_tables,
_token_is_binary_or_comma,
_token_is_blank,
_token_is_lparen,
_token_is_none,
_token_is_relation_keyword,
_token_value_is,
_tokens_wo_space,
_word_starts_with_digit_or_dot,
_word_starts_with_quote,
identifies,
is_inside_quotes,
suggest_based_on_last_token,
suggest_special,
suggest_type,
)
def sorted_dicts(dicts):
"""input is a list of dicts."""
return sorted(tuple(x.items()) for x in dicts)
def flattened_tokens(text):
return list(sqlparse.parse(text)[0].flatten())
def value_tokens(*values):
return [SimpleNamespace(value=value) for value in values]
def empty_identifier():
return SimpleNamespace(get_parent_name=lambda: None)
def last_non_whitespace_token(text):
parsed = sqlparse.parse(text)[0]
return parsed.token_prev(len(parsed.tokens) - 1)[1]
def test_select_suggests_cols_with_visible_table_scope():
suggestions = suggest_type("SELECT FROM tabl", "SELECT ")
assert sorted_dicts(suggestions) == sorted_dicts([
{"type": "alias", "aliases": ["tabl"]},
{"type": "column", "tables": [(None, "tabl", None)]},
{"type": "function", "schema": []},
{"type": "introducer"},
])
def test_select_suggests_cols_with_qualified_table_scope():
suggestions = suggest_type("SELECT FROM sch.tabl", "SELECT ")
assert sorted_dicts(suggestions) == sorted_dicts([
{"type": "alias", "aliases": ["tabl"]},
{"type": "column", "tables": [("sch", "tabl", None)]},
{"type": "function", "schema": []},
{"type": "introducer"},
])
@pytest.mark.parametrize(
"expression",
[
"SELECT * FROM tabl WHERE ",
"SELECT * FROM tabl WHERE (",
"SELECT * FROM tabl WHERE bar OR ",
"SELECT * FROM tabl WHERE foo = 1 AND ",
"SELECT * FROM tabl WHERE (bar > 10 AND ",
"SELECT * FROM tabl WHERE (bar AND (baz OR (qux AND (",
"SELECT * FROM tabl WHERE 10 < ",
"SELECT * FROM tabl WHERE foo BETWEEN ",
"SELECT * FROM tabl WHERE foo BETWEEN foo AND ",
],
)
def test_where_suggests_columns_functions(expression):
suggestions = suggest_type(expression, expression)
assert sorted_dicts(suggestions) == sorted_dicts([
{"type": "alias", "aliases": ["tabl"]},
{"type": "column", "tables": [(None, "tabl", None)]},
{"type": "function", "schema": []},
{"type": "introducer"},
])
def test_where_equals_suggests_enum_values_first():
expression = "SELECT * FROM tabl WHERE foo = "
suggestions = suggest_type(expression, expression)
assert sorted_dicts(suggestions) == sorted_dicts([
{"type": "enum_value", "tables": [(None, "tabl", None)], "column": "foo", "parent": None},
{"type": "alias", "aliases": ["tabl"]},
{"type": "column", "tables": [(None, "tabl", None)]},
{"type": "function", "schema": []},
{"type": "introducer"},
])
def test_enum_value_suggestion_returns_none_without_equals_context():
expression = 'SELECT * FROM tabl WHERE foo'
suggestion = _enum_value_suggestion(expression, expression)
assert suggestion is None
def test_enum_value_suggestion_returns_column_and_tables():
expression = 'SELECT * FROM tabl WHERE foo = '
suggestion = _enum_value_suggestion(expression, expression)
assert suggestion == {
'type': 'enum_value',
'tables': [(None, 'tabl', None)],
'column': 'foo',
'parent': None,
}
def test_enum_value_suggestion_handles_qualified_backticked_identifier():
expression = 'SELECT * FROM sch.tabl WHERE `tabl`.`foo` = '
suggestion = _enum_value_suggestion(expression, expression)
assert suggestion == {
'type': 'enum_value',
'tables': [('sch', 'tabl', None)],
'column': '`foo`',
'parent': '`tabl`',
}
def test_enum_value_suggestion_returns_none_inside_quotes():
full_text = 'SELECT * FROM tabl WHERE "foo = '
text_before_cursor = 'SELECT * FROM tabl WHERE "foo = '
suggestion = _enum_value_suggestion(text_before_cursor, full_text)
assert suggestion is None
@pytest.mark.parametrize(
('tokens', 'expected'),
[
(value_tokens('character', 'set'), [{'type': 'character_set'}]),
(value_tokens('x', 'character', 'set', ' '), [{'type': 'character_set'}]),
(value_tokens('collate'), [{'type': 'collation'}]),
(value_tokens('select', 'foo'), None),
],
)
def test_charset_suggestion(tokens, expected):
assert _charset_suggestion(tokens) == expected
def test_keyword_suggestions():
assert _keyword_suggestions() == [{'type': 'keyword'}]
def test_keyword_and_special_suggestions():
assert _keyword_and_special_suggestions() == [{'type': 'keyword'}, {'type': 'special'}]
def test_parse_suggestion_statement_returns_statement_and_nonspace_tokens():
tokens_wo_space = _tokens_wo_space('select 1')
assert [token.value for token in tokens_wo_space] == ['select', '1']
def test_parse_suggestion_statement_raises_type_error_for_invalid_input_type():
with pytest.raises(TypeError):
_parse_suggestion_statement(None) # type: ignore[arg-type]
def test_normalize_token_value_handles_string():
assert _normalize_token_value('SELECT') == 'select'
def test_normalize_token_value_handles_none():
assert _normalize_token_value(None) is None
def test_normalize_token_value_handles_plain_token():
token = SimpleNamespace(value='SHOW')
assert _normalize_token_value(token) == 'show'
def test_normalize_token_value_handles_comparison_token():
comparison = sqlparse.parse('a.id = d.')[0].tokens[0]
assert _normalize_token_value(comparison) == 'd.'
def test_build_suggest_context_populates_fields():
identifier = empty_identifier()
context = _build_suggest_context(
'SHOW',
'show ',
None,
'show ',
identifier,
)
assert context.token == 'SHOW'
assert context.token_value == 'show'
assert context.text_before_cursor == 'show '
assert context.word_before_cursor is None
assert context.full_text == 'show '
assert context.identifier is identifier
assert str(context.parsed_cb()) == 'show '
assert [token.value for token in context.tokens_wo_space_cb()] == ['show']
def test_build_suggest_context_handles_none_token():
context = _build_suggest_context(
None,
'',
None,
'',
empty_identifier(),
)
assert context.token is None
assert context.token_value is None
assert str(context.parsed_cb()) == ''
assert context.tokens_wo_space_cb() == []
@pytest.mark.parametrize(
('text_before_cursor', 'expected'),
[
("select 'foo", True),
('select "foo', True),
('select `foo', False),
('select foo', False),
],
)
def test_is_single_or_double_quoted(text_before_cursor, expected):
context = _build_suggest_context(
None,
text_before_cursor,
None,
text_before_cursor,
empty_identifier(),
)
assert _is_single_or_double_quoted(context) is expected
def test_parent_name_returns_identifier_parent():
identifier = SimpleNamespace(get_parent_name=lambda: 'sch')
context = _build_suggest_context(None, '', None, '', identifier)
assert _parent_name(context) == 'sch'
def test_parent_name_returns_empty_list_without_parent():
context = _build_suggest_context(None, '', None, '', empty_identifier())
assert _parent_name(context) == []
def test_tables_returns_extracted_tables_from_full_text():
full_text = 'SELECT * FROM abc a, sch.def d'
context = _build_suggest_context(None, '', None, full_text, empty_identifier())
assert _tables(context) == [
(None, 'abc', 'a'),
('sch', 'def', 'd'),
]
def test_aliases_prefers_alias_and_falls_back_to_table_name():
tables = [
(None, 'abc', 'a'),
('sch', 'def', ''),
]
assert _aliases(tables) == ['a', 'def']
@pytest.mark.parametrize(
('word_before_cursor', 'expected'),
[
('9foo', True),
('.foo', True),
('foo', False),
(None, False),
],
)
def test_word_starts_with_digit_or_dot(word_before_cursor, expected):
context = _build_suggest_context(
None,
'',
word_before_cursor,
'',
empty_identifier(),
)
assert _word_starts_with_digit_or_dot(context) is expected
@pytest.mark.parametrize(
('word_before_cursor', 'expected'),
[
("'foo", True),
('"foo', True),
('foo', False),
(None, False),
],
)
def test_word_starts_with_quote(word_before_cursor, expected):
context = _build_suggest_context(
None,
'',
word_before_cursor,
'',
empty_identifier(),
)
assert _word_starts_with_quote(context) is expected
def test_token_is_none_true_for_none_token():
context = _build_suggest_context(None, '', None, '', empty_identifier())
assert _token_is_none(context) is True
def test_token_is_none_false_for_non_none_token():
context = _build_suggest_context('select', '', None, '', empty_identifier())
assert _token_is_none(context) is False
@pytest.mark.parametrize(
('token', 'expected'),
[
('', True),
('select', False),
(None, True),
],
)
def test_token_is_blank(token, expected):
context = _build_suggest_context(token, '', None, '', empty_identifier())
assert _token_is_blank(context) is expected
@pytest.mark.parametrize(
('token', 'values', 'expected'),
[
('select', ('select', 'where'), True),
('show', ('select', 'where'), False),
(None, ('select',), False),
],
)
def test_token_value_is(token, values, expected):
context = _build_suggest_context(token, '', None, '', empty_identifier())
assert _token_value_is(context, *values) is expected
@pytest.mark.parametrize(
('token', 'expected'),
[
('(', True),
('any(', True),
('select', False),
(None, False),
],
)
def test_token_is_lparen(token, expected):
context = _build_suggest_context(token, '', None, '', empty_identifier())
assert _token_is_lparen(context) is expected
@pytest.mark.parametrize(
('token', 'text_before_cursor', 'full_text', 'expected'),
[
(last_non_whitespace_token('SELECT * FROM foo JOIN '), 'SELECT * FROM foo JOIN ', 'SELECT * FROM foo JOIN ', True),
('from', 'from ', 'from ', True),
('truncate', 'truncate ', 'truncate ', True),
('like', 'like ', 'create table new like ', True),
('like', 'like ', 'select * from foo like ', False),
('select', 'select ', 'select ', False),
],
)
def test_token_is_relation_keyword(token, text_before_cursor, full_text, expected):
context = _build_suggest_context(token, text_before_cursor, None, full_text, empty_identifier())
assert _token_is_relation_keyword(context) is expected
@pytest.mark.parametrize(
('token', 'expected'),
[
(',', True),
('=', True),
('and', True),
('select', False),
(None, False),
],
)
def test_token_is_binary_or_comma(token, expected):
context = _build_suggest_context(token, '', None, '', empty_identifier())
assert _token_is_binary_or_comma(context) is expected
def test_emit_none_token():
context = _build_suggest_context(None, '', None, '', empty_identifier())
assert _emit_none_token(context) == [{'type': 'keyword'}]
@pytest.mark.parametrize(
('text_before_cursor', 'expected'),
[
('', [{'type': 'keyword'}, {'type': 'special'}]),
('/', [{'type': 'special'}]),
],
)
def test_emit_blank_token(text_before_cursor, expected):
context = _build_suggest_context('', text_before_cursor, None, '', empty_identifier())
assert _emit_blank_token(context) == expected
def test_emit_star():
context = _build_suggest_context('*', '', None, '', empty_identifier())
assert _emit_star(context) == [{'type': 'keyword'}]
def test_emit_lparen_exists_where():
text = 'SELECT * FROM foo WHERE EXISTS ('
context = _build_suggest_context('(', text, None, text, empty_identifier())
assert _emit_lparen(context) == [{'type': 'keyword'}]
def test_emit_lparen_join_using():
text = 'select * from abc inner join def using ('
context = _build_suggest_context('(', text, None, text, empty_identifier())
assert _emit_lparen(context) == [{'type': 'column', 'tables': [(None, 'abc', None), (None, 'def', None)], 'drop_unique': True}]
def test_emit_lparen_show():
text = 'SHOW ('
context = _build_suggest_context('(', text, None, text, empty_identifier())
assert _emit_lparen(context) == [{'type': 'show'}]
def test_emit_lparen_function_argument_list():
text = 'SELECT MAX('
full_text = 'SELECT MAX( FROM tbl'
context = _build_suggest_context('(', text, None, full_text, empty_identifier())
assert _emit_lparen(context) == [{'type': 'column', 'tables': [(None, 'tbl', None)]}]
def test_emit_procedure():
context = _build_suggest_context('call', '', None, '', empty_identifier())
assert _emit_procedure(context) == [{'type': 'procedure', 'schema': []}]
def test_emit_character_set():
context = _build_suggest_context('set', '', None, '', empty_identifier())
assert _emit_character_set(context) == [{'type': 'character_set'}]
def test_emit_column_for_tables():
full_text = 'SELECT * FROM abc a, sch.def d'
context = _build_suggest_context('select', '', None, full_text, empty_identifier())
assert _emit_column_for_tables(context) == [
{
'type': 'column',
'tables': [
(None, 'abc', 'a'),
('sch', 'def', 'd'),
],
}
]
def test_emit_nothing():
context = _build_suggest_context('as', '', None, '', empty_identifier())
assert _emit_nothing(context) == []
def test_emit_show():
context = _build_suggest_context('show', '', None, '', empty_identifier())
assert _emit_show(context) == [{'type': 'show'}]
def test_emit_to_for_change_statement():
text = 'change master to '
context = _build_suggest_context('to', text, None, text, empty_identifier())
assert _emit_to(context) == [{'type': 'change'}]
def test_emit_to_for_non_change_statement():
text = 'grant all on db.* to '
context = _build_suggest_context('to', text, None, text, empty_identifier())
assert _emit_to(context) == [{'type': 'user'}]
def test_emit_user():
context = _build_suggest_context('user', '', None, '', empty_identifier())
assert _emit_user(context) == [{'type': 'user'}]
def test_emit_collation():
context = _build_suggest_context('collate', '', None, '', empty_identifier())
assert _emit_collation(context) == [{'type': 'collation'}]
@pytest.mark.xfail
def test_emit_select_like_with_parent_filters_tables():
identifier = SimpleNamespace(get_parent_name=lambda: 't1')
text = 'SELECT t1.'
full_text = 'SELECT t1. FROM tabl1 t1, tabl2 t2'
context = _build_suggest_context('select', text, None, full_text, identifier)
assert sorted_dicts(_emit_select_like(context)) == sorted_dicts([
{'type': 'column', 'tables': [(None, 'tabl1', 't1')]},
# xfail because these are also currently returned
# {'type': 'table', 'schema': 't1'},
# {'type': 'view', 'schema': 't1'},
# {'type': 'function', 'schema': 't1'},
])
def test_emit_select_like_inside_backticks_adds_keyword():
text = 'SELECT `a'
full_text = 'SELECT `a FROM tabl'
context = _build_suggest_context('select', text, None, full_text, empty_identifier())
assert sorted_dicts(_emit_select_like(context)) == sorted_dicts([
{'type': 'column', 'tables': [(None, 'tabl', None)]},
{'type': 'function', 'schema': []},
{'type': 'alias', 'aliases': ['tabl']},
{'type': 'keyword'},
])
def test_emit_select_like_default():
text = 'SELECT '
full_text = 'SELECT FROM tabl'
context = _build_suggest_context('select', text, None, full_text, empty_identifier())
assert sorted_dicts(_emit_select_like(context)) == sorted_dicts([
{'type': 'column', 'tables': [(None, 'tabl', None)]},
{'type': 'function', 'schema': []},
{'type': 'introducer'},
{'type': 'alias', 'aliases': ['tabl']},
])
def test_emit_relation_like_with_schema_parent():
identifier = SimpleNamespace(get_parent_name=lambda: 'sch')
text = 'INSERT INTO sch.'
context = _build_suggest_context('into', text, None, text, identifier)
assert sorted_dicts(_emit_relation_like(context)) == sorted_dicts([
{'type': 'table', 'schema': 'sch'},
{'type': 'view', 'schema': 'sch'},
])
def test_emit_relation_like_join_adds_database_and_join_flag():
text = 'SELECT * FROM foo JOIN '
token = last_non_whitespace_token(text)
context = _build_suggest_context(token, text, None, text, empty_identifier())
assert sorted_dicts(_emit_relation_like(context)) == sorted_dicts([
{'type': 'database'},
{'type': 'table', 'schema': [], 'join': True},
{'type': 'view', 'schema': []},
])
def test_emit_relation_like_truncate_omits_view():
text = 'TRUNCATE '
context = _build_suggest_context('truncate', text, None, text, empty_identifier())
assert sorted_dicts(_emit_relation_like(context)) == sorted_dicts([
{'type': 'database'},
{'type': 'table', 'schema': []},
])
def test_emit_relation_name_with_schema_parent():
identifier = SimpleNamespace(get_parent_name=lambda: 'sch')
context = _build_suggest_context('table', '', None, '', identifier)
assert _emit_relation_name(context) == [{'type': 'table', 'schema': 'sch'}]
def test_emit_relation_name_without_schema_parent():
context = _build_suggest_context('view', '', None, '', empty_identifier())
assert _emit_relation_name(context) == [{'type': 'schema'}, {'type': 'view', 'schema': []}]
@pytest.mark.xfail
def test_emit_on_with_parent_filters_tables():
identifier = SimpleNamespace(get_parent_name=lambda: 'a')
text = 'SELECT * FROM abc a JOIN def d ON a.'
context = _build_suggest_context('on', text, None, text, identifier)
assert sorted_dicts(_emit_on(context)) == sorted_dicts([
{'type': 'column', 'tables': [(None, 'abc', 'a')]},
# xfail because these currently also are returned
# {'type': 'table', 'schema': 'a'},
# {'type': 'view', 'schema': 'a'},
# {'type': 'function', 'schema': 'a'},
])
def test_emit_on_without_parent_uses_fk_join_and_aliases():
text = 'select a.x, b.y from abc a join bcd b on '
context = _build_suggest_context('on', text, None, text, empty_identifier())
assert _emit_on(context) == [
{'type': 'fk_join', 'tables': [(None, 'abc', 'a'), (None, 'bcd', 'b')]},
{'type': 'alias', 'aliases': ['a', 'b']},
]
def test_emit_on_without_visible_tables_adds_database_and_table():
text = 'grant select on '
context = _build_suggest_context('on', text, None, text, empty_identifier())
assert _emit_on(context) == [
{'type': 'fk_join', 'tables': []},
{'type': 'alias', 'aliases': []},
{'type': 'database'},
{'type': 'table', 'schema': []},
]
def test_emit_database():
context = _build_suggest_context('database', '', None, '', empty_identifier())
assert _emit_database(context) == [{'type': 'database'}]
def test_emit_where_token_returns_charset_suggestion_when_available(monkeypatch):
text = 'select * from tabl where foo = '
where_token = next(token for token in sqlparse.parse(text)[0].tokens if isinstance(token, sqlparse.sql.Where))
context = _build_suggest_context(where_token, text, None, text, empty_identifier())
suggestion = [{'type': 'character_set'}]
monkeypatch.setattr(completion_engine, '_charset_suggestion', lambda _tokens: suggestion)
monkeypatch.setattr(
completion_engine,
'suggest_based_on_last_token',
lambda *_args: pytest.fail('suggest_based_on_last_token should not be called'),
)
assert _emit_where_token(context) == suggestion
def test_emit_where_token_prepends_enum_value_for_where_fallback(monkeypatch):
text = 'select * from tabl where foo = '
where_token = next(token for token in sqlparse.parse(text)[0].tokens if isinstance(token, sqlparse.sql.Where))
context = _build_suggest_context(where_token, text, None, text, empty_identifier())
prev_keyword = SimpleNamespace(value='where')
enum_suggestion = {'type': 'enum_value'}
fallback = [{'type': 'keyword'}]
monkeypatch.setattr(completion_engine, '_charset_suggestion', lambda _tokens: None)
monkeypatch.setattr(completion_engine, 'find_prev_keyword', lambda _text: (prev_keyword, 'select * from tabl where '))
monkeypatch.setattr(completion_engine, '_enum_value_suggestion', lambda _original, _full: enum_suggestion)
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: fallback)
assert _emit_where_token(context) == [enum_suggestion] + fallback
def test_emit_where_token_returns_fallback_for_non_where_keyword(monkeypatch):
text = 'select * from tabl where foo = '
where_token = next(token for token in sqlparse.parse(text)[0].tokens if isinstance(token, sqlparse.sql.Where))
context = _build_suggest_context(where_token, text, None, text, empty_identifier())
fallback = [{'type': 'keyword'}]
monkeypatch.setattr(completion_engine, '_charset_suggestion', lambda _tokens: None)
monkeypatch.setattr(
completion_engine,
'find_prev_keyword',
lambda _text: (SimpleNamespace(value='from'), 'select * from tabl '),
)
monkeypatch.setattr(completion_engine, '_enum_value_suggestion', lambda _original, _full: {'type': 'enum_value'})
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: fallback)
assert _emit_where_token(context) == fallback
def test_emit_where_token_handles_convert_using_with_trailing_partial_name(monkeypatch):
text = 'select * from tabl where convert(foo using utf'
where_token = next(token for token in sqlparse.parse(text)[0].tokens if isinstance(token, sqlparse.sql.Where))
context = _build_suggest_context(where_token, text, None, text, empty_identifier())
monkeypatch.setattr(
completion_engine,
'suggest_based_on_last_token',
lambda *_args: pytest.fail('suggest_based_on_last_token should not be called'),
)
assert _emit_where_token(context) == [{'type': 'character_set'}]
def test_emit_binary_or_comma_prepends_enum_value_for_where_fallback(monkeypatch):
text = 'select * from tabl where foo = '
context = _build_suggest_context('=', text, None, text, empty_identifier())
prev_keyword = SimpleNamespace(value='where')
enum_suggestion = {'type': 'enum_value'}
fallback = [{'type': 'column', 'tables': [(None, 'tabl', None)]}]
monkeypatch.setattr(completion_engine, 'find_prev_keyword', lambda _text: (prev_keyword, 'select * from tabl where '))
monkeypatch.setattr(completion_engine, '_enum_value_suggestion', lambda _original, _full: enum_suggestion)
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: fallback)
assert _emit_binary_or_comma(context) == [enum_suggestion] + fallback
def test_emit_binary_or_comma_uses_keyword_fallback_for_nonprogressing_rewind(monkeypatch):
text = 'select * from tabl where foo = '
context = _build_suggest_context(',', text, None, text, empty_identifier())
prev_keyword = SimpleNamespace(value='where')
fallback = [{'type': 'keyword'}]
monkeypatch.setattr(completion_engine, 'find_prev_keyword', lambda _text: (prev_keyword, text.rstrip()))
monkeypatch.setattr(completion_engine, '_enum_value_suggestion', lambda _original, _full: None)
monkeypatch.setattr(
completion_engine,
'suggest_based_on_last_token',
lambda *_args: pytest.fail('suggest_based_on_last_token should not be called'),
)
monkeypatch.setattr(completion_engine, '_keyword_suggestions', lambda: fallback)
assert _emit_binary_or_comma(context) == fallback
def test_emit_binary_or_comma_returns_rewound_fallback_without_where_enum(monkeypatch):
text = 'select * from tabl and '
context = _build_suggest_context('and', text, None, text, empty_identifier())
fallback = [{'type': 'keyword'}]
monkeypatch.setattr(
completion_engine,
'find_prev_keyword',
lambda _text: (SimpleNamespace(value='from'), 'select * from '),
)
monkeypatch.setattr(completion_engine, '_enum_value_suggestion', lambda _original, _full: {'type': 'enum_value'})
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: fallback)
assert _emit_binary_or_comma(context) == fallback
@pytest.mark.parametrize(
('token', 'expected'),
[
(None, False),
(SimpleNamespace(value='where'), True),
(SimpleNamespace(value='HAVING'), True),
(SimpleNamespace(value='from'), False),
(SimpleNamespace(value=''), False),
],
)
def test_is_where_or_having(token, expected):
assert _is_where_or_having(token) is expected
@pytest.mark.parametrize('exc_type', [TypeError, AttributeError])
def test_suggest_type_returns_keyword_suggestions_when_sqlparse_parse_errors(monkeypatch, exc_type):
monkeypatch.setattr(completion_engine.sqlparse, 'parse', lambda _text: (_ for _ in ()).throw(exc_type()))
assert suggest_type('select 1', 'select 1') == [{'type': 'keyword'}]
@pytest.mark.parametrize('exc_type', [TypeError, AttributeError])
def test_suggest_type_returns_keyword_suggestions_when_word_parse_errors(monkeypatch, exc_type):
parse_inputs: list[str] = []
original_parse = sqlparse.parse
def fake_parse(text: str):
parse_inputs.append(text)
if len(parse_inputs) == 1:
return [original_parse('select ')[0]]
raise exc_type()
monkeypatch.setattr(completion_engine.sqlparse, 'parse', fake_parse)
assert suggest_type('select foo', 'select foo') == [{'type': 'keyword'}]
assert parse_inputs == ['select ', 'foo']
def test_suggest_type_dispatches_backslash_commands_to_suggest_special(monkeypatch):
parse_inputs: list[str] = []
special_inputs: list[str] = []
original_parse = sqlparse.parse
def fake_parse(text: str):
parse_inputs.append(text)
return [original_parse('\\dt ')[0]]
monkeypatch.setattr(completion_engine.sqlparse, 'parse', fake_parse)
monkeypatch.setattr(
completion_engine,
'suggest_special',
lambda text: special_inputs.append(text) or [{'type': 'special'}],
)
monkeypatch.setattr(
completion_engine,
'suggest_based_on_last_token',
lambda *_args: [{'type': 'keyword'}],
)
suggestions = suggest_type('\\dt', '\\dt')
assert parse_inputs == ['\\dt']
assert special_inputs == ['\\dt']
assert suggestions == [{'type': 'special'}]
def test_suggest_type_handles_whitespace_only_statement(monkeypatch):
whitespace_statement = Statement([Token(tokens.Text.Whitespace, ' ')])
monkeypatch.setattr(completion_engine.sqlparse, 'parse', lambda _text: [whitespace_statement])
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: [{'type': 'fallback'}])
assert suggest_type(' ', ' ') == [{'type': 'fallback'}]
def test_suggest_type_handles_parser_results_shorter_than_cursor(monkeypatch):
statements = [
Statement([Token(tokens.Keyword, 'SELECT')]),
Statement([Token(tokens.Keyword, 'SELECT')]),
]
monkeypatch.setattr(completion_engine.sqlparse, 'parse', lambda _text: statements)
monkeypatch.setattr(completion_engine, 'suggest_based_on_last_token', lambda *_args: [{'type': 'fallback'}])
assert suggest_type('long cursor text', 'long cursor text') == [{'type': 'fallback'}]
@pytest.mark.parametrize(
('text', 'expected'),
[
('\\', [{'type': 'special'}]),
('use ', [{'type': 'database'}]),
('connect ', [{'type': 'database'}]),
('\\u ', [{'type': 'database'}]),
('\\r ', [{'type': 'database'}]),
('tableformat ', [{'type': 'table_format'}]),
('redirectformat ', [{'type': 'table_format'}]),
('\\T ', [{'type': 'table_format'}]),
('\\Tr ', [{'type': 'table_format'}]),
('\\f ', [{'type': 'favoritequery'}]),
('\\fs ', [{'type': 'favoritequery'}]),
('\\fd ', [{'type': 'favoritequery'}]),
('/f report', [{'type': 'favoritequery'}]),
('/f report ', [{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': set()}]),
('\\f report --u', [{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': set()}]),
('/f report -', [{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': set()}]),
('/f report --', [{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': set()}]),
('/f report -- ', []),
('/f report positional', []),
('/f report positional ', [{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': set()}]),
('/f report --user=', []),
(
'/f report --user=henry ',
[{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': {'user'}}],
),
('/f report --user ', []),
('/f report --user henry', []),
(
'/f report --user henry ',
[{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': {'user'}}],
),
(
'/f report --start-date 2026-08-01 ',
[{'type': 'favoritequery_template_key', 'name': 'report', 'used_keys': {'start-date'}}],
),
('/f report -- --user', []),
('/f report --user="henry', []),
('\\dt ', [{'type': 'table', 'schema': []}, {'type': 'view', 'schema': []}, {'type': 'schema'}]),
('\\dt+ ', [{'type': 'table', 'schema': []}, {'type': 'view', 'schema': []}, {'type': 'schema'}]),
('\\. ', [{'type': 'file_name'}]),
('source ', [{'type': 'file_name'}]),
('\\o ', [{'type': 'file_name'}]),
('\\once ', [{'type': 'file_name'}]),
('tee ', [{'type': 'file_name'}]),
('\\e ', [{'type': 'file_name'}]),
('\\edit ', [{'type': 'file_name'}]),
('\\llm ', [{'type': 'llm'}]),
('\\ai ', [{'type': 'llm'}]),
('/dsn ', [{'type': 'special_subcommand', 'subcommands': list(DSN_SUBCOMMANDS)}]),
('/dsn delete ', [{'type': 'dsn_alias'}]),
('/dsn delete pro', [{'type': 'dsn_alias'}]),
('/dsn delete prod ', []),
('/dsn show', []),
('/dsn show ', [{'type': 'special_subcommand', 'subcommands': ['--more']}]),
('/dsn show --m', [{'type': 'special_subcommand', 'subcommands': ['--more']}]),
('/dsn show --more', []),
('/dsn show --more ', []),
('/dsn list', []),
('/dsn list ', []),
('/dsn list --m', []),
('/dsn list --more', []),
('/dsn list --more ', []),
('/dsn save ', [{'type': 'special_subcommand', 'subcommands': ['--more']}]),
('/dsn save --m', [{'type': 'special_subcommand', 'subcommands': ['--more']}]),
('/dsn save --more', []),
('/dsn save --more ', []),
('/dsn save --more prod', []),
('/dsn save prod', []),
('/dsn save prod ', []),
('/dsn help ', []),
('/help ', [{'type': 'keyword'}, {'type': 'special'}]),
('/pager ', []),
],
)
def test_suggest_special(text, expected):
assert suggest_special(text) == expected
@pytest.mark.parametrize(
('token', 'text_before_cursor', 'word_before_cursor', 'full_text', 'expected'),
[
(None, '', None, '', [{'type': 'keyword'}]),
('', '', None, '', [{'type': 'keyword'}, {'type': 'special'}]),
('*', 'select *', None, 'select *', [{'type': 'keyword'}]),
('as', 'select 1 as ', None, 'select 1 as ', []),
('show', 'show ', None, 'show ', [{'type': 'show'}]),
('to', 'grant all on db.* to ', None, 'grant all on db.* to ', [{'type': 'user'}]),
('to', 'change master to ', None, 'change master to ', [{'type': 'change'}]),
('where', 'select * from tabl where ', '9', 'select * from tabl where ', []),
('where', 'select * from tabl where "fo', '"fo', 'select * from tabl where "fo', []),
('where', "select * from tabl where 'fo", 'fo', "select * from tabl where 'fo", []),
],
)
def test_suggest_based_on_last_token(token, text_before_cursor, word_before_cursor, full_text, expected):
suggestion = suggest_based_on_last_token(
token,
text_before_cursor,
word_before_cursor,
full_text,
empty_identifier(),
)
assert suggestion == expected
def test_suggest_based_on_last_token_lparen_in_exists_where_suggests_keyword():
text = 'SELECT * FROM foo WHERE EXISTS ('
suggestion = suggest_based_on_last_token('(', text, None, text, empty_identifier())
assert suggestion == [{'type': 'keyword'}]
def test_suggest_based_on_last_token_lparen_in_where_any_suggests_columns_functions():
text = 'SELECT * FROM tabl WHERE foo = ANY('
suggestion = suggest_based_on_last_token('(', text, None, text, empty_identifier())
assert sorted_dicts(suggestion) == sorted_dicts([
{'type': 'alias', 'aliases': ['tabl']},
{'type': 'column', 'tables': [(None, 'tabl', None)]},
{'type': 'function', 'schema': []},
{'type': 'introducer'},
])
def test_suggest_based_on_last_token_lparen_after_join_using_suggests_common_columns():
text = 'select * from abc inner join def using ('
suggestion = suggest_based_on_last_token('(', text, None, text, empty_identifier())
assert suggestion == [{'type': 'column', 'tables': [(None, 'abc', None), (None, 'def', None)], 'drop_unique': True}]
def test_suggest_based_on_last_token_lparen_after_select_subquery_suggests_keyword():
text = 'SELECT * FROM ('
suggestion = suggest_based_on_last_token('(', text, None, text, empty_identifier())
assert suggestion == [{'type': 'keyword'}]
def test_suggest_based_on_last_token_lparen_after_show_suggests_show_items():
text = 'SHOW ('
suggestion = suggest_based_on_last_token('(', text, None, text, empty_identifier())
assert suggestion == [{'type': 'show'}]
def test_suggest_based_on_last_token_lparen_in_function_call_suggests_columns():
text = 'SELECT MAX('
full_text = 'SELECT MAX( FROM tbl'
suggestion = suggest_based_on_last_token('(', text, None, full_text, empty_identifier())
assert suggestion == [{'type': 'column', 'tables': [(None, 'tbl', None)]}]
@pytest.mark.parametrize(
('token', 'text_before_cursor', 'full_text', 'expected'),
[
('call', 'call ', 'call ', [{'type': 'procedure', 'schema': []}]),
('set', 'character set', 'character set', [{'type': 'character_set'}]),