-
Notifications
You must be signed in to change notification settings - Fork 48
/
ast_test.go
2020 lines (1857 loc) · 69.8 KB
/
ast_test.go
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
package influxql_test
import (
"fmt"
"go/importer"
"math"
"math/rand"
"reflect"
"strings"
"testing"
"time"
"github.com/influxdata/influxql"
)
func BenchmarkQuery_String(b *testing.B) {
p := influxql.NewParser(strings.NewReader(`SELECT foo AS zoo, a AS b FROM bar WHERE value > 10 AND q = 'hello'`))
q, _ := p.ParseStatement()
for i := 0; i < b.N; i++ {
_ = q.String()
}
}
// Ensure a value's data type can be retrieved.
func TestInspectDataType(t *testing.T) {
for i, tt := range []struct {
v interface{}
typ influxql.DataType
}{
{float64(100), influxql.Float},
{int64(100), influxql.Integer},
{int32(100), influxql.Integer},
{100, influxql.Integer},
{true, influxql.Boolean},
{"string", influxql.String},
{time.Now(), influxql.Time},
{time.Second, influxql.Duration},
{nil, influxql.Unknown},
} {
if typ := influxql.InspectDataType(tt.v); tt.typ != typ {
t.Errorf("%d. %v (%s): unexpected type: %s", i, tt.v, tt.typ, typ)
continue
}
}
}
func TestDataTypeFromString(t *testing.T) {
for i, tt := range []struct {
s string
typ influxql.DataType
}{
{s: "float", typ: influxql.Float},
{s: "integer", typ: influxql.Integer},
{s: "unsigned", typ: influxql.Unsigned},
{s: "string", typ: influxql.String},
{s: "boolean", typ: influxql.Boolean},
{s: "time", typ: influxql.Time},
{s: "duration", typ: influxql.Duration},
{s: "tag", typ: influxql.Tag},
{s: "field", typ: influxql.AnyField},
{s: "foobar", typ: influxql.Unknown},
} {
if typ := influxql.DataTypeFromString(tt.s); tt.typ != typ {
t.Errorf("%d. %s: unexpected type: %s != %s", i, tt.s, tt.typ, typ)
}
}
}
func TestDataType_String(t *testing.T) {
for i, tt := range []struct {
typ influxql.DataType
v string
}{
{influxql.Float, "float"},
{influxql.Integer, "integer"},
{influxql.Boolean, "boolean"},
{influxql.String, "string"},
{influxql.Time, "time"},
{influxql.Duration, "duration"},
{influxql.Tag, "tag"},
{influxql.Unknown, "unknown"},
} {
if v := tt.typ.String(); tt.v != v {
t.Errorf("%d. %v (%s): unexpected string: %s", i, tt.typ, tt.v, v)
}
}
}
func TestDataType_LessThan(t *testing.T) {
for i, tt := range []struct {
typ influxql.DataType
other influxql.DataType
exp bool
}{
{typ: influxql.Unknown, other: influxql.Unknown, exp: true},
{typ: influxql.Unknown, other: influxql.Float, exp: true},
{typ: influxql.Unknown, other: influxql.Integer, exp: true},
{typ: influxql.Unknown, other: influxql.Unsigned, exp: true},
{typ: influxql.Unknown, other: influxql.String, exp: true},
{typ: influxql.Unknown, other: influxql.Boolean, exp: true},
{typ: influxql.Unknown, other: influxql.Tag, exp: true},
{typ: influxql.Float, other: influxql.Unknown, exp: false},
{typ: influxql.Integer, other: influxql.Unknown, exp: false},
{typ: influxql.Unsigned, other: influxql.Unknown, exp: false},
{typ: influxql.String, other: influxql.Unknown, exp: false},
{typ: influxql.Boolean, other: influxql.Unknown, exp: false},
{typ: influxql.Tag, other: influxql.Unknown, exp: false},
{typ: influxql.Float, other: influxql.Float, exp: false},
{typ: influxql.Float, other: influxql.Integer, exp: false},
{typ: influxql.Float, other: influxql.Unsigned, exp: false},
{typ: influxql.Float, other: influxql.String, exp: false},
{typ: influxql.Float, other: influxql.Boolean, exp: false},
{typ: influxql.Float, other: influxql.Tag, exp: false},
{typ: influxql.Integer, other: influxql.Float, exp: true},
{typ: influxql.Integer, other: influxql.Integer, exp: false},
{typ: influxql.Integer, other: influxql.Unsigned, exp: false},
{typ: influxql.Integer, other: influxql.String, exp: false},
{typ: influxql.Integer, other: influxql.Boolean, exp: false},
{typ: influxql.Integer, other: influxql.Tag, exp: false},
{typ: influxql.Unsigned, other: influxql.Float, exp: true},
{typ: influxql.Unsigned, other: influxql.Integer, exp: true},
{typ: influxql.Unsigned, other: influxql.Unsigned, exp: false},
{typ: influxql.Unsigned, other: influxql.String, exp: false},
{typ: influxql.Unsigned, other: influxql.Boolean, exp: false},
{typ: influxql.Unsigned, other: influxql.Tag, exp: false},
{typ: influxql.String, other: influxql.Float, exp: true},
{typ: influxql.String, other: influxql.Integer, exp: true},
{typ: influxql.String, other: influxql.Unsigned, exp: true},
{typ: influxql.String, other: influxql.String, exp: false},
{typ: influxql.String, other: influxql.Boolean, exp: false},
{typ: influxql.String, other: influxql.Tag, exp: false},
{typ: influxql.Boolean, other: influxql.Float, exp: true},
{typ: influxql.Boolean, other: influxql.Integer, exp: true},
{typ: influxql.Boolean, other: influxql.Unsigned, exp: true},
{typ: influxql.Boolean, other: influxql.String, exp: true},
{typ: influxql.Boolean, other: influxql.Boolean, exp: false},
{typ: influxql.Boolean, other: influxql.Tag, exp: false},
{typ: influxql.Tag, other: influxql.Float, exp: true},
{typ: influxql.Tag, other: influxql.Integer, exp: true},
{typ: influxql.Tag, other: influxql.Unsigned, exp: true},
{typ: influxql.Tag, other: influxql.String, exp: true},
{typ: influxql.Tag, other: influxql.Boolean, exp: true},
{typ: influxql.Tag, other: influxql.Tag, exp: false},
} {
if got, exp := tt.typ.LessThan(tt.other), tt.exp; got != exp {
t.Errorf("%d. %q.LessThan(%q) = %v; exp = %v", i, tt.typ, tt.other, got, exp)
}
}
}
// Ensure the SELECT statement can extract GROUP BY interval.
func TestSelectStatement_GroupByInterval(t *testing.T) {
q := "SELECT sum(value) from foo where time < now() GROUP BY time(10m)"
stmt, err := influxql.NewParser(strings.NewReader(q)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", stmt, err)
}
s := stmt.(*influxql.SelectStatement)
d, err := s.GroupByInterval()
if d != 10*time.Minute {
t.Fatalf("group by interval not equal:\nexp=%s\ngot=%s", 10*time.Minute, d)
}
if err != nil {
t.Fatalf("error parsing group by interval: %s", err.Error())
}
}
// Ensure the SELECT statement can have its start and end time set
func TestSelectStatement_SetTimeRange(t *testing.T) {
q := "SELECT sum(value) from foo where time < now() GROUP BY time(10m)"
stmt, err := influxql.NewParser(strings.NewReader(q)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", stmt, err)
}
s := stmt.(*influxql.SelectStatement)
start := time.Now().Add(-20 * time.Hour).Round(time.Second).UTC()
end := time.Now().Add(10 * time.Hour).Round(time.Second).UTC()
s.SetTimeRange(start, end)
min, max := MustTimeRange(s.Condition)
if min != start {
t.Fatalf("start time wasn't set properly.\n exp: %s\n got: %s", start, min)
}
// the end range is actually one nanosecond before the given one since end is exclusive
end = end.Add(-time.Nanosecond)
if max != end {
t.Fatalf("end time wasn't set properly.\n exp: %s\n got: %s", end, max)
}
// ensure we can set a time on a select that already has one set
start = time.Now().Add(-20 * time.Hour).Round(time.Second).UTC()
end = time.Now().Add(10 * time.Hour).Round(time.Second).UTC()
q = fmt.Sprintf("SELECT sum(value) from foo WHERE time >= %ds and time <= %ds GROUP BY time(10m)", start.Unix(), end.Unix())
stmt, err = influxql.NewParser(strings.NewReader(q)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", stmt, err)
}
s = stmt.(*influxql.SelectStatement)
min, max = MustTimeRange(s.Condition)
if start != min || end != max {
t.Fatalf("start and end times weren't equal:\n exp: %s\n got: %s\n exp: %s\n got:%s\n", start, min, end, max)
}
// update and ensure it saves it
start = time.Now().Add(-40 * time.Hour).Round(time.Second).UTC()
end = time.Now().Add(20 * time.Hour).Round(time.Second).UTC()
s.SetTimeRange(start, end)
min, max = MustTimeRange(s.Condition)
// TODO: right now the SetTimeRange can't override the start time if it's more recent than what they're trying to set it to.
// shouldn't matter for our purposes with continuous queries, but fix this later
if min != start {
t.Fatalf("start time wasn't set properly.\n exp: %s\n got: %s", start, min)
}
// the end range is actually one nanosecond before the given one since end is exclusive
end = end.Add(-time.Nanosecond)
if max != end {
t.Fatalf("end time wasn't set properly.\n exp: %s\n got: %s", end, max)
}
// ensure that when we set a time range other where clause conditions are still there
q = "SELECT sum(value) from foo WHERE foo = 'bar' and time < now() GROUP BY time(10m)"
stmt, err = influxql.NewParser(strings.NewReader(q)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", stmt, err)
}
s = stmt.(*influxql.SelectStatement)
// update and ensure it saves it
start = time.Now().Add(-40 * time.Hour).Round(time.Second).UTC()
end = time.Now().Add(20 * time.Hour).Round(time.Second).UTC()
s.SetTimeRange(start, end)
min, max = MustTimeRange(s.Condition)
if min != start {
t.Fatalf("start time wasn't set properly.\n exp: %s\n got: %s", start, min)
}
// the end range is actually one nanosecond before the given one since end is exclusive
end = end.Add(-time.Nanosecond)
if max != end {
t.Fatalf("end time wasn't set properly.\n exp: %s\n got: %s", end, max)
}
// ensure the where clause is there
hasWhere := false
influxql.WalkFunc(s.Condition, func(n influxql.Node) {
if ex, ok := n.(*influxql.BinaryExpr); ok {
if lhs, ok := ex.LHS.(*influxql.VarRef); ok {
if lhs.Val == "foo" {
if rhs, ok := ex.RHS.(*influxql.StringLiteral); ok {
if rhs.Val == "bar" {
hasWhere = true
}
}
}
}
}
})
if !hasWhere {
t.Fatal("set time range cleared out the where clause")
}
}
func TestSelectStatement_HasWildcard(t *testing.T) {
var tests = []struct {
stmt string
wildcard bool
}{
// No wildcards
{
stmt: `SELECT value FROM cpu`,
wildcard: false,
},
// Query wildcard
{
stmt: `SELECT * FROM cpu`,
wildcard: true,
},
// No GROUP BY wildcards
{
stmt: `SELECT value FROM cpu GROUP BY host`,
wildcard: false,
},
// No GROUP BY wildcards, time only
{
stmt: `SELECT mean(value) FROM cpu where time < now() GROUP BY time(5ms)`,
wildcard: false,
},
// GROUP BY wildcard
{
stmt: `SELECT value FROM cpu GROUP BY *`,
wildcard: true,
},
// GROUP BY wildcard with time
{
stmt: `SELECT mean(value) FROM cpu where time < now() GROUP BY *,time(1m)`,
wildcard: true,
},
// GROUP BY wildcard with explicit
{
stmt: `SELECT value FROM cpu GROUP BY *,host`,
wildcard: true,
},
// GROUP BY multiple wildcards
{
stmt: `SELECT value FROM cpu GROUP BY *,*`,
wildcard: true,
},
// Combo
{
stmt: `SELECT * FROM cpu GROUP BY *`,
wildcard: true,
},
}
for i, tt := range tests {
// Parse statement.
stmt, err := influxql.NewParser(strings.NewReader(tt.stmt)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", tt.stmt, err)
}
// Test wildcard detection.
if w := stmt.(*influxql.SelectStatement).HasWildcard(); tt.wildcard != w {
t.Errorf("%d. %q: unexpected wildcard detection:\n\nexp=%v\n\ngot=%v\n\n", i, tt.stmt, tt.wildcard, w)
continue
}
}
}
// Test SELECT statement field rewrite.
func TestSelectStatement_RewriteFields(t *testing.T) {
var tests = []struct {
stmt string
rewrite string
err string
}{
// No wildcards
{
stmt: `SELECT value FROM cpu`,
rewrite: `SELECT value FROM cpu`,
},
// Query wildcard
{
stmt: `SELECT * FROM cpu`,
rewrite: `SELECT host::tag, region::tag, value1::float, value2::integer FROM cpu`,
},
// Parser fundamentally prohibits multiple query sources
// Query wildcard with explicit
{
stmt: `SELECT *,value1 FROM cpu`,
rewrite: `SELECT host::tag, region::tag, value1::float, value2::integer, value1::float FROM cpu`,
},
// Query multiple wildcards
{
stmt: `SELECT *,* FROM cpu`,
rewrite: `SELECT host::tag, region::tag, value1::float, value2::integer, host::tag, region::tag, value1::float, value2::integer FROM cpu`,
},
// Query wildcards with group by
{
stmt: `SELECT * FROM cpu GROUP BY host`,
rewrite: `SELECT region::tag, value1::float, value2::integer FROM cpu GROUP BY host`,
},
// No GROUP BY wildcards
{
stmt: `SELECT value FROM cpu GROUP BY host`,
rewrite: `SELECT value FROM cpu GROUP BY host`,
},
// No GROUP BY wildcards, time only
{
stmt: `SELECT mean(value) FROM cpu where time < now() GROUP BY time(5ms)`,
rewrite: `SELECT mean(value) FROM cpu WHERE time < now() GROUP BY time(5ms)`,
},
// GROUP BY wildcard
{
stmt: `SELECT value FROM cpu GROUP BY *`,
rewrite: `SELECT value FROM cpu GROUP BY host, region`,
},
// GROUP BY wildcard with time
{
stmt: `SELECT mean(value) FROM cpu where time < now() GROUP BY *,time(1m)`,
rewrite: `SELECT mean(value) FROM cpu WHERE time < now() GROUP BY host, region, time(1m)`,
},
// GROUP BY wildcard with fill
{
stmt: `SELECT mean(value) FROM cpu where time < now() GROUP BY *,time(1m) fill(0)`,
rewrite: `SELECT mean(value) FROM cpu WHERE time < now() GROUP BY host, region, time(1m) fill(0)`,
},
// GROUP BY wildcard with explicit
{
stmt: `SELECT value FROM cpu GROUP BY *,host`,
rewrite: `SELECT value FROM cpu GROUP BY host, region, host`,
},
// GROUP BY multiple wildcards
{
stmt: `SELECT value FROM cpu GROUP BY *,*`,
rewrite: `SELECT value FROM cpu GROUP BY host, region, host, region`,
},
// Combo
{
stmt: `SELECT * FROM cpu GROUP BY *`,
rewrite: `SELECT value1::float, value2::integer FROM cpu GROUP BY host, region`,
},
// Wildcard function with all fields.
{
stmt: `SELECT mean(*) FROM cpu`,
rewrite: `SELECT mean(value1::float) AS mean_value1, mean(value2::integer) AS mean_value2 FROM cpu`,
},
{
stmt: `SELECT distinct(*) FROM strings`,
rewrite: `SELECT distinct(string::string) AS distinct_string, distinct(value::float) AS distinct_value FROM strings`,
},
{
stmt: `SELECT distinct(*) FROM bools`,
rewrite: `SELECT distinct(bool::boolean) AS distinct_bool, distinct(value::float) AS distinct_value FROM bools`,
},
// Wildcard function with some fields excluded.
{
stmt: `SELECT mean(*) FROM strings`,
rewrite: `SELECT mean(value::float) AS mean_value FROM strings`,
},
{
stmt: `SELECT mean(*) FROM bools`,
rewrite: `SELECT mean(value::float) AS mean_value FROM bools`,
},
// Wildcard function with an alias.
{
stmt: `SELECT mean(*) AS alias FROM cpu`,
rewrite: `SELECT mean(value1::float) AS alias_value1, mean(value2::integer) AS alias_value2 FROM cpu`,
},
// Query regex
{
stmt: `SELECT /1/ FROM cpu`,
rewrite: `SELECT value1::float FROM cpu`,
},
{
stmt: `SELECT value1 FROM cpu GROUP BY /h/`,
rewrite: `SELECT value1::float FROM cpu GROUP BY host`,
},
// Query regex
{
stmt: `SELECT mean(/1/) FROM cpu`,
rewrite: `SELECT mean(value1::float) AS mean_value1 FROM cpu`,
},
// Rewrite subquery
{
stmt: `SELECT * FROM (SELECT mean(value1) FROM cpu GROUP BY host) GROUP BY *`,
rewrite: `SELECT mean::float FROM (SELECT mean(value1::float) FROM cpu GROUP BY host) GROUP BY host`,
},
// Invalid queries that can't be rewritten should return an error (to
// avoid a panic in the query engine)
{
stmt: `SELECT count(*) / 2 FROM cpu`,
err: `unsupported expression with wildcard: count(*) / 2`,
},
{
stmt: `SELECT * / 2 FROM (SELECT count(*) FROM cpu)`,
err: `unsupported expression with wildcard: * / 2`,
},
{
stmt: `SELECT count(/value/) / 2 FROM cpu`,
err: `unsupported expression with regex field: count(/value/) / 2`,
},
// This one should be possible though since there's no wildcard in the
// binary expression.
{
stmt: `SELECT value1 + value2, * FROM cpu`,
rewrite: `SELECT value1::float + value2::integer, host::tag, region::tag, value1::float, value2::integer FROM cpu`,
},
{
stmt: `SELECT value1 + value2, /value/ FROM cpu`,
rewrite: `SELECT value1::float + value2::integer, value1::float, value2::integer FROM cpu`,
},
}
for i, tt := range tests {
// Parse statement.
stmt, err := influxql.NewParser(strings.NewReader(tt.stmt)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", tt.stmt, err)
}
var mapper FieldMapper
mapper.FieldDimensionsFn = func(m *influxql.Measurement) (fields map[string]influxql.DataType, dimensions map[string]struct{}, err error) {
switch m.Name {
case "cpu":
fields = map[string]influxql.DataType{
"value1": influxql.Float,
"value2": influxql.Integer,
}
case "strings":
fields = map[string]influxql.DataType{
"value": influxql.Float,
"string": influxql.String,
}
case "bools":
fields = map[string]influxql.DataType{
"value": influxql.Float,
"bool": influxql.Boolean,
}
}
dimensions = map[string]struct{}{"host": struct{}{}, "region": struct{}{}}
return
}
// Rewrite statement.
rw, err := stmt.(*influxql.SelectStatement).RewriteFields(&mapper)
if tt.err != "" {
if err != nil && err.Error() != tt.err {
t.Errorf("%d. %q: unexpected error: %s != %s", i, tt.stmt, err.Error(), tt.err)
} else if err == nil {
t.Errorf("%d. %q: expected error", i, tt.stmt)
}
} else {
if err != nil {
t.Errorf("%d. %q: error: %s", i, tt.stmt, err)
} else if rw == nil && tt.err == "" {
t.Errorf("%d. %q: unexpected nil statement", i, tt.stmt)
} else if rw := rw.String(); tt.rewrite != rw {
t.Errorf("%d. %q: unexpected rewrite:\n\nexp=%s\n\ngot=%s\n\n", i, tt.stmt, tt.rewrite, rw)
}
}
}
}
// Test SELECT statement regex conditions rewrite.
func TestSelectStatement_RewriteRegexConditions(t *testing.T) {
var tests = []struct {
in string
out string
}{
{in: `SELECT value FROM cpu`, out: `SELECT value FROM cpu`},
{in: `SELECT value FROM cpu WHERE host = 'server-1'`, out: `SELECT value FROM cpu WHERE host = 'server-1'`},
{in: `SELECT value FROM cpu WHERE host = 'server-1'`, out: `SELECT value FROM cpu WHERE host = 'server-1'`},
{in: `SELECT value FROM cpu WHERE host != 'server-1'`, out: `SELECT value FROM cpu WHERE host != 'server-1'`},
// Non matching regex
{in: `SELECT value FROM cpu WHERE host =~ /server-1|server-2|server-3/`, out: `SELECT value FROM cpu WHERE host =~ /server-1|server-2|server-3/`},
{in: `SELECT value FROM cpu WHERE host =~ /server-1/`, out: `SELECT value FROM cpu WHERE host =~ /server-1/`},
{in: `SELECT value FROM cpu WHERE host !~ /server-1/`, out: `SELECT value FROM cpu WHERE host !~ /server-1/`},
{in: `SELECT value FROM cpu WHERE host =~ /^server-1/`, out: `SELECT value FROM cpu WHERE host =~ /^server-1/`},
{in: `SELECT value FROM cpu WHERE host =~ /server-1$/`, out: `SELECT value FROM cpu WHERE host =~ /server-1$/`},
{in: `SELECT value FROM cpu WHERE host !~ /\^server-1$/`, out: `SELECT value FROM cpu WHERE host !~ /\^server-1$/`},
{in: `SELECT value FROM cpu WHERE host !~ /\^$/`, out: `SELECT value FROM cpu WHERE host !~ /\^$/`},
{in: `SELECT value FROM cpu WHERE host !~ /^server-1\$/`, out: `SELECT value FROM cpu WHERE host !~ /^server-1\$/`},
{in: `SELECT value FROM cpu WHERE host =~ /^\$/`, out: `SELECT value FROM cpu WHERE host =~ /^\$/`},
{in: `SELECT value FROM cpu WHERE host !~ /^a/`, out: `SELECT value FROM cpu WHERE host !~ /^a/`},
// These regexes are not supported due to the presence of escaped or meta characters.
{in: `SELECT value FROM cpu WHERE host !~ /^?a$/`, out: `SELECT value FROM cpu WHERE host !~ /^?a$/`},
{in: `SELECT value FROM cpu WHERE host !~ /^a*$/`, out: `SELECT value FROM cpu WHERE host !~ /^a*$/`},
{in: `SELECT value FROM cpu WHERE host !~ /^a.b$/`, out: `SELECT value FROM cpu WHERE host !~ /^a.b$/`},
{in: `SELECT value FROM cpu WHERE host !~ /^ab+$/`, out: `SELECT value FROM cpu WHERE host !~ /^ab+$/`},
// These regexes are not supported due to the presence of unsupported regex flags.
{in: `SELECT value FROM cpu WHERE host =~ /(?i)^SeRvEr01$/`, out: `SELECT value FROM cpu WHERE host =~ /(?i)^SeRvEr01$/`},
// These regexes are not supported due to large character class(es).
{in: `SELECT value FROM cpu WHERE host =~ /^[^abcd]$/`, out: `SELECT value FROM cpu WHERE host =~ /^[^abcd]$/`},
// These regexes all match and will be rewritten.
{in: `SELECT value FROM cpu WHERE host !~ /^a[2]$/`, out: `SELECT value FROM cpu WHERE host != 'a2'`},
{in: `SELECT value FROM cpu WHERE host =~ /^server-1$/`, out: `SELECT value FROM cpu WHERE host = 'server-1'`},
{in: `SELECT value FROM cpu WHERE host !~ /^server-1$/`, out: `SELECT value FROM cpu WHERE host != 'server-1'`},
{in: `SELECT value FROM cpu WHERE host =~ /^server 1$/`, out: `SELECT value FROM cpu WHERE host = 'server 1'`},
{in: `SELECT value FROM cpu WHERE host =~ /^$/`, out: `SELECT value FROM cpu WHERE host = ''`},
{in: `SELECT value FROM cpu WHERE host !~ /^$/`, out: `SELECT value FROM cpu WHERE host != ''`},
{in: `SELECT value FROM cpu WHERE host =~ /^server-1$/ OR host =~ /^server-2$/`, out: `SELECT value FROM cpu WHERE host = 'server-1' OR host = 'server-2'`},
{in: `SELECT value FROM cpu WHERE host =~ /^server-1$/ OR host =~ /^server]a$/`, out: `SELECT value FROM cpu WHERE host = 'server-1' OR host = 'server]a'`},
{in: `SELECT value FROM cpu WHERE host =~ /^hello\?$/`, out: `SELECT value FROM cpu WHERE host = 'hello?'`},
{in: `SELECT value FROM cpu WHERE host !~ /^\\$/`, out: `SELECT value FROM cpu WHERE host != '\\'`},
{in: `SELECT value FROM cpu WHERE host !~ /^\\\$$/`, out: `SELECT value FROM cpu WHERE host != '\\$'`},
// This is supported, but annoying to write and the below queries satisfy this condition.
//{in: `SELECT value FROM cpu WHERE host =~ /^hello\world$/`, out: `SELECT value FROM cpu WHERE host =~ /^hello\world$/`},
{in: `SELECT value FROM cpu WHERE host =~ /^(server-1|server-2|server-3)$/`, out: `SELECT value FROM cpu WHERE host = 'server-1' OR host = 'server-2' OR host = 'server-3'`},
{in: `SELECT value FROM cpu WHERE host !~ /^(foo|bar)$/`, out: `SELECT value FROM cpu WHERE host != 'foo' AND host != 'bar'`},
{in: `SELECT value FROM cpu WHERE host !~ /^\d$/`, out: `SELECT value FROM cpu WHERE host != '0' AND host != '1' AND host != '2' AND host != '3' AND host != '4' AND host != '5' AND host != '6' AND host != '7' AND host != '8' AND host != '9'`},
{in: `SELECT value FROM cpu WHERE host !~ /^[a-z]$/`, out: `SELECT value FROM cpu WHERE host != 'a' AND host != 'b' AND host != 'c' AND host != 'd' AND host != 'e' AND host != 'f' AND host != 'g' AND host != 'h' AND host != 'i' AND host != 'j' AND host != 'k' AND host != 'l' AND host != 'm' AND host != 'n' AND host != 'o' AND host != 'p' AND host != 'q' AND host != 'r' AND host != 's' AND host != 't' AND host != 'u' AND host != 'v' AND host != 'w' AND host != 'x' AND host != 'y' AND host != 'z'`},
{in: `SELECT value FROM cpu WHERE host =~ /^[ab]{3}$/`, out: `SELECT value FROM cpu WHERE host = 'aaa' OR host = 'aab' OR host = 'aba' OR host = 'abb' OR host = 'baa' OR host = 'bab' OR host = 'bba' OR host = 'bbb'`},
}
for i, test := range tests {
stmt, err := influxql.NewParser(strings.NewReader(test.in)).ParseStatement()
if err != nil {
t.Fatalf("[Example %d], %v", i, err)
}
// Rewrite any supported regex conditions.
stmt.(*influxql.SelectStatement).RewriteRegexConditions()
// Get the expected rewritten statement.
expStmt, err := influxql.NewParser(strings.NewReader(test.out)).ParseStatement()
if err != nil {
t.Fatalf("[Example %d], %v", i, err)
}
// Compare the (potentially) rewritten AST to the expected AST.
if got, exp := stmt, expStmt; !reflect.DeepEqual(got, exp) {
t.Errorf("[Example %d]\nattempting %v\ngot %v\n%s\n\nexpected %v\n%s\n", i+1, test.in, got, mustMarshalJSON(got), exp, mustMarshalJSON(exp))
}
}
}
// Test SELECT statement time field rewrite.
func TestSelectStatement_RewriteTimeFields(t *testing.T) {
var tests = []struct {
s string
stmt influxql.Statement
}{
{
s: `SELECT time, field1 FROM cpu`,
stmt: &influxql.SelectStatement{
IsRawQuery: true,
Fields: []*influxql.Field{
{Expr: &influxql.VarRef{Val: "field1"}},
},
Sources: []influxql.Source{
&influxql.Measurement{Name: "cpu"},
},
},
},
{
s: `SELECT time AS timestamp, field1 FROM cpu`,
stmt: &influxql.SelectStatement{
IsRawQuery: true,
Fields: []*influxql.Field{
{Expr: &influxql.VarRef{Val: "field1"}},
},
Sources: []influxql.Source{
&influxql.Measurement{Name: "cpu"},
},
TimeAlias: "timestamp",
},
},
}
for i, tt := range tests {
// Parse statement.
stmt, err := influxql.NewParser(strings.NewReader(tt.s)).ParseStatement()
if err != nil {
t.Fatalf("invalid statement: %q: %s", tt.s, err)
}
// Rewrite statement.
stmt.(*influxql.SelectStatement).RewriteTimeFields()
if !reflect.DeepEqual(tt.stmt, stmt) {
t.Logf("\n# %s\nexp=%s\ngot=%s\n", tt.s, mustMarshalJSON(tt.stmt), mustMarshalJSON(stmt))
t.Logf("\nSQL exp=%s\nSQL got=%s\n", tt.stmt.String(), stmt.String())
t.Errorf("%d. %q\n\nstmt mismatch:\n\nexp=%#v\n\ngot=%#v\n\n", i, tt.s, tt.stmt, stmt)
}
}
}
// Ensure that the IsRawQuery flag gets set properly
func TestSelectStatement_IsRawQuerySet(t *testing.T) {
var tests = []struct {
stmt string
isRaw bool
}{
{
stmt: "select * from foo",
isRaw: true,
},
{
stmt: "select value1,value2 from foo",
isRaw: true,
},
{
stmt: "select value1,value2 from foo, time(10m)",
isRaw: true,
},
{
stmt: "select mean(value) from foo where time < now() group by time(5m)",
isRaw: false,
},
{
stmt: "select mean(value) from foo group by bar",
isRaw: false,
},
{
stmt: "select mean(value) from foo group by *",
isRaw: false,
},
{
stmt: "select mean(value) from foo group by *",
isRaw: false,
},
}
for _, tt := range tests {
s := MustParseSelectStatement(tt.stmt)
if s.IsRawQuery != tt.isRaw {
t.Errorf("'%s', IsRawQuery should be %v", tt.stmt, tt.isRaw)
}
}
}
// Ensure binary expression names can be evaluated.
func TestBinaryExprName(t *testing.T) {
for i, tt := range []struct {
expr string
name string
}{
{expr: `value + 1`, name: `value`},
{expr: `"user" / total`, name: `user_total`},
{expr: `("user" + total) / total`, name: `user_total_total`},
} {
expr := influxql.MustParseExpr(tt.expr)
switch expr := expr.(type) {
case *influxql.BinaryExpr:
name := influxql.BinaryExprName(expr)
if name != tt.name {
t.Errorf("%d. unexpected name %s, got %s", i, name, tt.name)
}
default:
t.Errorf("%d. unexpected expr type: %T", i, expr)
}
}
}
func TestConditionExpr(t *testing.T) {
mustParseTime := func(value string) time.Time {
ts, err := time.Parse(time.RFC3339, value)
if err != nil {
t.Fatalf("unable to parse time: %s", err)
}
return ts
}
now := mustParseTime("2000-01-01T00:00:00Z")
valuer := influxql.NowValuer{Now: now}
for _, tt := range []struct {
s string
cond string
min, max time.Time
err string
}{
{s: `host = 'server01'`, cond: `host = 'server01'`},
{s: `time >= '2000-01-01T00:00:00Z' AND time < '2000-01-01T01:00:00Z'`,
min: mustParseTime("2000-01-01T00:00:00Z"),
max: mustParseTime("2000-01-01T01:00:00Z").Add(-1)},
{s: `host = 'server01' AND (region = 'uswest' AND time >= now() - 10m)`,
cond: `host = 'server01' AND (region = 'uswest')`,
min: mustParseTime("1999-12-31T23:50:00Z")},
{s: `(host = 'server01' AND region = 'uswest') AND time >= now() - 10m`,
cond: `host = 'server01' AND region = 'uswest'`,
min: mustParseTime("1999-12-31T23:50:00Z")},
{s: `host = 'server01' AND (time >= '2000-01-01T00:00:00Z' AND time < '2000-01-01T01:00:00Z')`,
cond: `host = 'server01'`,
min: mustParseTime("2000-01-01T00:00:00Z"),
max: mustParseTime("2000-01-01T01:00:00Z").Add(-1)},
{s: `(time >= '2000-01-01T00:00:00Z' AND time < '2000-01-01T01:00:00Z') AND host = 'server01'`,
cond: `host = 'server01'`,
min: mustParseTime("2000-01-01T00:00:00Z"),
max: mustParseTime("2000-01-01T01:00:00Z").Add(-1)},
{s: `'2000-01-01T00:00:00Z' <= time AND '2000-01-01T01:00:00Z' > time`,
min: mustParseTime("2000-01-01T00:00:00Z"),
max: mustParseTime("2000-01-01T01:00:00Z").Add(-1)},
{s: `'2000-01-01T00:00:00Z' < time AND '2000-01-01T01:00:00Z' >= time`,
min: mustParseTime("2000-01-01T00:00:00Z").Add(1),
max: mustParseTime("2000-01-01T01:00:00Z")},
{s: `time = '2000-01-01T00:00:00Z'`,
min: mustParseTime("2000-01-01T00:00:00Z"),
max: mustParseTime("2000-01-01T00:00:00Z")},
{s: `time >= 10s`, min: mustParseTime("1970-01-01T00:00:10Z")},
{s: `time >= 10000000000`, min: mustParseTime("1970-01-01T00:00:10Z")},
{s: `time >= 10000000000.0`, min: mustParseTime("1970-01-01T00:00:10Z")},
{s: `time > now()`, min: now.Add(1)},
{s: `value`, err: `invalid condition expression: value`},
{s: `4`, err: `invalid condition expression: 4`},
{s: `time >= 'today'`, err: `invalid operation: time and *influxql.StringLiteral are not compatible`},
{s: `time != '2000-01-01T00:00:00Z'`, err: `invalid time comparison operator: !=`},
// This query makes no logical sense, but it's common enough that we pretend
// it does. Technically, this should be illegal because the AND has higher precedence
// than the OR so the AND only applies to the server02 tag, but a person's intention
// is to have it apply to both and previous versions worked that way.
{s: `host = 'server01' OR host = 'server02' AND time >= now() - 10m`,
cond: `host = 'server01' OR host = 'server02'`,
min: mustParseTime("1999-12-31T23:50:00Z")},
// TODO(jsternberg): This should be an error, but we can't because the above query
// needs to work. Until we can work a way for the above to work or at least get
// a warning message for people to transition to a correct syntax, the bad behavior
// stays.
//{s: `host = 'server01' OR (time >= now() - 10m AND host = 'server02')`, err: `cannot use OR with time conditions`},
{s: `value AND host = 'server01'`, err: `invalid condition expression: value`},
{s: `host = 'server01' OR (value)`, err: `invalid condition expression: value`},
{s: `time > '2262-04-11 23:47:17'`, err: `time 2262-04-11T23:47:17Z overflows time literal`},
{s: `time > '1677-09-20 19:12:43'`, err: `time 1677-09-20T19:12:43Z underflows time literal`},
{s: `true AND (false OR product = 'xyz')`,
cond: `product = 'xyz'`,
},
{s: `'a' = 'a'`, cond: ``},
{s: `value > 0 OR true`, cond: ``},
{s: `host = 'server01' AND false`, cond: `false`},
{s: `TIME >= '2000-01-01T00:00:00Z'`, min: mustParseTime("2000-01-01T00:00:00Z")},
{s: `'2000-01-01T00:00:00Z' <= TIME`, min: mustParseTime("2000-01-01T00:00:00Z")},
// Remove enclosing parentheses
{s: `(host = 'server01')`, cond: `host = 'server01'`},
// Preserve nested parentheses
{s: `host = 'server01' AND (region = 'region01' OR region = 'region02')`,
cond: `host = 'server01' AND (region = 'region01' OR region = 'region02')`,
},
} {
t.Run(tt.s, func(t *testing.T) {
expr, err := influxql.ParseExpr(tt.s)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
cond, timeRange, err := influxql.ConditionExpr(expr, &valuer)
if err != nil {
if tt.err == "" {
t.Fatalf("unexpected error: %s", err)
} else if have, want := err.Error(), tt.err; have != want {
t.Fatalf("unexpected error: %s != %s", have, want)
}
}
if cond != nil {
if have, want := cond.String(), tt.cond; have != want {
t.Errorf("unexpected condition:\nhave=%s\nwant=%s", have, want)
}
} else {
if have, want := "", tt.cond; have != want {
t.Errorf("unexpected condition:\nhave=%s\nwant=%s", have, want)
}
}
if have, want := timeRange.Min, tt.min; !have.Equal(want) {
t.Errorf("unexpected min time:\nhave=%s\nwant=%s", have, want)
}
if have, want := timeRange.Max, tt.max; !have.Equal(want) {
t.Errorf("unexpected max time:\nhave=%s\nwant=%s", have, want)
}
})
}
}
// Ensure an AST node can be rewritten.
func TestRewrite(t *testing.T) {
expr := MustParseExpr(`time > 1 OR foo = 2`)
// Flip LHS & RHS in all binary expressions.
act := influxql.RewriteFunc(expr, func(n influxql.Node) influxql.Node {
switch n := n.(type) {
case *influxql.BinaryExpr:
return &influxql.BinaryExpr{Op: n.Op, LHS: n.RHS, RHS: n.LHS}
default:
return n
}
})
// Verify that everything is flipped.
if act := act.String(); act != `2 = foo OR 1 > time` {
t.Fatalf("unexpected result: %s", act)
}
}
// Ensure an Expr can be rewritten handling nils.
func TestRewriteExpr(t *testing.T) {
expr := MustParseExpr(`(time > 1 AND time < 10) OR foo = 2`)
// Remove all time expressions.
act := influxql.RewriteExpr(expr, func(e influxql.Expr) influxql.Expr {
switch e := e.(type) {
case *influxql.BinaryExpr:
if lhs, ok := e.LHS.(*influxql.VarRef); ok && lhs.Val == "time" {
return nil
}
}
return e
})
// Verify that everything is flipped.
if act := act.String(); act != `foo = 2` {
t.Fatalf("unexpected result: %s", act)
}
}
// Ensure that the String() value of a statement is parseable
func TestParseString(t *testing.T) {
var tests = []struct {
stmt string
}{
{
stmt: `SELECT "cpu load" FROM myseries`,
},
{
stmt: `SELECT "cpu load" FROM "my series"`,
},
{
stmt: `SELECT "cpu\"load" FROM myseries`,
},
{
stmt: `SELECT "cpu'load" FROM myseries`,
},
{
stmt: `SELECT "cpu load" FROM "my\"series"`,
},
{
stmt: `SELECT "field with spaces" FROM "\"ugly\" db"."\"ugly\" rp"."\"ugly\" measurement"`,
},
{
stmt: `SELECT * FROM myseries`,
},
{
stmt: `DROP DATABASE "!"`,
},
{
stmt: `DROP RETENTION POLICY "my rp" ON "a database"`,
},
{
stmt: `CREATE RETENTION POLICY "my rp" ON "a database" DURATION 1d REPLICATION 1`,
},
{
stmt: `ALTER RETENTION POLICY "my rp" ON "a database" DEFAULT`,
},
{
stmt: `SHOW RETENTION POLICIES ON "a database"`,
},
{
stmt: `SHOW TAG VALUES WITH KEY IN ("a long name", short)`,
},
{
stmt: `DROP CONTINUOUS QUERY "my query" ON "my database"`,
},
// See issues https://github.com/influxdata/influxdb/issues/1647
// and https://github.com/influxdata/influxdb/issues/4404
//{
// stmt: `DELETE FROM "my db"."my rp"."my measurement"`,
//},
{
stmt: `DROP SUBSCRIPTION "ugly \"subscription\" name" ON "\"my\" db"."\"my\" rp"`,
},
{
stmt: `CREATE SUBSCRIPTION "ugly \"subscription\" name" ON "\"my\" db"."\"my\" rp" DESTINATIONS ALL 'my host', 'my other host'`,
},
{
stmt: `SHOW MEASUREMENTS WITH MEASUREMENT =~ /foo/`,
},
{
stmt: `SHOW MEASUREMENTS WITH MEASUREMENT = "and/or"`,
},
{
stmt: `DROP USER "user with spaces"`,
},
{
stmt: `GRANT ALL PRIVILEGES ON "db with spaces" TO "user with spaces"`,
},
{
stmt: `GRANT ALL PRIVILEGES TO "user with spaces"`,
},
{
stmt: `SHOW GRANTS FOR "user with spaces"`,
},
{
stmt: `REVOKE ALL PRIVILEGES ON "db with spaces" FROM "user with spaces"`,
},
{
stmt: `REVOKE ALL PRIVILEGES FROM "user with spaces"`,
},