-
Notifications
You must be signed in to change notification settings - Fork 28
/
select.go
728 lines (636 loc) · 15.9 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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
package sqlingo
import (
"context"
"errors"
"reflect"
"strconv"
"strings"
)
type selectWithFields interface {
toSelectWithContext
toSelectFinal
From(tables ...Table) selectWithTables
}
type selectWithTables interface {
toSelectJoin
toSelectWhere
toSelectWithLock
toSelectWithContext
toSelectFinal
toUnionSelect
GroupBy(expressions ...Expression) selectWithGroupBy
OrderBy(orderBys ...OrderBy) selectWithOrder
Limit(limit int) selectWithLimit
}
type toSelectJoin interface {
Join(table Table) selectWithJoin
LeftJoin(table Table) selectWithJoin
RightJoin(table Table) selectWithJoin
NaturalJoin(table Table) selectWithJoinOn
}
type selectWithJoin interface {
On(condition BooleanExpression) selectWithJoinOn
}
type selectWithJoinOn interface {
toSelectWhere
toSelectWithLock
toSelectWithContext
toSelectFinal
toUnionSelect
toSelectJoin
GroupBy(expressions ...Expression) selectWithGroupBy
OrderBy(orderBys ...OrderBy) selectWithOrder
Limit(limit int) selectWithLimit
}
type toSelectWhere interface {
Where(conditions ...BooleanExpression) selectWithWhere
WhereIf(prerequisite bool, conditions ...BooleanExpression) selectWithWhere
}
type selectWithWhere interface {
toSelectWhere
toSelectWithLock
toSelectWithContext
toSelectFinal
toUnionSelect
GroupBy(expressions ...Expression) selectWithGroupBy
OrderBy(orderBys ...OrderBy) selectWithOrder
Limit(limit int) selectWithLimit
}
type selectWithGroupBy interface {
toSelectWithLock
toSelectWithContext
toSelectFinal
toUnionSelect
Having(conditions ...BooleanExpression) selectWithGroupByHaving
OrderBy(orderBys ...OrderBy) selectWithOrder
Limit(limit int) selectWithLimit
}
type selectWithGroupByHaving interface {
toSelectWithLock
toSelectWithContext
toSelectFinal
toUnionSelect
OrderBy(orderBys ...OrderBy) selectWithOrder
}
type selectWithOrder interface {
toSelectWithLock
toSelectWithContext
toSelectFinal
Limit(limit int) selectWithLimit
}
type selectWithLimit interface {
toSelectWithLock
toSelectWithContext
toSelectFinal
Offset(offset int) selectWithOffset
}
type selectWithOffset interface {
toSelectWithLock
toSelectWithContext
toSelectFinal
}
type toSelectWithLock interface {
LockInShareMode() selectWithLock
ForUpdate() selectWithLock
ForUpdateNoWait() selectWithLock
ForUpdateSkipLocked() selectWithLock
}
type selectWithLock interface {
toSelectWithContext
toSelectFinal
}
type toSelectWithContext interface {
WithContext(ctx context.Context) toSelectFinal
}
type toUnionSelect interface {
UnionSelect(fields ...interface{}) selectWithFields
UnionSelectFrom(tables ...Table) selectWithTables
UnionSelectDistinct(fields ...interface{}) selectWithFields
UnionAllSelect(fields ...interface{}) selectWithFields
UnionAllSelectFrom(tables ...Table) selectWithTables
UnionAllSelectDistinct(fields ...interface{}) selectWithFields
}
type toSelectFinal interface {
Exists() (bool, error)
Count() (int, error)
GetSQL() (string, error)
FetchFirst(out ...interface{}) (bool, error)
FetchExactlyOne(out ...interface{}) error
FetchAll(dest ...interface{}) (rows int, err error)
FetchCursor() (Cursor, error)
FetchSeq() func(yield func(row Scanner) bool) // use with "range over function" in Go 1.22
}
type join struct {
previous *join
prefix string
table Table
on BooleanExpression
}
type selectBase struct {
scope scope
distinct bool
fields fieldList
where BooleanExpression
groupBys []Expression
having BooleanExpression
}
type selectStatus struct {
base selectBase
orderBys []OrderBy
lastUnion *unionSelectStatus
limit *int
offset int
ctx context.Context
lock string
}
type errorScanner struct {
err error
}
func (e errorScanner) Scan(dest ...interface{}) error {
return e.err
}
func (s selectStatus) FetchSeq() func(yield func(row Scanner) bool) {
return func(yield func(row Scanner) bool) {
cursor, err := s.FetchCursor()
if err != nil {
yield(errorScanner{err})
return
}
defer cursor.Close()
for cursor.Next() {
if !yield(cursor) {
break
}
}
}
}
type unionSelectStatus struct {
base selectBase
all bool
previous *unionSelectStatus
}
func activeSelectBase(s *selectStatus) *selectBase {
if s.lastUnion != nil {
return &s.lastUnion.base
}
return &s.base
}
func (s selectStatus) Join(table Table) selectWithJoin {
return s.join("", table)
}
func (s selectStatus) LeftJoin(table Table) selectWithJoin {
return s.join("LEFT ", table)
}
func (s selectStatus) RightJoin(table Table) selectWithJoin {
return s.join("RIGHT ", table)
}
// NaturalJoin joins the table using the NATURAL keyword.
// it automatically matches the columns in the two tables that have the same name.
// it not be needed but be provided for completeness.
func (s selectStatus) NaturalJoin(table Table) selectWithJoinOn {
base := activeSelectBase(&s)
base.scope.lastJoin = &join{
previous: base.scope.lastJoin,
prefix: "NATURAL ",
table: table,
}
join := *base.scope.lastJoin
base.scope.lastJoin = &join
return s
}
func (s selectStatus) join(prefix string, table Table) selectWithJoin {
base := activeSelectBase(&s)
base.scope.lastJoin = &join{
previous: base.scope.lastJoin,
prefix: prefix,
table: table,
}
return s
}
func (s selectStatus) On(condition BooleanExpression) selectWithJoinOn {
base := activeSelectBase(&s)
join := *base.scope.lastJoin
join.on = condition
base.scope.lastJoin = &join
return s
}
func getFields(fields []interface{}) (result []Field) {
fields = expandSliceValues(fields)
result = make([]Field, 0, len(fields))
for _, field := range fields {
switch field.(type) {
case Field:
result = append(result, field.(Field))
case Table:
result = append(result, field.(Table).GetFields()...)
default:
fieldCopy := field
fieldExpression := expression{builder: func(scope scope) (string, error) {
sql, _, err := getSQL(scope, fieldCopy)
if err != nil {
return "", err
}
return sql, nil
}}
result = append(result, fieldExpression)
}
}
return
}
func (d *database) Select(fields ...interface{}) selectWithFields {
return selectStatus{
base: selectBase{
scope: scope{
Database: d,
},
fields: getFields(fields),
},
}
}
func (s selectStatus) From(tables ...Table) selectWithTables {
activeSelectBase(&s).scope.Tables = tables
return s
}
func (d *database) SelectFrom(tables ...Table) selectWithTables {
return selectStatus{
base: selectBase{
scope: scope{
Database: d,
Tables: tables,
},
},
}
}
func (d *database) SelectDistinct(fields ...interface{}) selectWithFields {
return selectStatus{
base: selectBase{
scope: scope{
Database: d,
},
fields: getFields(fields),
distinct: true,
},
}
}
func (s selectStatus) Where(conditions ...BooleanExpression) selectWithWhere {
if base := activeSelectBase(&s); base.where == nil {
base.where = And(conditions...)
} else {
base.where = And(base.where, And(conditions...))
}
return s
}
func (s selectStatus) WhereIf(prerequisite bool, conditions ...BooleanExpression) selectWithWhere {
if !prerequisite {
return s
}
if base := activeSelectBase(&s); base.where == nil {
base.where = And(conditions...)
} else {
base.where = And(base.where, And(conditions...))
}
return s
}
func (s selectStatus) GroupBy(expressions ...Expression) selectWithGroupBy {
activeSelectBase(&s).groupBys = expressions
return s
}
func (s selectStatus) Having(conditions ...BooleanExpression) selectWithGroupByHaving {
activeSelectBase(&s).having = And(conditions...)
return s
}
func (s selectStatus) UnionSelect(fields ...interface{}) selectWithFields {
return s.withUnionSelect(false, false, fields, nil)
}
func (s selectStatus) UnionSelectFrom(tables ...Table) selectWithTables {
return s.withUnionSelect(false, false, nil, tables)
}
func (s selectStatus) UnionSelectDistinct(fields ...interface{}) selectWithFields {
return s.withUnionSelect(false, true, fields, nil)
}
func (s selectStatus) UnionAllSelect(fields ...interface{}) selectWithFields {
return s.withUnionSelect(true, false, fields, nil)
}
func (s selectStatus) UnionAllSelectFrom(tables ...Table) selectWithTables {
return s.withUnionSelect(true, false, nil, tables)
}
func (s selectStatus) UnionAllSelectDistinct(fields ...interface{}) selectWithFields {
return s.withUnionSelect(true, true, fields, nil)
}
func (s selectStatus) withUnionSelect(all bool, distinct bool, fields []interface{}, tables []Table) selectStatus {
s.lastUnion = &unionSelectStatus{
base: selectBase{
scope: scope{
Database: s.base.scope.Database,
Tables: tables,
},
distinct: distinct,
fields: getFields(fields),
},
all: all,
previous: s.lastUnion,
}
return s
}
func (s selectStatus) OrderBy(orderBys ...OrderBy) selectWithOrder {
s.orderBys = orderBys
return s
}
func (s selectStatus) Limit(limit int) selectWithLimit {
s.limit = &limit
return s
}
func (s selectStatus) Offset(offset int) selectWithOffset {
s.offset = offset
return s
}
func (s selectStatus) Count() (count int, err error) {
if s.lastUnion == nil && len(s.base.groupBys) == 0 && s.limit == nil {
if s.base.distinct {
fields := s.base.fields
s.base.distinct = false
s.base.fields = []Field{expression{builder: func(scope scope) (string, error) {
fieldsSql, err := fields.GetSQL(scope)
if err != nil {
return "", err
}
return "COUNT(DISTINCT " + fieldsSql + ")", nil
}}}
_, err = s.FetchFirst(&count)
} else {
s.base.fields = []Field{staticExpression("COUNT(1)", 0, false)}
_, err = s.FetchFirst(&count)
}
} else {
if !s.base.distinct {
s.base.fields = []Field{staticExpression("1", 0, false)}
}
_, err = s.base.scope.Database.Select(Function("COUNT", 1)).
From(s.asDerivedTable("t")).
FetchFirst(&count)
}
return
}
func (s selectStatus) LockInShareMode() selectWithLock {
s.lock = " LOCK IN SHARE MODE"
return s
}
func (s selectStatus) ForUpdate() selectWithLock {
s.lock = " FOR UPDATE"
return s
}
func (s selectStatus) ForUpdateNoWait() selectWithLock {
s.lock = " FOR UPDATE NOWAIT"
return s
}
func (s selectStatus) ForUpdateSkipLocked() selectWithLock {
s.lock = " FOR UPDATE SKIP LOCKED"
return s
}
func (s selectStatus) asDerivedTable(name string) Table {
return derivedTable{
name: name,
selectStatus: s,
}
}
func (s selectStatus) Exists() (exists bool, err error) {
_, err = s.base.scope.Database.Select(command("EXISTS", s)).FetchFirst(&exists)
return
}
func (s selectBase) buildSelectBase(sb *strings.Builder) error {
sb.WriteString("SELECT ")
if s.distinct {
sb.WriteString("DISTINCT ")
}
// find tables from fields if "From" is not specified
if len(s.scope.Tables) == 0 && len(s.fields) > 0 {
tableNames := make([]string, 0, len(s.fields))
tableMap := make(map[string]Table)
for _, field := range s.fields {
table := field.GetTable()
if table == nil {
continue
}
tableName := table.GetName()
if _, ok := tableMap[tableName]; !ok {
tableMap[tableName] = table
tableNames = append(tableNames, tableName)
}
}
for _, tableName := range tableNames {
table := tableMap[tableName]
s.scope.Tables = append(s.scope.Tables, table)
}
}
fieldsSql, err := s.fields.GetSQL(s.scope)
if err != nil {
return err
}
sb.WriteString(fieldsSql)
if len(s.scope.Tables) > 0 {
fromSql := commaTables(s.scope, s.scope.Tables)
sb.WriteString(" FROM ")
sb.WriteString(fromSql)
}
if s.scope.lastJoin != nil {
var joins []*join
for j := s.scope.lastJoin; j != nil; j = j.previous {
joins = append(joins, j)
}
for i := len(joins) - 1; i >= 0; i-- {
join := joins[i]
sb.WriteString(" ")
sb.WriteString(join.prefix)
sb.WriteString("JOIN ")
sb.WriteString(join.table.GetSQL(s.scope))
// cause on isn't a required part of join when using natural join,
// so move it to if statement
if join.on != nil {
onSql, err := join.on.GetSQL(s.scope)
if err != nil {
return err
}
sb.WriteString(" ON ")
sb.WriteString(onSql)
}
}
}
if err := appendWhere(sb, s.scope, s.where); err != nil {
return err
}
if len(s.groupBys) != 0 {
groupBySql, err := commaExpressions(s.scope, s.groupBys)
if err != nil {
return err
}
sb.WriteString(" GROUP BY ")
sb.WriteString(groupBySql)
if s.having != nil {
havingSql, err := s.having.GetSQL(s.scope)
if err != nil {
return err
}
sb.WriteString(" HAVING ")
sb.WriteString(havingSql)
}
}
return nil
}
func (s selectStatus) GetSQL() (string, error) {
var sb strings.Builder
sb.Grow(128)
if err := s.base.buildSelectBase(&sb); err != nil {
return "", err
}
var unions []*unionSelectStatus
for union := s.lastUnion; union != nil; union = union.previous {
unions = append(unions, union)
}
for i := len(unions) - 1; i >= 0; i-- {
union := unions[i]
if union.all {
sb.WriteString(" UNION ALL ")
} else {
sb.WriteString(" UNION ")
}
if err := union.base.buildSelectBase(&sb); err != nil {
return "", err
}
}
if len(s.orderBys) > 0 {
orderBySql, err := commaOrderBys(s.base.scope, s.orderBys)
if err != nil {
return "", err
}
sb.WriteString(" ORDER BY ")
sb.WriteString(orderBySql)
}
if s.limit != nil {
sb.WriteString(" LIMIT ")
sb.WriteString(strconv.Itoa(*s.limit))
}
if s.offset != 0 {
sb.WriteString(" OFFSET ")
sb.WriteString(strconv.Itoa(s.offset))
}
sb.WriteString(s.lock)
return sb.String(), nil
}
func (s selectStatus) WithContext(ctx context.Context) toSelectFinal {
s.ctx = ctx
return s
}
func (s selectStatus) FetchCursor() (Cursor, error) {
sqlString, err := s.GetSQL()
if err != nil {
return nil, err
}
cursor, err := s.base.scope.Database.QueryContext(s.ctx, sqlString)
if err != nil {
return nil, err
}
return cursor, nil
}
func (s selectStatus) FetchFirst(dest ...interface{}) (ok bool, err error) {
cursor, err := s.FetchCursor()
if err != nil {
return
}
defer cursor.Close()
for cursor.Next() {
err = cursor.Scan(dest...)
if err != nil {
return
}
ok = true
break
}
return
}
func (s selectStatus) FetchExactlyOne(dest ...interface{}) (err error) {
cursor, err := s.FetchCursor()
if err != nil {
return
}
defer cursor.Close()
hasResult := false
for cursor.Next() {
if hasResult {
return errors.New("more than one rows")
}
err = cursor.Scan(dest...)
if err != nil {
return
}
hasResult = true
}
if !hasResult {
err = errors.New("no rows")
}
return
}
func (s selectStatus) fetchAllAsMap(cursor Cursor, mapType reflect.Type) (mapValue reflect.Value, err error) {
mapValue = reflect.MakeMap(mapType)
key := reflect.New(mapType.Key())
elem := reflect.New(mapType.Elem())
for cursor.Next() {
err = cursor.Scan(key.Interface(), elem.Interface())
if err != nil {
return
}
mapValue.SetMapIndex(reflect.Indirect(key), reflect.Indirect(elem))
}
return
}
func (s selectStatus) FetchAll(dest ...interface{}) (rows int, err error) {
cursor, err := s.FetchCursor()
if err != nil {
return
}
defer cursor.Close()
count := len(dest)
values := make([]reflect.Value, count)
for i, item := range dest {
if reflect.ValueOf(item).Kind() != reflect.Ptr {
err = errors.New("dest should be a pointer")
return
}
val := reflect.Indirect(reflect.ValueOf(item))
switch val.Kind() {
case reflect.Slice:
values[i] = val
case reflect.Map:
if len(dest) != 1 {
err = errors.New("dest map should be 1 element")
return
}
var mapValue reflect.Value
mapValue, err = s.fetchAllAsMap(cursor, val.Type())
if err != nil {
return
}
reflect.ValueOf(item).Elem().Set(mapValue)
return
default:
err = errors.New("dest should be pointed to a slice")
return
}
}
elements := make([]reflect.Value, count)
pointers := make([]interface{}, count)
for i := 0; i < count; i++ {
elements[i] = reflect.New(values[i].Type().Elem())
pointers[i] = elements[i].Interface()
}
for cursor.Next() {
err = cursor.Scan(pointers...)
if err != nil {
return
}
for i := 0; i < count; i++ {
values[i].Set(reflect.Append(values[i], reflect.Indirect(elements[i])))
}
rows++
}
return
}