-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathbinary.go
More file actions
77 lines (61 loc) · 1.47 KB
/
binary.go
File metadata and controls
77 lines (61 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package sqltypes
import (
"strings"
"golang.org/x/xerrors"
)
type binaryOperator int
const (
_ binaryOperator = iota
binaryOpOR
binaryOpAND
)
type binaryOp struct {
source RegoSource
op binaryOperator
Terms []BooleanNode
}
func (binaryOp) UseAs() Node { return binaryOp{} }
func (binaryOp) IsBooleanNode() {}
func Or(source RegoSource, terms ...BooleanNode) BooleanNode {
return newBinaryOp(source, binaryOpOR, terms...)
}
func And(source RegoSource, terms ...BooleanNode) BooleanNode {
return newBinaryOp(source, binaryOpAND, terms...)
}
func newBinaryOp(source RegoSource, op binaryOperator, terms ...BooleanNode) BooleanNode {
if len(terms) == 0 {
// TODO: How to handle 0 terms?
return Bool(false)
}
opTerms := make([]BooleanNode, 0, len(terms))
for i := range terms {
// Always wrap terms in parentheses to be safe.
opTerms = append(opTerms, BoolParenthesis(terms[i]))
}
if len(opTerms) == 1 {
return opTerms[0]
}
return binaryOp{
Terms: opTerms,
op: op,
source: source,
}
}
func (b binaryOp) SQLString(cfg *SQLGenerator) string {
sqlOp := ""
switch b.op {
case binaryOpOR:
sqlOp = "OR"
case binaryOpAND:
sqlOp = "AND"
default:
cfg.AddError(xerrors.Errorf("unsupported binary operator: %s (%d)", b.source, b.op))
return "BinaryOpError"
}
terms := make([]string, 0, len(b.Terms))
for _, term := range b.Terms {
termSQL := term.SQLString(cfg)
terms = append(terms, termSQL)
}
return strings.Join(terms, " "+sqlOp+" ")
}