-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
96 lines (76 loc) · 1.74 KB
/
ast.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
package greasel
import (
"fmt"
"strings"
)
// Intermediate ast representing a sql query
// Filters
type Expression interface {
SQL(q *Query) string
Params() []interface{}
}
type Filter interface {
Expression
}
type CombinedFilter struct {
Sep string // AND, OR
Filters []Filter
}
func And(filters ...Filter) Filter {
return CombinedFilter{
Sep: " AND ",
Filters: filters,
}
}
func Or(filters ...Filter) Filter {
return CombinedFilter{
Sep: " OR ",
Filters: filters,
}
}
func (f CombinedFilter) SQL(q *Query) string {
clauses := make([]string, len(f.Filters))
for i, filter := range f.Filters {
clauses[i] = filter.SQL(q)
}
return "(" + strings.Join(clauses, f.Sep) + ") "
}
func (f CombinedFilter) Params() []interface{} {
params := make([]interface{}, 0, len(f.Filters))
for _, filter := range f.Filters {
params = append(params, filter.Params()...)
}
return params
}
type ValueComparisonFilter struct {
Lhs *Field
Op string
Rhs interface{} // value, field, or expression(?)
}
func (f ValueComparisonFilter) SQL(q *Query) string {
return fmt.Sprintf("%s %s ? ", q.falias(f.Lhs), f.Op)
}
func (f ValueComparisonFilter) Params() []interface{} {
return []interface{}{f.Rhs}
}
type FieldComparisonFilter struct {
Lhs *Field
Op string
Rhs *Field
}
func (f FieldComparisonFilter) SQL(q *Query) string {
return fmt.Sprintf("%s %s %s ", q.falias(f.Lhs), f.Op, q.falias(f.Rhs))
}
func (f FieldComparisonFilter) Params() []interface{} {
return []interface{}{}
}
// Joins
type Join struct {
Type string // Inner, Left
//Field *Field ??
JoinTable *Table
Filter Filter
}
func (j Join) SQL(q *Query) string {
return fmt.Sprintf("%s JOIN %s AS %s ON %s ", j.Type, j.JoinTable.source, q.alias(j.JoinTable), j.Filter.SQL(q))
}