This repository has been archived by the owner on Nov 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.go
215 lines (187 loc) · 4.87 KB
/
select.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
package chem
import (
"database/sql"
"fmt"
"reflect"
"strings"
)
type nullableInt struct {
value int
valid bool
}
type SelectStmt struct {
columns []Column
filters []Filter
orderings []Ordering
limit nullableInt
offset nullableInt
}
func Select(columnThings ...Columnser) SelectStmt {
columns := make([]Column, 0, len(columnThings))
for _, c := range columnThings {
columns = append(columns, c.Columns()...)
}
return SelectStmt{columns: columns}
}
func (stmt SelectStmt) Where(filters ...Filter) SelectStmt {
stmt.filters = append(stmt.filters, filters...)
return stmt
}
func (stmt SelectStmt) OrderBy(orderings ...Ordering) SelectStmt {
stmt.orderings = append(stmt.orderings, orderings...)
return stmt
}
func (stmt SelectStmt) Limit(limit int) SelectStmt {
stmt.limit = nullableInt{value: limit, valid: true}
return stmt
}
func (stmt SelectStmt) Offset(offset int) SelectStmt {
stmt.offset = nullableInt{value: offset, valid: true}
return stmt
}
func toTableNames(columns []Column) []string {
names := make(map[string]bool)
for _, column := range columns {
names[column.Table().Name()] = true
}
nameList := make([]string, 0, len(names))
for name := range names {
nameList = append(nameList, name)
}
return nameList
}
func toColumnExpressions(columns []Column, withTableName bool) (out []string) {
for _, column := range columns {
out = append(out, column.toColumnExpression(withTableName))
}
return
}
func flattenValues(values []interface{}) []interface{} {
out := make([]interface{}, 0, len(values))
flattened := false
for _, value := range values {
reflection := reflect.ValueOf(value).Elem()
reflectType := reflection.Type()
switch reflectType.Kind() {
case reflect.Struct:
for i := 0; i < reflection.NumField(); i++ {
// flatten this struct into pointers to each field of it
out = append(out, reflection.Field(i).Addr().Interface())
}
flattened = true
default:
out = append(out, value)
}
}
// if we ever flattened any structs, there could be nested structs, so let's recurse
if flattened {
return flattenValues(out)
}
// otherwise we're done
return out
}
func makeWhereClause(f Filter, withTableNames bool) string {
expression := f.toBooleanExpression(withTableNames)
if expression == "" {
return ""
}
return fmt.Sprintf("WHERE %v", expression)
}
func makeOrderByClause(orderings []Ordering, fullyQualifyColumns bool) string {
if len(orderings) == 0 {
return ""
}
expressionList := make([]string, len(orderings))
for i, ordering := range orderings {
expressionList[i] = ordering.toOrderingExpression(fullyQualifyColumns)
}
return fmt.Sprintf(
"ORDER BY %v",
strings.Join(expressionList, ", "),
)
}
func makeOffsetClause(offset nullableInt) string {
if !offset.valid {
return ""
}
return fmt.Sprintf("OFFSET %v", offset.value)
}
func makeLimitClause(limit nullableInt, offset nullableInt) string {
if !limit.valid {
return ""
}
return strings.Join(
filterEmptyStrings(
fmt.Sprintf("LIMIT %v", limit.value),
makeOffsetClause(offset),
),
" ",
)
}
func (stmt SelectStmt) prepareStmt(db DB) (*sql.Stmt, error) {
tableNames := toTableNames(stmt.columns)
fullyQualifyColumns := (len(tableNames) > 1)
return db.Prepare(
strings.Join(
filterEmptyStrings(
fmt.Sprintf(
"SELECT %v FROM %v",
strings.Join(toColumnExpressions(stmt.columns, fullyQualifyColumns), ", "),
strings.Join(tableNames, ", "),
),
makeWhereClause(AND(stmt.filters...), fullyQualifyColumns),
makeOrderByClause(stmt.orderings, fullyQualifyColumns),
makeLimitClause(stmt.limit, stmt.offset),
),
" ",
),
)
}
func (stmt SelectStmt) First(db DB, values ...interface{}) error {
preparedStmt, err := stmt.prepareStmt(db)
if err != nil {
return err
}
return preparedStmt.QueryRow(
AND(stmt.filters...).binds()...,
).Scan(flattenValues(values)...)
}
func (stmt SelectStmt) All(db DB, values ...interface{}) error {
reflections := make([]reflect.Value, len(values))
for i, value := range values {
reflection := reflect.ValueOf(value).Elem()
reflectType := reflection.Type()
if reflectType.Kind() != reflect.Slice {
return NonSliceError{
Type: reflectType,
}
}
reflections[i] = reflection
}
preparedStmt, err := stmt.prepareStmt(db)
if err != nil {
return err
}
rows, err := preparedStmt.Query(
AND(stmt.filters...).binds()...,
)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
// create new slice element value(s) to scan the database row into
rowValues := make([]interface{}, len(reflections))
for i, reflection := range reflections {
rowValues[i] = reflect.New(reflection.Type().Elem()).Interface()
}
err = rows.Scan(flattenValues(rowValues)...)
if err != nil {
return err
}
for i, rowValue := range rowValues {
reflections[i].Set(reflect.Append(reflections[i], reflect.ValueOf(rowValue).Elem()))
}
}
return rows.Err()
}