forked from ulule/loukoum
/
where.go
61 lines (50 loc) · 1.44 KB
/
where.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
package stmt
import (
"github.com/ulule/loukoum/token"
"github.com/ulule/loukoum/types"
)
// Where is a WHERE clause.
type Where struct {
Condition Expression
}
// NewWhere returns a new Where instance.
func NewWhere(expression Expression) Where {
return Where{
Condition: NewWrapper(expression),
}
}
// Write exposes statement as a SQL query.
func (where Where) Write(ctx types.Context) {
if where.IsEmpty() {
panic("loukoum: a where clause expects at least one condition")
}
ctx.Write(token.Where.String())
ctx.Write(" ")
where.Condition.Write(ctx)
}
// IsEmpty returns true if statement is undefined.
func (where Where) IsEmpty() bool {
return where.Condition == nil || where.Condition.IsEmpty()
}
// And appends given Expression using AND as logical operator.
func (where Where) And(right Expression) Where {
if where.IsEmpty() {
panic("loukoum: two conditions are required for AND statement")
}
left := where.Condition
operator := NewAndOperator()
where.Condition = NewInfixExpression(left, operator, NewWrapper(right))
return where
}
// Or appends given Expression using OR as logical operator.
func (where Where) Or(right Expression) Where {
if where.IsEmpty() {
panic("loukoum: two conditions are required for OR statement")
}
left := where.Condition
operator := NewOrOperator()
where.Condition = NewInfixExpression(left, operator, NewWrapper(right))
return where
}
// Ensure that Where is a Statement
var _ Statement = Where{}