-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcel2sql.go
845 lines (789 loc) · 22.9 KB
/
cel2sql.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
package cel2sql
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/operators"
"github.com/google/cel-go/common/overloads"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// Implementations based on `google/cel-go`'s unparser
// https://github.com/google/cel-go/blob/master/parser/unparser.go
func Convert(ast *cel.Ast) (string, error) {
checkedExpr, err := cel.AstToCheckedExpr(ast)
if err != nil {
return "", err
}
un := &converter{
typeMap: checkedExpr.TypeMap,
}
if err := un.visit(checkedExpr.Expr); err != nil {
return "", err
}
return un.str.String(), nil
}
type converter struct {
str strings.Builder
typeMap map[int64]*exprpb.Type
}
func (con *converter) visit(expr *exprpb.Expr) error {
switch expr.ExprKind.(type) {
case *exprpb.Expr_CallExpr:
return con.visitCall(expr)
// TODO: Comprehensions are currently not supported.
case *exprpb.Expr_ComprehensionExpr:
return con.visitComprehension(expr)
case *exprpb.Expr_ConstExpr:
return con.visitConst(expr)
case *exprpb.Expr_IdentExpr:
return con.visitIdent(expr)
case *exprpb.Expr_ListExpr:
return con.visitList(expr)
case *exprpb.Expr_SelectExpr:
return con.visitSelect(expr)
case *exprpb.Expr_StructExpr:
return con.visitStruct(expr)
}
return fmt.Errorf("unsupported expr: %v", expr)
}
func (con *converter) visitCall(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
switch fun {
// ternary operator
case operators.Conditional:
return con.visitCallConditional(expr)
// index operator
case operators.Index:
return con.visitCallIndex(expr)
// unary operators
case operators.LogicalNot, operators.Negate:
return con.visitCallUnary(expr)
// binary operators
case operators.Add,
operators.Divide,
operators.Equals,
operators.Greater,
operators.GreaterEquals,
operators.In,
operators.Less,
operators.LessEquals,
operators.LogicalAnd,
operators.LogicalOr,
operators.Multiply,
operators.NotEquals,
operators.OldIn,
operators.Subtract:
return con.visitCallBinary(expr)
// standard function calls.
default:
return con.visitCallFunc(expr)
}
}
var standardSQLBinaryOperators = map[string]string{
operators.LogicalAnd: "AND",
operators.LogicalOr: "OR",
operators.Equals: "=",
operators.In: "IN",
}
func (con *converter) visitCallBinary(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
lhs := args[0]
// add parens if the current operator is lower precedence than the lhs expr operator.
lhsParen := isComplexOperatorWithRespectTo(fun, lhs)
rhs := args[1]
// add parens if the current operator is lower precedence than the rhs expr operator,
// or the same precedence and the operator is left recursive.
rhsParen := isComplexOperatorWithRespectTo(fun, rhs)
lhsType := con.getType(lhs)
rhsType := con.getType(rhs)
if (isTimestampRelatedType(lhsType) && isDurationRelatedType(rhsType)) ||
(isTimestampRelatedType(rhsType) && isDurationRelatedType(lhsType)) {
return con.callTimestampOperation(fun, lhs, rhs)
}
if !rhsParen && isLeftRecursive(fun) {
rhsParen = isSamePrecedence(fun, rhs)
}
if err := con.visitMaybeNested(lhs, lhsParen); err != nil {
return err
}
var operator string
if fun == operators.Add && (lhsType.GetPrimitive() == exprpb.Type_STRING && rhsType.GetPrimitive() == exprpb.Type_STRING) {
operator = "||"
} else if fun == operators.Add && (rhsType.GetPrimitive() == exprpb.Type_BYTES && lhsType.GetPrimitive() == exprpb.Type_BYTES) {
operator = "||"
} else if fun == operators.Add && (isListType(lhsType) && isListType(rhsType)) {
operator = "||"
} else if fun == operators.Equals && (isNullLiteral(rhs) || isBoolLiteral(rhs)) {
operator = "IS"
} else if fun == operators.NotEquals && (isNullLiteral(rhs) || isBoolLiteral(rhs)) {
operator = "IS NOT"
} else if op, found := standardSQLBinaryOperators[fun]; found {
operator = op
} else if op, found := operators.FindReverseBinaryOperator(fun); found {
operator = op
} else {
return fmt.Errorf("cannot unmangle operator: %s", fun)
}
con.str.WriteString(" ")
con.str.WriteString(operator)
con.str.WriteString(" ")
if fun == operators.In && isListType(rhsType) {
con.str.WriteString("UNNEST(")
}
if err := con.visitMaybeNested(rhs, rhsParen); err != nil {
return err
}
if fun == operators.In && isListType(rhsType) {
con.str.WriteString(")")
}
return nil
}
func isTimestampRelatedType(typ *exprpb.Type) bool {
abstractType := typ.GetAbstractType()
if abstractType != nil {
name := abstractType.GetName()
return name == "DATE" || name == "TIME" || name == "DATETIME"
}
return typ.GetWellKnown() == exprpb.Type_TIMESTAMP
}
func isDateType(typ *exprpb.Type) bool {
return typ.GetAbstractType() != nil && typ.GetAbstractType().GetName() == "DATE"
}
func isTimeType(typ *exprpb.Type) bool {
return typ.GetAbstractType() != nil && typ.GetAbstractType().GetName() == "TIME"
}
func isDateTimeType(typ *exprpb.Type) bool {
return typ.GetAbstractType() != nil && typ.GetAbstractType().GetName() == "DATETIME"
}
func isTimestampType(typ *exprpb.Type) bool {
return typ.GetWellKnown() == exprpb.Type_TIMESTAMP
}
func isDurationRelatedType(typ *exprpb.Type) bool {
abstractType := typ.GetAbstractType()
if abstractType != nil {
name := abstractType.GetName()
return name == "INTERVAL"
}
return typ.GetWellKnown() == exprpb.Type_DURATION
}
func (con *converter) callTimestampOperation(fun string, lhs *exprpb.Expr, rhs *exprpb.Expr) error {
lhsParen := isComplexOperatorWithRespectTo(fun, lhs)
rhsParen := isComplexOperatorWithRespectTo(fun, rhs)
lhsType := con.getType(lhs)
rhsType := con.getType(rhs)
var timestampType *exprpb.Type
var timestamp, duration *exprpb.Expr
var timestampParen, durationParen bool
switch {
case isTimestampRelatedType(lhsType):
timestampType = lhsType
timestamp, duration = lhs, rhs
timestampParen, durationParen = lhsParen, rhsParen
case isTimestampRelatedType(rhsType):
timestampType = rhsType
timestamp, duration = rhs, lhs
timestampParen, durationParen = rhsParen, lhsParen
default:
panic("lhs or rhs must be timestamp related type")
}
var sqlFun string
switch fun {
case operators.Add:
switch {
case isTimeType(timestampType):
sqlFun = "TIME_ADD"
case isDateType(timestampType):
sqlFun = "DATE_ADD"
case isDateTimeType(timestampType):
sqlFun = "DATETIME_ADD"
default:
sqlFun = "TIMESTAMP_ADD"
}
case operators.Subtract:
switch {
case isTimeType(timestampType):
sqlFun = "TIME_SUB"
case isDateType(timestampType):
sqlFun = "DATE_SUB"
case isDateTimeType(timestampType):
sqlFun = "DATETIME_SUB"
default:
sqlFun = "TIMESTAMP_SUB"
}
default:
return fmt.Errorf("unsupported operation (%s)", fun)
}
con.str.WriteString(sqlFun)
con.str.WriteString("(")
if err := con.visitMaybeNested(timestamp, timestampParen); err != nil {
return err
}
con.str.WriteString(", ")
if err := con.visitMaybeNested(duration, durationParen); err != nil {
return err
}
con.str.WriteString(")")
return nil
}
func (con *converter) visitCallConditional(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
con.str.WriteString("IF(")
if err := con.visit(args[0]); err != nil {
return err
}
con.str.WriteString(", ")
if err := con.visit(args[1]); err != nil {
return err
}
con.str.WriteString(", ")
if err := con.visit(args[2]); err != nil {
return nil
}
con.str.WriteString(")")
return nil
}
var standardSQLFunctions = map[string]string{
operators.Modulo: "MOD",
overloads.StartsWith: "STARTS_WITH",
overloads.EndsWith: "ENDS_WITH",
overloads.Matches: "REGEXP_CONTAINS",
}
func (con *converter) callContains(target *exprpb.Expr, args []*exprpb.Expr) error {
con.str.WriteString("INSTR(")
if target != nil {
nested := isBinaryOrTernaryOperator(target)
err := con.visitMaybeNested(target, nested)
if err != nil {
return err
}
con.str.WriteString(", ")
}
for i, arg := range args {
err := con.visit(arg)
if err != nil {
return err
}
if i < len(args)-1 {
con.str.WriteString(", ")
}
}
con.str.WriteString(") != 0")
return nil
}
func (con *converter) callDuration(target *exprpb.Expr, args []*exprpb.Expr) error {
if len(args) != 1 {
return fmt.Errorf("arguments must be single")
}
arg := args[0]
var durationString string
switch arg.ExprKind.(type) {
case *exprpb.Expr_ConstExpr:
switch arg.GetConstExpr().ConstantKind.(type) {
case *exprpb.Constant_StringValue:
durationString = arg.GetConstExpr().GetStringValue()
default:
return fmt.Errorf("unsupported constant kind %t", arg.GetConstExpr().ConstantKind)
}
default:
return fmt.Errorf("unsupported kind %t", arg.ExprKind)
}
d, err := time.ParseDuration(durationString)
if err != nil {
return err
}
con.str.WriteString("INTERVAL ")
switch d {
case d.Round(time.Hour):
con.str.WriteString(strconv.FormatFloat(d.Hours(), 'f', 0, 64))
con.str.WriteString(" HOUR")
case d.Round(time.Minute):
con.str.WriteString(strconv.FormatFloat(d.Minutes(), 'f', 0, 64))
con.str.WriteString(" MINUTE")
case d.Round(time.Second):
con.str.WriteString(strconv.FormatFloat(d.Seconds(), 'f', 0, 64))
con.str.WriteString(" SECOND")
case d.Round(time.Millisecond):
con.str.WriteString(strconv.FormatInt(d.Milliseconds(), 10))
con.str.WriteString(" MILLISECOND")
default:
con.str.WriteString(strconv.FormatInt(d.Truncate(time.Microsecond).Microseconds(), 10))
con.str.WriteString(" MICROSECOND")
}
return nil
}
func (con *converter) callInterval(target *exprpb.Expr, args []*exprpb.Expr) error {
con.str.WriteString("INTERVAL ")
if err := con.visit(args[0]); err != nil {
return err
}
con.str.WriteString(" ")
datePart := args[1]
con.str.WriteString(datePart.GetIdentExpr().GetName())
return nil
}
func (con *converter) callExtractFromTimestamp(function string, target *exprpb.Expr, args []*exprpb.Expr) error {
con.str.WriteString("EXTRACT(")
switch function {
case overloads.TimeGetFullYear:
con.str.WriteString("YEAR")
case overloads.TimeGetMonth:
con.str.WriteString("MONTH")
case overloads.TimeGetDate:
con.str.WriteString("DAY")
case overloads.TimeGetHours:
con.str.WriteString("HOUR")
case overloads.TimeGetMinutes:
con.str.WriteString("MINUTE")
case overloads.TimeGetSeconds:
con.str.WriteString("SECOND")
case overloads.TimeGetMilliseconds:
con.str.WriteString("MILLISECOND")
case overloads.TimeGetDayOfYear:
con.str.WriteString("DAYOFYEAR")
case overloads.TimeGetDayOfMonth:
con.str.WriteString("DAY")
case overloads.TimeGetDayOfWeek:
con.str.WriteString("DAYOFWEEK")
}
con.str.WriteString(" FROM ")
if err := con.visit(target); err != nil {
return err
}
if isTimestampType(con.getType(target)) && len(args) == 1 {
con.str.WriteString(" AT ")
if err := con.visit(args[0]); err != nil {
return err
}
}
con.str.WriteString(")")
if function == overloads.TimeGetMonth || function == overloads.TimeGetDayOfYear || function == overloads.TimeGetDayOfMonth || function == overloads.TimeGetDayOfWeek {
con.str.WriteString(" - 1")
}
return nil
}
func (con *converter) callCasting(function string, target *exprpb.Expr, args []*exprpb.Expr) error {
arg := args[0]
if function == overloads.TypeConvertInt && isTimestampType(con.getType(arg)) {
con.str.WriteString("UNIX_SECONDS(")
if err := con.visit(arg); err != nil {
return err
}
con.str.WriteString(")")
return nil
}
con.str.WriteString("CAST(")
if err := con.visit(arg); err != nil {
return err
}
con.str.WriteString(" AS ")
switch function {
case overloads.TypeConvertBool:
con.str.WriteString("BOOL")
case overloads.TypeConvertBytes:
con.str.WriteString("BYTES")
case overloads.TypeConvertDouble:
con.str.WriteString("FLOAT64")
case overloads.TypeConvertInt:
con.str.WriteString("INT64")
case overloads.TypeConvertString:
con.str.WriteString("STRING")
case overloads.TypeConvertUint:
con.str.WriteString("INT64")
}
con.str.WriteString(")")
return nil
}
func (con *converter) visitCallFunc(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
target := c.GetTarget()
args := c.GetArgs()
switch fun {
case overloads.Contains:
return con.callContains(target, args)
case overloads.TypeConvertDuration:
return con.callDuration(target, args)
case "interval":
return con.callInterval(target, args)
case overloads.TimeGetFullYear,
overloads.TimeGetMonth,
overloads.TimeGetDate,
overloads.TimeGetHours,
overloads.TimeGetMinutes,
overloads.TimeGetSeconds,
overloads.TimeGetMilliseconds,
overloads.TimeGetDayOfYear,
overloads.TimeGetDayOfMonth,
overloads.TimeGetDayOfWeek:
return con.callExtractFromTimestamp(fun, target, args)
case overloads.TypeConvertBool,
overloads.TypeConvertBytes,
overloads.TypeConvertDouble,
overloads.TypeConvertInt,
overloads.TypeConvertString,
overloads.TypeConvertUint:
return con.callCasting(fun, target, args)
}
sqlFun, ok := standardSQLFunctions[fun]
if !ok {
if fun == overloads.Size {
argType := con.getType(args[0])
switch {
case argType.GetPrimitive() == exprpb.Type_STRING:
sqlFun = "LENGTH"
case argType.GetPrimitive() == exprpb.Type_BYTES:
sqlFun = "LENGTH"
case isListType(argType):
sqlFun = "ARRAY_LENGTH"
default:
return fmt.Errorf("unsupported type: %v", argType)
}
} else {
sqlFun = strings.ToUpper(fun)
}
}
con.str.WriteString(sqlFun)
con.str.WriteString("(")
if target != nil {
nested := isBinaryOrTernaryOperator(target)
err := con.visitMaybeNested(target, nested)
if err != nil {
return err
}
con.str.WriteString(", ")
}
for i, arg := range args {
err := con.visit(arg)
if err != nil {
return err
}
if i < len(args)-1 {
con.str.WriteString(", ")
}
}
con.str.WriteString(")")
return nil
}
func (con *converter) visitCallIndex(expr *exprpb.Expr) error {
if isMapType(con.getType(expr.GetCallExpr().GetArgs()[0])) {
return con.visitCallMapIndex(expr)
}
return con.visitCallListIndex(expr)
}
func (con *converter) visitCallMapIndex(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
m := args[0]
nested := isBinaryOrTernaryOperator(m)
if err := con.visitMaybeNested(m, nested); err != nil {
return err
}
fieldName, err := extractFieldName(args[1])
if err != nil {
return err
}
con.str.WriteString(".`")
con.str.WriteString(fieldName)
con.str.WriteString("`")
return nil
}
func (con *converter) visitCallListIndex(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
args := c.GetArgs()
l := args[0]
nested := isBinaryOrTernaryOperator(l)
if err := con.visitMaybeNested(l, nested); err != nil {
return err
}
con.str.WriteString("[OFFSET(")
index := args[1]
if err := con.visit(index); err != nil {
return err
}
con.str.WriteString(")]")
return nil
}
var standardSQLUnaryOperators = map[string]string{
operators.LogicalNot: "NOT ",
}
func (con *converter) visitCallUnary(expr *exprpb.Expr) error {
c := expr.GetCallExpr()
fun := c.GetFunction()
args := c.GetArgs()
var operator string
if op, found := standardSQLUnaryOperators[fun]; found {
operator = op
} else if op, found := operators.FindReverse(fun); found {
operator = op
} else {
return fmt.Errorf("cannot unmangle operator: %s", fun)
}
con.str.WriteString(operator)
nested := isComplexOperator(args[0])
return con.visitMaybeNested(args[0], nested)
}
func (con *converter) visitComprehension(expr *exprpb.Expr) error {
// TODO: introduce a macro expansion map between the top-level comprehension id and the
// function call that the macro replaces.
return fmt.Errorf("unimplemented : %v", expr)
}
func (con *converter) visitConst(expr *exprpb.Expr) error {
c := expr.GetConstExpr()
switch c.ConstantKind.(type) {
case *exprpb.Constant_BoolValue:
if c.GetBoolValue() {
con.str.WriteString("TRUE")
} else {
con.str.WriteString("FALSE")
}
case *exprpb.Constant_BytesValue:
b := c.GetBytesValue()
con.str.WriteString(`b"`)
con.str.WriteString(bytesToOctets(b))
con.str.WriteString(`"`)
case *exprpb.Constant_DoubleValue:
d := strconv.FormatFloat(c.GetDoubleValue(), 'g', -1, 64)
con.str.WriteString(d)
case *exprpb.Constant_Int64Value:
i := strconv.FormatInt(c.GetInt64Value(), 10)
con.str.WriteString(i)
case *exprpb.Constant_NullValue:
con.str.WriteString("NULL")
case *exprpb.Constant_StringValue:
con.str.WriteString(strconv.Quote(c.GetStringValue()))
case *exprpb.Constant_Uint64Value:
ui := strconv.FormatUint(c.GetUint64Value(), 10)
con.str.WriteString(ui)
default:
return fmt.Errorf("unimplemented : %v", expr)
}
return nil
}
func (con *converter) visitIdent(expr *exprpb.Expr) error {
con.str.WriteString("`")
con.str.WriteString(expr.GetIdentExpr().GetName())
con.str.WriteString("`")
return nil
}
func (con *converter) visitList(expr *exprpb.Expr) error {
l := expr.GetListExpr()
elems := l.GetElements()
con.str.WriteString("[")
for i, elem := range elems {
err := con.visit(elem)
if err != nil {
return err
}
if i < len(elems)-1 {
con.str.WriteString(", ")
}
}
con.str.WriteString("]")
return nil
}
func (con *converter) visitSelect(expr *exprpb.Expr) error {
sel := expr.GetSelectExpr()
// handle the case when the select expression was generated by the has() macro.
if sel.GetTestOnly() {
con.str.WriteString("has(")
}
nested := !sel.GetTestOnly() && isBinaryOrTernaryOperator(sel.GetOperand())
err := con.visitMaybeNested(sel.GetOperand(), nested)
if err != nil {
return err
}
con.str.WriteString(".`")
con.str.WriteString(sel.GetField())
con.str.WriteString("`")
if sel.GetTestOnly() {
con.str.WriteString(")")
}
return nil
}
func (con *converter) visitStruct(expr *exprpb.Expr) error {
s := expr.GetStructExpr()
// If the message name is non-empty, then this should be treated as message construction.
if s.GetMessageName() != "" {
return con.visitStructMsg(expr)
}
// Otherwise, build a map.
return con.visitStructMap(expr)
}
func (con *converter) visitStructMsg(expr *exprpb.Expr) error {
m := expr.GetStructExpr()
entries := m.GetEntries()
con.str.WriteString(m.GetMessageName())
con.str.WriteString("{")
for i, entry := range entries {
f := entry.GetFieldKey()
con.str.WriteString(f)
con.str.WriteString(": ")
v := entry.GetValue()
err := con.visit(v)
if err != nil {
return err
}
if i < len(entries)-1 {
con.str.WriteString(", ")
}
}
con.str.WriteString("}")
return nil
}
func (con *converter) visitStructMap(expr *exprpb.Expr) error {
m := expr.GetStructExpr()
entries := m.GetEntries()
con.str.WriteString("STRUCT(")
for i, entry := range entries {
v := entry.GetValue()
if err := con.visit(v); err != nil {
return err
}
con.str.WriteString(" AS ")
fieldName, err := extractFieldName(entry.GetMapKey())
if err != nil {
return err
}
con.str.WriteString(fieldName)
if i < len(entries)-1 {
con.str.WriteString(", ")
}
}
con.str.WriteString(")")
return nil
}
func (con *converter) visitMaybeNested(expr *exprpb.Expr, nested bool) error {
if nested {
con.str.WriteString("(")
}
err := con.visit(expr)
if err != nil {
return err
}
if nested {
con.str.WriteString(")")
}
return nil
}
func (con *converter) getType(node *exprpb.Expr) *exprpb.Type {
return con.typeMap[node.GetId()]
}
func isMapType(typ *exprpb.Type) bool {
_, ok := typ.TypeKind.(*exprpb.Type_MapType_)
return ok
}
func isListType(typ *exprpb.Type) bool {
_, ok := typ.TypeKind.(*exprpb.Type_ListType_)
return ok
}
// isLeftRecursive indicates whether the parser resolves the call in a left-recursive manner as
// this can have an effect of how parentheses affect the order of operations in the AST.
func isLeftRecursive(op string) bool {
return op != operators.LogicalAnd && op != operators.LogicalOr
}
// isSamePrecedence indicates whether the precedence of the input operator is the same as the
// precedence of the (possible) operation represented in the input Expr.
//
// If the expr is not a Call, the result is false.
func isSamePrecedence(op string, expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil {
return false
}
c := expr.GetCallExpr()
other := c.GetFunction()
return operators.Precedence(op) == operators.Precedence(other)
}
// isLowerPrecedence indicates whether the precedence of the input operator is lower precedence
// than the (possible) operation represented in the input Expr.
//
// If the expr is not a Call, the result is false.
func isLowerPrecedence(op string, expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil {
return false
}
c := expr.GetCallExpr()
other := c.GetFunction()
return operators.Precedence(op) < operators.Precedence(other)
}
// Indicates whether the expr is a complex operator, i.e., a call expression
// with 2 or more arguments.
func isComplexOperator(expr *exprpb.Expr) bool {
if expr.GetCallExpr() != nil && len(expr.GetCallExpr().GetArgs()) >= 2 {
return true
}
return false
}
// Indicates whether it is a complex operation compared to another.
// expr is *not* considered complex if it is not a call expression or has
// less than two arguments, or if it has a higher precedence than op.
func isComplexOperatorWithRespectTo(op string, expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil || len(expr.GetCallExpr().GetArgs()) < 2 {
return false
}
return isLowerPrecedence(op, expr)
}
// Indicate whether this is a binary or ternary operator.
func isBinaryOrTernaryOperator(expr *exprpb.Expr) bool {
if expr.GetCallExpr() == nil || len(expr.GetCallExpr().GetArgs()) < 2 {
return false
}
_, isBinaryOp := operators.FindReverseBinaryOperator(expr.GetCallExpr().GetFunction())
return isBinaryOp || isSamePrecedence(operators.Conditional, expr)
}
func isNullLiteral(node *exprpb.Expr) bool {
_, isConst := node.ExprKind.(*exprpb.Expr_ConstExpr)
if !isConst {
return false
}
_, isNull := node.GetConstExpr().ConstantKind.(*exprpb.Constant_NullValue)
return isNull
}
func isBoolLiteral(node *exprpb.Expr) bool {
_, isConst := node.ExprKind.(*exprpb.Expr_ConstExpr)
if !isConst {
return false
}
_, isBool := node.GetConstExpr().ConstantKind.(*exprpb.Constant_BoolValue)
return isBool
}
func isStringLiteral(node *exprpb.Expr) bool {
_, isConst := node.ExprKind.(*exprpb.Expr_ConstExpr)
if !isConst {
return false
}
_, isString := node.GetConstExpr().ConstantKind.(*exprpb.Constant_StringValue)
return isString
}
// bytesToOctets converts byte sequences to a string using a three digit octal encoded value
// per byte.
func bytesToOctets(byteVal []byte) string {
var b strings.Builder
for _, c := range byteVal {
_, _ = fmt.Fprintf(&b, "\\%03o", c)
}
return b.String()
}
var fieldNameRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]{0,127}$`)
func validateFieldName(name string) error {
if !fieldNameRegexp.MatchString(name) {
return fmt.Errorf("invalid field name \"%s\"", name)
}
return nil
}
func extractFieldName(node *exprpb.Expr) (string, error) {
if !isStringLiteral(node) {
return "", fmt.Errorf("unsupported type: %v", node)
}
fieldName := node.GetConstExpr().GetStringValue()
if err := validateFieldName(fieldName); err != nil {
return "", err
}
return fieldName, nil
}