-
Notifications
You must be signed in to change notification settings - Fork 0
/
operators.go
127 lines (108 loc) · 2.52 KB
/
operators.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
package pgtalk
import (
"fmt"
"strings"
)
const (
validComparisonOperators = "= > < >= <= <>"
)
type binaryExpression struct {
Operator string
Left SQLExpression
Right SQLExpression
}
func (o binaryExpression) SQLOn(w WriteContext) {
fmt.Fprint(w, "(")
o.Left.SQLOn(w)
// inline comparison operators
if strings.Contains(validComparisonOperators, o.Operator) {
fmt.Fprintf(w, " ")
} else {
fmt.Fprintf(w, "\n\t")
}
fmt.Fprintf(w, "%s ", o.Operator)
o.Right.SQLOn(w)
fmt.Fprint(w, ")")
}
func makeBinaryOperator(left SQLExpression, operator string, right SQLExpression) binaryExpression {
return binaryExpression{
Left: left,
Operator: operator,
Right: right,
}
}
func (o binaryExpression) And(right SQLExpression) SQLExpression {
return binaryExpression{
Left: o,
Operator: "AND",
Right: right,
}
}
func (o binaryExpression) Or(right SQLExpression) SQLExpression {
return binaryExpression{
Left: o,
Operator: "OR",
Right: right,
}
}
func (o binaryExpression) Like(pattern string) SQLExpression {
return binaryExpression{
Left: o,
Operator: "LIKE",
Right: valuePrinter{v: pattern},
}
}
type betweenAnd struct {
}
func makeBetweenAnd(_ ColumnAccessor, _, _ SQLExpression) betweenAnd { return betweenAnd{} }
type unaryExpression struct {
Operator string
Operand SQLExpression
}
func (u unaryExpression) SQLOn(w WriteContext) {
fmt.Fprintf(w, "%s (", u.Operator)
u.Operand.SQLOn(w)
fmt.Fprint(w, ")")
}
func (u unaryExpression) And(right SQLExpression) SQLExpression {
return binaryExpression{
Left: u,
Operator: "AND",
Right: right,
}
}
func (u unaryExpression) Or(right SQLExpression) SQLExpression {
return binaryExpression{
Left: u,
Operator: "OR",
Right: right,
}
}
type nullCheck struct {
Operand SQLExpression
// IsNot == true -> IS NOT NULL
IsNot bool
}
func (n nullCheck) SQLOn(w WriteContext) {
fmt.Fprint(w, "(")
n.Operand.SQLOn(w)
if n.IsNot {
fmt.Fprint(w, " IS NOT NULL)")
return
}
fmt.Fprint(w, " IS NULL)")
}
func (n nullCheck) And(right SQLExpression) SQLExpression {
return makeBinaryOperator(n, "AND", right)
}
func (n nullCheck) Or(right SQLExpression) SQLExpression {
return makeBinaryOperator(n, "OR", right)
}
// IsNotNull returns an expression with the IS NOT NULL condition
func IsNotNull(e SQLExpression) nullCheck {
return nullCheck{Operand: e, IsNot: true}
}
// IsNull returns an expression with the IS NULL condition
func IsNull(e SQLExpression) nullCheck {
return nullCheck{Operand: e, IsNot: false}
}