-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvfilter.go
1825 lines (1501 loc) · 44.8 KB
/
vfilter.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
/*
The veloci-filter (vfilter) library implements a generic SQL like
query language.
Overview::
There are many applications in which it is useful to provide a
flexible query language for the end user. Velocifilter has the
following design goals:
- It should be generic and easily adaptable to be used by any project.
- It should be fast and efficient.
An example makes the use case very clear. Suppose you are writing an
archiving application. Most archiving tools require a list of files to
be archived (e.g. on the command line).
You launch your tool and a user requests a new flag that allows them
to specify the files using a glob expression. For example, a user
might wish to only select the files ending with the ".go"
extension. While on a unix system one might use shell expansion to
support this, on other operating systems shell expansion may not work
(e.g. on windows).
You then add the ability to specify a glob expression directly to your
tool (suppose you add the flag --glob). A short while later, a user
requires filtering the files to archive by their size - suppose they
want to only archive a file smaller than a certain size. You
studiously add another set of flags (e.g. --size with a special syntax
for greater than or less than semantics).
Now a user wishes to be able to combine these conditions logically
(e.g. all files with ".go" extension newer than 5 days and smaller
than 5kb).
Clearly this approach is limited, if we wanted to support every
possible use case, our tool would add many flags with a complex syntax
making it harder for our users. One approach is to simply rely on the
unix "find" tool (with its many obscure flags) to support the file
selection problem. This is not ideal either since the find tool may
not be present on the system (E.g. on Windows) or may have varying
syntax. It may also not support every possible condition the user may
have in mind (e.g. files containing a RegExp or files not present in
the archive).
There has to be a better way. You wish to provide your users with a
powerful and flexible way to specify which files to archive, but we do
not want to write complicated logic and make our tool more complex to
use.
This is where velocifilter comes in. By using the library we can
provide a single flag where the user may specify a flexible VQL query
(Velocidex Query Language - a simplified SQL dialect) allowing the
user to specify arbirarily complex filter expressions. For example:
SELECT file from glob(pattern=["*.go", "*.py"]) where file.Size < 5000
and file.Mtime < now() - "5 days"
Not only does VQL allow for complex logical operators, but it is also
efficient and optimized automatically. For example, consider the
following query:
SELECT file from glob(pattern="*") where grep(file=file,
pattern="foobar") and file.Size < 5k
The grep() function will open the file and search it for the
pattern. If the file is large, this might take a long time. However
velocifilter will automatically abort the grep() function if the file
size is larger than 5k bytes. Velocifilter correctly handles such
cancellations automatically in order to reduce query evaluation
latency.
Protocols - supporting custom types::
Velocifilter uses a plugin system to allow clients to define how
their own custom types behave within the VQL evaluator.
Note that this is necessary because Go does not allow an external
package to add an interface to an existing type without creating a new
type which embeds it. Clients who need to handle the original third
party types must have a way to attach new protocols to existing types
defined outside their own codebase. Velocifilter achieves this by
implementing a registration systen in the Scope{} object.
For example, consider a client of the library wishing to pass custom
types in queries:
type Foo struct {
...
bar Bar
}
Where both Foo and Bar are defined and produced by some other library
which our client uses. Suppose our client wishes to allow addition of
Foo objects. We would therefore need to implement the AddProtocol
interface on Foo structs. Since Foo structs are defined externally we
can not simply add a new method to Foo struct (we could embed Foo
struct in a new struct, but then we would also need to wrap the bar
field to produce an extended Bar. This is typically impractical and
not maintainable for heavily nested complex structs). We define a
FooAdder{} object which implements the Addition protocol on behalf of
the Foo object.
// This is an object which implements addition between two Foo objects.
type FooAdder struct{}
// This method will be run to see if this implementation is
// applicable. We only want to run when we add two Foo objects together.
func (self FooAdder) Applicable(a Any, b Any) bool {
_, a_ok := a.(Foo)
_, b_ok := b.(Foo)
return a_ok && b_ok
}
// Actually implement the addition between two Foo objects.
func (self FooAdder) Add(scope types.Scope, a Any, b Any) Any {
... return new object (does not have to be Foo{}).
}
Now clients can add this protocol to the scope before evaluating a
query:
scope := NewScope().AddProtocolImpl(FooAdder{})
*/
package vfilter
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"github.com/Velocidex/ordereddict"
"github.com/alecthomas/participle"
"github.com/alecthomas/participle/lexer"
errors "github.com/pkg/errors"
"www.velocidex.com/golang/vfilter/scope"
scope_module "www.velocidex.com/golang/vfilter/scope"
"www.velocidex.com/golang/vfilter/types"
"www.velocidex.com/golang/vfilter/utils"
)
var (
vqlLexer = lexer.Must(lexer.Regexp(
`(?ms)` +
`(\s+)` +
`|(?P<MLineComment>/[*].*?[*]/)` + // C Style comment.
`|(?P<VQLComment>^--.*?$)` + // SQL style one line comment.
`|(?P<Comment>^//.*?$)` + // C++ style one line comment.
`|(?ims)(?P<EXPLAIN>\bEXPLAIN\b)` +
`|(?ims)(?P<SELECT>\bSELECT\b)` +
`|(?ims)(?P<WHERE>\bWHERE\b)` +
`|(?ims)(?P<AND>\bAND\b)` +
`|(?ims)(?P<OR>\bOR\b)` +
`|(?ims)(?P<AlternativeOR>\|+)` +
`|(?ims)(?P<AlternativeAND>&&)` +
`|(?ims)(?P<FROM>\bFROM\b)` +
`|(?ims)(?P<NOT>\bNOT\b)` +
`|(?ims)(?P<AS>\bAS\b)` +
`|(?ims)(?P<IN>\bIN\b)` +
`|(?ims)(?P<LIMIT>\bLIMIT\b)` +
`|(?ims)(?P<NULL>\bNULL\b)` +
`|(?ims)(?P<DESC>\bDESC\b)` +
`|(?ims)(?P<GROUPBY>\bGROUP\s+BY\b)` +
`|(?ims)(?P<ORDERBY>\bORDER\s+BY\b)` +
`|(?ims)(?P<BOOL>\bTRUE\b|\bFALSE\b)` +
`|(?ims)(?P<LET>\bLET\b)` +
"|(?P<Ident>[a-zA-Z_][a-zA-Z0-9_]*|`[^`]+`)" +
`|''(?P<MultilineString>'.*?')''` +
`|(?P<String>'([^'\\]*(\\.[^'\\]*)*)'|"([^"\\]*(\\.[^"\\]*)*)")` +
`|(?P<Number>[-+]?(0x[0-9a-f]+|\d*\.?\d+([eE][-+]?\d+)?))` +
`|(?P<Operators><>|!=|<=|>=|=>|=~|[-:+*/%,.()=<>{}\[\]])`,
))
vqlParser = participle.MustBuild(
&VQL{},
participle.Lexer(vqlLexer),
participle.Upper("IN", "DESC"),
participle.Elide("Comment", "MLineComment", "VQLComment"),
// Need to solve left recursion detection first, if possible.
// participle.UseLookahead(),
)
multiVQLParser = participle.MustBuild(
&MultiVQL{},
participle.Lexer(vqlLexer),
participle.Upper("IN", "DESC"),
participle.Elide("Comment", "MLineComment", "VQLComment"),
)
multiVQLParserWithComments = participle.MustBuild(
&MultiVQL{},
participle.Lexer(vqlLexer),
participle.Upper("IN", "DESC"),
)
)
func reportError(err error, t *lexer.Error, expression string) error {
end := t.Tok.Pos.Offset + 10
if end >= len(expression) {
end = len(expression) - 1
}
if end < 0 {
end = 0
}
start := t.Tok.Pos.Offset - 10
if start < 0 {
start = 0
}
pos := t.Tok.Pos.Offset
if pos >= len(expression) {
pos = len(expression) - 1
}
if pos < 0 {
pos = 0
}
return errors.Wrap(
err,
expression[start:pos]+"|"+expression[pos:end])
}
// Parse the VQL expression. Returns a VQL object which may be
// evaluated.
func Parse(expression string) (*VQL, error) {
vql := &VQL{}
err := vqlParser.ParseString(expression, vql)
switch t := err.(type) {
case *lexer.Error:
return vql, reportError(err, t, expression)
default:
return vql, err
}
}
// Parse a string into multiple VQL statements.
func MultiParse(expression string) ([]*VQL, error) {
vql := &MultiVQL{}
err := multiVQLParser.ParseString(expression, vql)
switch t := err.(type) {
case *lexer.Error:
return nil, reportError(err, t, expression)
default:
return vql.GetStatements(), err
}
}
// Parse a string into multiple VQL statements.
func MultiParseWithComments(expression string) ([]*VQL, error) {
vql := &MultiVQL{}
err := multiVQLParserWithComments.ParseString(expression, vql)
switch t := err.(type) {
case *lexer.Error:
return nil, reportError(err, t, expression)
default:
return vql.GetStatements(), err
}
}
type MultiVQL struct {
Comments []*_Comment `{ @@ } `
VQL1 *VQL ` @@ `
Comments2 []*_Comment `{ @@ } `
VQL2 *MultiVQL ` { @@ } `
}
func (self *MultiVQL) GetStatements() []*VQL {
self.VQL1.Comments = self.Comments
// Rebalance the comments - trailing comments belong in the next
// statement
if len(self.Comments2) > 0 && self.VQL2 != nil {
self.VQL2.Comments = append(self.Comments2, self.VQL2.Comments...)
self.Comments2 = nil
}
result := []*VQL{self.VQL1}
if self.VQL2 != nil {
return append(result, self.VQL2.GetStatements()...)
}
return result
}
type _Comment struct {
VQLComment *string `( @VQLComment | `
Comment *string `@Comment | `
MultiLine *string `@MLineComment )`
}
// An opaque object representing the VQL expression.
type VQL struct {
Let string `LET @Ident `
Parameters *_ParameterList `{ "(" @@ ")" }`
LetOperator string ` ( @"=" | @"<=" ) `
StoredQuery *_Select ` ( @@ | `
Expression *_AndExpression ` @@ ) |`
Query *_Select ` @@ `
Comments []*_Comment
}
type _ParameterList struct {
Comments []*_Comment ` [ @@ ] `
Left string ` @Ident `
Right *_ParameterListTerm `{ @@ }`
}
type _ParameterListTerm struct {
Operator string `@","`
Term *_ParameterList ` @@ `
}
// Returns the type of statement it is:
// LAZY_LET - A lazy stored query
// MATERIALIZED_LET - A stored meterialized query.
// SELECT - A query
func (self *VQL) Type() string {
if self.LetOperator == "=" {
return "LAZY_LET"
} else if self.LetOperator == "<=" {
return "MATERIALIZED_LET"
} else if self.Query != nil && self.Query.Explain != nil {
return "EXPLAIN"
} else if self.Query != nil {
return "SELECT"
}
return ""
}
// Evaluate the expression. Returns a channel which emits a series of
// rows.
func (self *VQL) Eval(ctx context.Context, scope types.Scope) <-chan Row {
output_chan := make(chan Row)
// If this is a Let expression we need to create a stored
// query and assign to the scope.
if len(self.Let) > 0 {
if self.Parameters != nil && self.LetOperator == "<=" {
scope.Log("WARN:Expression %v takes parameters but is "+
"materialized! Did you mean to use '='? ", self.Let)
}
_, pres := scope.GetFunction(self.Let)
if pres {
scope.Log("WARN:LET expression is masking a built in function %v", self.Let)
}
name := utils.Unquote_ident(self.Let)
// Let assigning an expression.
if self.Expression != nil {
expr := &StoredExpression{
Expr: self.Expression,
name: name,
}
if self.Parameters != nil {
expr.parameters = self.getParameters()
}
switch self.LetOperator {
// Store the expression in the scope for later.
case "=":
scope.AppendVars(ordereddict.NewDict().
Set(name, expr))
// If we are materializing here,
// reduce it now.
case "<=":
// It may yield a stored query - in
// that case we materialize it in
// place.
value := expr.Reduce(ctx, scope)
stored_query, ok := value.(types.StoredQuery)
if ok {
value = scope.Materialize(ctx, name, stored_query)
}
scope.AppendVars(ordereddict.NewDict().Set(name, value))
}
close(output_chan)
return output_chan
}
// LET is for stored query: LET X = SELECT ...
switch self.LetOperator {
case "=":
stored_query := NewStoredQuery(self.StoredQuery, name)
if self.Parameters != nil {
stored_query.parameters = self.getParameters()
}
scope.AppendVars(ordereddict.NewDict().Set(name, stored_query))
case "<=":
// Delegate to the scope's materializer to actually
// materialize this query.
scope.AppendVars(ordereddict.NewDict().Set(
name, scope.Materialize(ctx, name, self.StoredQuery)))
}
close(output_chan)
return output_chan
} else {
subscope := scope.Copy()
subscope.AppendVars(
ordereddict.NewDict().Set("$Query", FormatToString(scope, self)))
go func() {
defer close(output_chan)
defer subscope.Close()
row_chan := self.Query.Eval(ctx, subscope)
for {
select {
case <-ctx.Done():
return
case row, ok := <-row_chan:
if !ok {
return
}
output_chan <- row
}
}
}()
return output_chan
}
}
// Walk the parameters list and collect all the parameter names.
func visitor(parameters *_ParameterList, result *[]string) {
*result = append(*result, parameters.Left)
if parameters.Right != nil {
visitor(parameters.Right.Term, result)
}
}
func (self *VQL) getParameters() []string {
result := []string{}
if self.Let != "" && self.Parameters != nil {
visitor(self.Parameters, &result)
}
return result
}
type _Select struct {
Comments []*_Comment ` { @@ } `
Explain *bool ` { @EXPLAIN }`
SelectExpression *_SelectExpression `SELECT @@`
From *_From `FROM @@`
Where *_CommaExpression `[ WHERE @@ ]`
GroupBy *_CommaExpression `[ GROUPBY @@ ]`
OrderBy *string `[ ORDERBY @Ident `
OrderByDesc *bool ` [ @DESC ] ]`
Limit *int64 `[ LIMIT @Number ]`
}
func (self *_Select) Eval(ctx context.Context, scope types.Scope) <-chan Row {
// If the EXPLAIN keyword was used, enabled explaining for this
// scope and its children.
if self.Explain != nil {
scope.EnableExplain()
}
// Start query evaluation
scope.Explainer().StartQuery(self)
output_chan := make(chan Row)
// Limits occur before the group by so we can cut the group by
// result short according to the limit clause.
if self.Limit != nil {
go func() {
defer close(output_chan)
limit := int(*self.Limit)
count := 1
self_copy := *self
self_copy.Limit = nil
// Cancel the query when we hit the limit.
sub_ctx, cancel := context.WithCancel(ctx)
defer cancel()
for row := range self_copy.Eval(sub_ctx, scope) {
select {
case <-ctx.Done():
return
case output_chan <- row:
}
count += 1
if count > limit {
return
}
}
}()
return output_chan
}
// Group by occurs before order by so we can order the grouped by
// results.
if self.GroupBy != nil {
return self.EvalGroupBy(ctx, scope)
}
if self.OrderBy != nil {
desc := false
if self.OrderByDesc != nil {
desc = *self.OrderByDesc
}
// Sort the output groups
sorter_input_chan := make(chan Row)
sorted_chan := scope.(*scope_module.Scope).Sort(
ctx, scope, sorter_input_chan,
utils.Unquote_ident(*self.OrderBy), desc)
// Feed all the aggregate rows into the sorter.
go func() {
defer close(sorter_input_chan)
// Re-run the same query with no order by clause then
// we sort the results.
self_copy := *self
self_copy.OrderBy = nil
for row := range self_copy.Eval(ctx, scope) {
sorter_input_chan <- row
}
}()
return sorted_chan
}
// Gets a row from the FROM clause, then transforms it
// according to the SelectExpression. After transformation,
// apply the WHERE clause to the row to determine if it should
// be relayed. NOTE: We need to transform the row first in
// order to assign aliases.
go func() {
from_chan := self.From.Eval(ctx, scope)
defer close(output_chan)
for {
select {
// Are we cancelled?
case <-ctx.Done():
return
// Get a row
case row, ok := <-from_chan:
if !ok {
return
}
scope.Explainer().PluginOutput(
&self.From.Plugin, row)
self.processSingleRow(ctx, scope, row, output_chan)
}
}
}()
return output_chan
}
func (self *_Select) processSingleRow(
ctx context.Context, scope types.Scope, row Row, output_chan chan Row) {
subscope := scope.Copy()
defer subscope.Close()
transformed_row, closer := self.SelectExpression.Transform(
ctx, subscope, row)
defer closer()
if self.Where == nil {
materialized_row := MaterializedLazyRow(
ctx, transformed_row, subscope)
select {
case <-ctx.Done():
return
case output_chan <- materialized_row:
scope.Explainer().SelectOutput(materialized_row)
}
} else {
// If there is a filter clause, we need to filter the
// row using a new scope.
new_scope := subscope.Copy()
defer new_scope.Close()
// Filters can access both the untransformed row and
// the transformed row. This allows WHERE clause to
// refer to both the raw plugin output as well as
// aliases of transformations on the row.
new_scope.AppendVars(row)
new_scope.AppendVars(transformed_row)
expression := self.Where.Reduce(ctx, new_scope)
// If the filtered expression returns a bool true,
// then pass the row to the output.
if expression != nil && scope.Bool(expression) {
materialized_row := MaterializedLazyRow(
ctx, transformed_row, new_scope)
select {
case <-ctx.Done():
return
case output_chan <- materialized_row:
scope.Explainer().SelectOutput(materialized_row)
}
} else {
scope.Explainer().RejectRow(self.Where)
}
}
}
type _From struct {
Plugin Plugin ` @@ `
}
type Plugin struct {
mu sync.Mutex
split_name []string
Name string `@Ident { @"." @Ident } `
Call bool `[ @"("`
Args []*_Args ` [ @@ { "," @@ } ] ")" ]`
}
type _Args struct {
Comments []*_Comment `[ @@ ] `
Left string `@Ident "=" `
SubSelect *_Select `( "{" @@ "}" | `
ArrayOpenBrace string ` @"[" `
Array *_CommaExpression ` @@? `
ArrayCloseBrace string `@"]" | `
Right *_AndExpression ` @@ ) `
}
type _SelectExpression struct {
All bool ` [ @"*" ","? ] `
Expressions []*_AliasedExpression ` [ @@ { "," @@ } ]`
}
type _AliasedExpression struct {
Comments []*_Comment ` { @@ } `
Star *bool ` ( @"*" | `
SubSelect *_Select ` "{" @@ "}" |`
Expression *_AndExpression ` @@ )`
As string `[ AS @Ident ]`
mu sync.Mutex
cache, column_name *string
}
// Cache the column name since each row needs it
func (self *_AliasedExpression) GetName(scope types.Scope) string {
self.mu.Lock()
column_name := self.column_name
self.mu.Unlock()
if column_name != nil {
return *column_name
}
if self.As != "" {
name := utils.Unquote_ident(self.As)
column_name = &name
} else {
name := utils.Unquote_ident(FormatToString(scope, self))
column_name = &name
}
self.mu.Lock()
self.column_name = column_name
self.mu.Unlock()
return *column_name
}
func (self *_AliasedExpression) IsAggregate(scope types.Scope) bool {
if self.SubSelect != nil {
return true
}
if self.Expression.IsAggregate(scope) {
return true
}
return false
}
func (self *_AliasedExpression) Reduce(ctx context.Context, scope types.Scope) Any {
if self.Expression != nil {
return self.Expression.Reduce(ctx, scope)
}
if self.SubSelect != nil {
var rows []Row
for item := range self.SubSelect.Eval(ctx, scope) {
members := scope.GetMembers(item)
if len(members) == 1 {
item_column, pres := scope.Associative(item, members[0])
if pres {
rows = append(rows, item_column)
}
} else {
rows = append(rows, item)
}
}
// If the subselect returns only a single row
// we just pass that item. This allows a
// subselect in row spec to just substitute
// one value instead of needlessly creating a
// slice of one item.
if len(rows) == 1 {
return rows[0]
} else {
return rows
}
}
return nil
}
// Expressions separated by addition or subtraction.
type _AdditionExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_MultiplicationExpression `@@`
Right []*_OpAddTerm `{ @@ }`
}
type _OpAddTerm struct {
Operator string `@("+" | "-")`
Term *_MultiplicationExpression `@@`
}
// Expressions separated by multiplication or division.
type _MultiplicationExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_MemberExpression `@@`
Right []*_OpFactor `{ @@ }`
}
type _OpFactor struct {
Operator string `@("*" | "/")`
Factor *_Value `@@`
}
// Expression for membership access (dot operator).
// e.g. x.y.z
type _MemberExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_Value `@@`
Right []*_OpMembershipTerm `[{ @@ }] `
}
type _OpMembershipTerm struct {
Index *_Value ` ( "[" {@@} `
Range *string ` { @":" }`
RangeEnd *_Value ` { @@ } "]" |`
Term *string ` "." @Ident )`
}
type _SliceRange struct {
X *string `( { @Number} ":" `
RangeRightStr *string ` { @Number } )`
}
// ---------------------------------------
// The Top level precedence expression. Precedence table:
// 1) , (Array)
// 2) AND
// 3) OR
// 4) * /
// 5) + -
// 6) . (dereference operator)
// Comma separated expressions create a list.
// e.g. 1, 2, 3 -> (1, 2, 3)
type _CommaExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_AndExpression `@@`
Right []*_OpArrayTerm `{ @@ }`
}
type _OpArrayTerm struct {
Comments []*_Comment ` [ @@ ] `
Operator string `@","`
Comment2 []*_Comment ` [ @@ ] `
Term *_AndExpression `{ @@ }`
}
// Expressions separated by AND.
type _AndExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_OrExpression `( @@ `
Right []*_OpAndTerm `{ @@ })`
}
type _OpAndTerm struct {
Operator string ` ( @AND | @AlternativeAND ) `
Term *_OrExpression `@@`
}
// Expressions separated by OR
type _OrExpression struct {
Comments []*_Comment ` [ @@ ] `
Left *_ConditionOperand `@@`
Right []*_OpOrTerm `{ @@ }`
}
type _OpOrTerm struct {
Operator string ` (@OR | @AlternativeOR) `
Term *_ConditionOperand `@@`
}
// Conditional expressions imply comparison.
type _ConditionOperand struct {
Comments []*_Comment ` [ @@ ] `
Not *_ConditionOperand `(NOT @@ | `
Left *_AdditionExpression `@@)`
Right *_OpComparison `{ @@ }`
}
type _OpComparison struct {
Operator string `@( "<>" | "<=" | ">=" | "=" | "<" | ">" | "!=" | IN | "=~")`
Right *_AdditionExpression `@@`
}
type _Term struct {
Comments []*_Comment ` [ @@ ] `
Select *_Select `| @@`
SymbolRef *_SymbolRef `| @@`
Value *_Value `| @@`
SubExpression *_CommaExpression `| "(" @@ ")"`
}
type _SymbolRef struct {
Comments []*_Comment ` [ @@ ] `
Symbol string `@Ident { @"." @Ident }`
Called bool `{ @"(" `
Parameters []*_Args ` [ @@ { "," @@ } ] ")" } `
mu sync.Mutex
function FunctionInterface
split_symbol []string
}
type _Value struct {
Comments []*_Comment ` [ @@ ] `
Negated bool `[ "-" | "+" ]`
SymbolRef *_SymbolRef `( @@ `
Subexpression *_CommaExpression `| "(" @@ ")"`
String *string ` | @( MultilineString | String ) `
// Figure out if this is an int or float.
StrNumber *string ` | @Number`
Float *float64
Int *int64
Boolean *string ` | @BOOL `
Null bool ` | @NULL)`
mu sync.Mutex
cache Any
}
// A * expression means to merge the old row on top of the new row,
// but not override any variables. This allows users to add a column
// to the left side of a * and have the * merge all old columns if
// they are not there.
func (self *_SelectExpression) mergeStarRow(
scope types.Scope, new_row types.LazyRow, row types.Row) {
for _, member := range scope.GetMembers(row) {
if new_row.Has(member) {
continue
}
value, pres := scope.Associative(row, member)
if pres {
new_row.AddColumn(member,
func(ctx context.Context, scope types.Scope) Any {
return value
})
}
}
}
// Receives a row from the FROM clause (i.e. the plugin) and
// transforms it according to the select expression to produce a new
// row. The transformation results in a lazy row - The column
// expressions are not evaluated, instead they are wrapped in an
// evaluator which will reduce when any column is accessed. The scope
// in which the lazy columns are evaluated is created by extending the
// existing scope with the row scope that came from the plugin. NOTE:
// Returns a closer which should be called when the LazyRow is
// resolved and not needed any more.
func (self *_SelectExpression) Transform(
ctx context.Context, scope types.Scope, row Row) (types.LazyRow, func()) {
// The select uses a * to relay all the rows without filtering
// The select expression consists of multiple columns, each may be
// an expression. Expressions may also be repeated. VQL produces
// unique column names so each column must be a unique string.
// If an AS keyword is used to name the column, then we use that
// name, otherwise we generate the name by converting the
// expression to a string using its ToString() method.
new_row := NewLazyRow(ctx, scope)
// If there is a * expression in addition to the column
// expressions, this is equivalent to adding all the columns as
// defined by the * as if they were explicitely defined.
if self.All {
for _, member := range scope.GetMembers(row) {
value, pres := scope.Associative(row, member)
if pres {
new_row.AddColumn(member,
func(ctx context.Context, scope types.Scope) Any {
return value
})
}
}
}
// Scope will be closed with the parent - need to keep alive until
// the row is materialized.
new_scope := scope.Copy()
// Closer is called by our caller.
new_scope.AppendVars(row)
for _, expr_ := range self.Expressions {
// A copy of the expression for the lambda capture.
expr := expr_
name := expr.GetName(scope)
if name == "*" {
self.mergeStarRow(scope, new_row, row)
continue
}
new_row.AddColumn(
name,
// Use the new scope rather than the callers scope since
// the lazy row may be accessed in any scope but needs to
// resolve members in the scope it was created from.
func(ctx context.Context, scope types.Scope) Any {
item := expr.Reduce(ctx, new_scope)
switch t := item.(type) {
case types.Materializer:
return t.Materialize(ctx, new_scope)
// if we end up with a stored query in a column value
// we expand it since all columns should be
// materialized.
case types.StoredQuery:
return new_scope.Materialize(ctx, name, t)
}
return item
})
}
return new_row, new_scope.Close
}
// The From expression runs the Plugin and then filters each row
// according to the Where clause.
func (self *_From) Eval(ctx context.Context, scope types.Scope) <-chan Row {
output_chan := make(chan Row)
input_chan := self.Plugin.Eval(ctx, scope)
go func() {
defer close(output_chan)
for row := range input_chan {
scope.GetStats().IncRowsScanned()
scope.ChargeOp()