forked from slicebit/qb
-
Notifications
You must be signed in to change notification settings - Fork 2
/
select.go
385 lines (335 loc) · 10.3 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package qb
import "fmt"
// Selectable is any clause from which we can select columns and is suitable
// as a FROM clause element
type Selectable interface {
Clause
All() []Clause
ColumnList() []ColumnElem
C(column string) ColumnElem
DefaultName() string
}
// Select generates a select statement and returns it
func Select(clauses ...Clause) SelectStmt {
return SelectStmt{
SelectList: clauses,
GroupByClause: []ColumnElem{},
HavingClause: []HavingClause{},
}
}
// SelectStmt is the base struct for building select statements
type SelectStmt struct {
SelectList []Clause
FromClause Selectable
GroupByClause []ColumnElem
OrderByClause *OrderByClause
HavingClause []HavingClause
WhereClause *WhereClause
ForUpdateClause *ForUpdateClause
OffsetValue *int
LimitValue *int
}
// Select sets the selected columns
func (s SelectStmt) Select(clauses ...Clause) SelectStmt {
s.SelectList = clauses
return s
}
// From sets the from selectable of select statement
func (s SelectStmt) From(selectable Selectable) SelectStmt {
s.FromClause = selectable
return s
}
// Where sets the where clause of select statement
func (s SelectStmt) Where(clauses ...Clause) SelectStmt {
where := Where(clauses...)
s.WhereClause = &where
return s
}
// InnerJoin appends an inner join clause to the select statement
func (s SelectStmt) InnerJoin(right Selectable, onClause ...Clause) SelectStmt {
return s.From(Join("INNER JOIN", s.FromClause, right, onClause...))
}
// CrossJoin appends an cross join clause to the select statement
func (s SelectStmt) CrossJoin(right Selectable) SelectStmt {
return s.From(Join("CROSS JOIN", s.FromClause, right, nil))
}
// LeftJoin appends an left outer join clause to the select statement
func (s SelectStmt) LeftJoin(right Selectable, onClause ...Clause) SelectStmt {
return s.From(Join("LEFT OUTER JOIN", s.FromClause, right, onClause...))
}
// RightJoin appends a right outer join clause to select statement
func (s SelectStmt) RightJoin(right Selectable, onClause ...Clause) SelectStmt {
return s.From(Join("RIGHT OUTER JOIN", s.FromClause, right, onClause...))
}
// OrderBy generates an OrderByClause and sets select statement's orderbyclause
// OrderBy(usersTable.C("id")).Asc()
// OrderBy(usersTable.C("email")).Desc()
func (s SelectStmt) OrderBy(columns ...ColumnElem) SelectStmt {
s.OrderByClause = &OrderByClause{columns, "ASC"}
return s
}
// Asc sets the t type of current order by clause
// NOTE: Please use it after calling OrderBy()
func (s SelectStmt) Asc() SelectStmt {
s.OrderByClause.t = "ASC"
return s
}
// Desc sets the t type of current order by clause
// NOTE: Please use it after calling OrderBy()
func (s SelectStmt) Desc() SelectStmt {
s.OrderByClause.t = "DESC"
return s
}
// GroupBy appends columns to group by clause of the select statement
func (s SelectStmt) GroupBy(cols ...ColumnElem) SelectStmt {
s.GroupByClause = append(s.GroupByClause, cols...)
return s
}
// Having appends a having clause to select statement
func (s SelectStmt) Having(aggregate AggregateClause, op string, value interface{}) SelectStmt {
s.HavingClause = append(s.HavingClause, HavingClause{aggregate, op, value})
return s
}
// Limit sets the limit number of rows
func (s SelectStmt) Limit(limit int) SelectStmt {
s.LimitValue = &limit
return s
}
// Offset sets the offset
func (s SelectStmt) Offset(value int) SelectStmt {
s.OffsetValue = &value
return s
}
// LimitOffset sets the limit & offset values of the select statement
func (s SelectStmt) LimitOffset(limit, offset int) SelectStmt {
s.LimitValue = &limit
s.OffsetValue = &offset
return s
}
// ForUpdate adds a "FOR UPDATE" clause
func (s SelectStmt) ForUpdate(tables ...TableElem) SelectStmt {
s.ForUpdateClause = &ForUpdateClause{tables}
return s
}
// Accept calls the compiler VisitSelect method
func (s SelectStmt) Accept(context Context) string {
return context.Compiler().VisitSelect(context, s)
}
// Build compiles the select statement and returns the Stmt
func (s SelectStmt) Build(dialect Dialect) *Stmt {
context := NewCompilerContext(dialect)
statement := Statement()
statement.AddSQLClause(s.Accept(context))
statement.AddBinding(context.Binds()...)
return statement
}
type joinOnClauseCandidate struct {
source TableElem
fkey ForeignKeyConstraint
target TableElem
}
func getTable(sel Selectable) (TableElem, bool) {
switch t := sel.(type) {
case TableElem:
return t, true
case *TableElem:
return *t, true
default:
return TableElem{}, false
}
}
// GuessJoinOnClause finds a join 'ON' clause between two tables
func GuessJoinOnClause(left Selectable, right Selectable) Clause {
leftTable, ok := getTable(left)
if !ok {
panic("left Selectable is not a Table: Cannot guess join onClause")
}
rightTable, ok := getTable(right)
if !ok {
panic("right Selectable is not a Table: Cannot guess join onClause")
}
var candidates []joinOnClauseCandidate
for _, fkey := range leftTable.ForeignKeyConstraints.FKeys {
if fkey.RefTable != rightTable.Name {
continue
}
candidates = append(
candidates,
joinOnClauseCandidate{leftTable, fkey, rightTable})
}
for _, fkey := range rightTable.ForeignKeyConstraints.FKeys {
if fkey.RefTable != leftTable.Name {
continue
}
candidates = append(
candidates,
joinOnClauseCandidate{rightTable, fkey, leftTable})
}
switch len(candidates) {
case 0:
panic(fmt.Sprintf(
"No foreign keys found between %s and %s",
leftTable.Name, rightTable.Name))
case 1:
candidate := candidates[0]
var clauses []Clause
for i, col := range candidate.fkey.Cols {
refCol := candidate.fkey.RefCols[i]
clauses = append(
clauses,
Eq(candidate.source.C(col), candidate.target.C(refCol)),
)
}
if len(clauses) == 1 {
return clauses[0]
}
return And(clauses...)
default:
panic(fmt.Sprintf(
"Found %d foreign keys between %s and %s",
len(candidates), leftTable.Name, rightTable.Name))
}
}
// MakeJoinOnClause assemble a 'ON' clause for a join from either:
// 0 clause: attempt to guess the join clause (only if left & right are tables),
// otherwise panics
// 1 clause: returns it
// 2 clauses: returns a Eq() of both
// otherwise if panics
func MakeJoinOnClause(left Selectable, right Selectable, onClause ...Clause) Clause {
switch len(onClause) {
case 0:
return GuessJoinOnClause(left, right)
case 1:
return onClause[0]
case 2:
return Eq(onClause[0], onClause[1])
default:
panic("Cannot make a join condition with more than 2 clauses")
}
}
// Join returns a new JoinClause
// onClause can be one of:
// - 0 clause: attempt to guess the join clause (only if left & right are tables),
// otherwise panics
// - 1 clause: use it directly
// - 2 clauses: use a Eq() of both
func Join(joinType string, left Selectable, right Selectable, onClause ...Clause) JoinClause {
return JoinClause{
JoinType: joinType,
Left: left,
Right: right,
OnClause: MakeJoinOnClause(left, right, onClause...),
}
}
// JoinClause is the base struct for generating join clauses when using select
// It satisfies Clause interface
type JoinClause struct {
JoinType string
Left Selectable
Right Selectable
OnClause Clause
}
// Accept calls the compiler VisitJoin method
func (c JoinClause) Accept(context Context) string {
return context.Compiler().VisitJoin(context, c)
}
// All returns the columns from both sides of the join
func (c JoinClause) All() []Clause {
return append(c.Left.All(), c.Right.All()...)
}
// ColumnList returns the columns from both sides of the join
func (c JoinClause) ColumnList() []ColumnElem {
return append(c.Left.ColumnList(), c.Right.ColumnList()...)
}
// C returns the first column with the given name
// If columns from both sides of the join match the name,
// the one from the left side will be returned.
func (c JoinClause) C(name string) ColumnElem {
for _, c := range c.ColumnList() {
if c.Name == name {
return c
}
}
panic(fmt.Sprintf("No such column '%s' in join %v", name, c))
}
// DefaultName returns an empty string because Joins have no name by default
func (c JoinClause) DefaultName() string {
return ""
}
// OrderByClause is the base struct for generating order by clauses when using select
// It satisfies SQLClause interface
type OrderByClause struct {
columns []ColumnElem
t string
}
// Accept generates an order by clause
func (c OrderByClause) Accept(context Context) string {
return context.Compiler().VisitOrderBy(context, c)
}
// HavingClause is the base struct for generating having clauses when using select
// It satisfies SQLClause interface
type HavingClause struct {
aggregate AggregateClause
op string
value interface{}
}
// Accept calls the compiler VisitHaving function
func (c HavingClause) Accept(context Context) string {
return context.Compiler().VisitHaving(context, c)
}
// ForUpdateClause is a FOR UPDATE expression
type ForUpdateClause struct {
Tables []TableElem
}
// Accept calls the compiler VisitForUpdate method
func (s ForUpdateClause) Accept(context Context) string {
return context.Compiler().VisitForUpdate(context, s)
}
// Alias returns a new AliasClause
func Alias(name string, selectable Selectable) AliasClause {
return AliasClause{
Name: name,
Selectable: selectable,
}
}
// AliasClause is a ALIAS sql clause
type AliasClause struct {
Name string
Selectable Selectable
}
// Accept calls the compiler VisitAlias function
func (c AliasClause) Accept(context Context) string {
return context.Compiler().VisitAlias(context, c)
}
// C returns the aliased selectable column with the given name.
// Before returning it, the 'Table' field is updated with alias
// name so that they can be used in Select()
func (c AliasClause) C(name string) ColumnElem {
col := c.Selectable.C(name)
col.Table = c.Name
return col
}
// All returns the aliased selectable columns with their "Table"
// field updated with the alias name
func (c AliasClause) All() []Clause {
var clauses []Clause
for _, col := range c.ColumnList() {
clauses = append(clauses, col)
}
return clauses
}
// ColumnList returns the aliased selectable columns with their "Table"
// field updated with the alias name
func (c AliasClause) ColumnList() []ColumnElem {
var cols []ColumnElem
for _, col := range c.Selectable.ColumnList() {
col.Table = c.Name
cols = append(cols, col)
}
return cols
}
// DefaultName returns the alias name
func (c AliasClause) DefaultName() string {
return c.Name
}