-
-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathquery_select.go
More file actions
1439 lines (1186 loc) · 33.8 KB
/
query_select.go
File metadata and controls
1439 lines (1186 loc) · 33.8 KB
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package bun
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"sync"
"github.com/uptrace/bun/dialect"
"github.com/uptrace/bun/dialect/feature"
"github.com/uptrace/bun/internal"
"github.com/uptrace/bun/schema"
)
type union struct {
expr string
query *SelectQuery
}
// SelectQuery builds SQL SELECT statements.
type SelectQuery struct {
whereBaseQuery
idxHintsQuery
orderLimitOffsetQuery
distinctOn []schema.QueryWithArgs
joins []joinQuery
group []schema.QueryWithArgs
having []schema.QueryWithArgs
selFor schema.QueryWithArgs
union []union
comment string
}
var _ Query = (*SelectQuery)(nil)
// NewSelectQuery returns a SelectQuery attached to the provided DB.
func NewSelectQuery(db *DB) *SelectQuery {
return &SelectQuery{
whereBaseQuery: whereBaseQuery{
baseQuery: baseQuery{
db: db,
},
},
}
}
// Conn sets the database connection for this query.
func (q *SelectQuery) Conn(db IConn) *SelectQuery {
q.setConn(db)
return q
}
// Model sets the model to select into and generates SELECT and FROM clauses.
func (q *SelectQuery) Model(model any) *SelectQuery {
q.setModel(model)
return q
}
// Err sets an error on the query, causing subsequent operations to fail.
func (q *SelectQuery) Err(err error) *SelectQuery {
q.setErr(err)
return q
}
// Apply calls each function in fns, passing the SelectQuery as an argument.
func (q *SelectQuery) Apply(fns ...func(*SelectQuery) *SelectQuery) *SelectQuery {
for _, fn := range fns {
if fn != nil {
q = fn(q)
}
}
return q
}
// With adds a WITH clause (Common Table Expression) to the query.
func (q *SelectQuery) With(name string, query Query) *SelectQuery {
q.addWith(NewWithQuery(name, query))
return q
}
// WithRecursive adds a WITH RECURSIVE clause to the query.
func (q *SelectQuery) WithRecursive(name string, query Query) *SelectQuery {
q.addWith(NewWithQuery(name, query).Recursive())
return q
}
// WithQuery adds a pre-configured WITH clause to the query.
func (q *SelectQuery) WithQuery(query *WithQuery) *SelectQuery {
q.addWith(query)
return q
}
// Distinct adds a DISTINCT clause to eliminate duplicate rows.
func (q *SelectQuery) Distinct() *SelectQuery {
q.distinctOn = make([]schema.QueryWithArgs, 0)
return q
}
// DistinctOn adds a DISTINCT ON clause for PostgreSQL-specific distinct behavior.
func (q *SelectQuery) DistinctOn(query string, args ...any) *SelectQuery {
q.distinctOn = append(q.distinctOn, schema.SafeQuery(query, args))
return q
}
//------------------------------------------------------------------------------
// Table specifies the table(s) to select from.
func (q *SelectQuery) Table(tables ...string) *SelectQuery {
for _, table := range tables {
q.addTable(schema.UnsafeIdent(table))
}
return q
}
// TableExpr adds a table expression to the FROM clause with arguments.
func (q *SelectQuery) TableExpr(query string, args ...any) *SelectQuery {
q.addTable(schema.SafeQuery(query, args))
return q
}
// ModelTableExpr overrides the table name derived from the model.
func (q *SelectQuery) ModelTableExpr(query string, args ...any) *SelectQuery {
q.modelTableName = schema.SafeQuery(query, args)
return q
}
//------------------------------------------------------------------------------
// Column adds columns to the SELECT clause.
func (q *SelectQuery) Column(columns ...string) *SelectQuery {
for _, column := range columns {
q.addColumn(schema.UnsafeIdent(column))
}
return q
}
// ColumnExpr adds a column expression to the SELECT clause with arguments.
func (q *SelectQuery) ColumnExpr(query string, args ...any) *SelectQuery {
q.addColumn(schema.SafeQuery(query, args))
return q
}
// ExcludeColumn excludes specific columns from being selected.
func (q *SelectQuery) ExcludeColumn(columns ...string) *SelectQuery {
q.excludeColumn(columns)
return q
}
//------------------------------------------------------------------------------
// WherePK adds a WHERE condition on the model's primary key columns.
func (q *SelectQuery) WherePK(cols ...string) *SelectQuery {
q.addWhereCols(cols)
return q
}
// Where adds a WHERE condition combined with AND.
func (q *SelectQuery) Where(query string, args ...any) *SelectQuery {
q.addWhere(schema.SafeQueryWithSep(query, args, " AND "))
return q
}
// WhereOr adds a WHERE condition combined with OR.
func (q *SelectQuery) WhereOr(query string, args ...any) *SelectQuery {
q.addWhere(schema.SafeQueryWithSep(query, args, " OR "))
return q
}
// WhereGroup groups WHERE conditions with the given separator (AND/OR).
func (q *SelectQuery) WhereGroup(sep string, fn func(*SelectQuery) *SelectQuery) *SelectQuery {
saved := q.where
q.where = nil
q = fn(q)
where := q.where
q.where = saved
q.addWhereGroup(sep, where)
return q
}
// WhereDeleted adds a WHERE condition to select soft-deleted rows only.
func (q *SelectQuery) WhereDeleted() *SelectQuery {
q.whereDeleted()
return q
}
// WhereAllWithDeleted includes both active and soft-deleted rows.
func (q *SelectQuery) WhereAllWithDeleted() *SelectQuery {
q.whereAllWithDeleted()
return q
}
//------------------------------------------------------------------------------
// UseIndex adds a USE INDEX hint for MySQL to suggest index usage.
func (q *SelectQuery) UseIndex(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addUseIndex(indexes...)
}
return q
}
// UseIndexForJoin adds a USE INDEX FOR JOIN hint for MySQL.
func (q *SelectQuery) UseIndexForJoin(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addUseIndexForJoin(indexes...)
}
return q
}
// UseIndexForOrderBy adds a USE INDEX FOR ORDER BY hint for MySQL.
func (q *SelectQuery) UseIndexForOrderBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addUseIndexForOrderBy(indexes...)
}
return q
}
// UseIndexForGroupBy adds a USE INDEX FOR GROUP BY hint for MySQL.
func (q *SelectQuery) UseIndexForGroupBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addUseIndexForGroupBy(indexes...)
}
return q
}
// IgnoreIndex adds an IGNORE INDEX hint for MySQL to prevent index usage.
func (q *SelectQuery) IgnoreIndex(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addIgnoreIndex(indexes...)
}
return q
}
// IgnoreIndexForJoin adds an IGNORE INDEX FOR JOIN hint for MySQL.
func (q *SelectQuery) IgnoreIndexForJoin(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addIgnoreIndexForJoin(indexes...)
}
return q
}
// IgnoreIndexForOrderBy adds an IGNORE INDEX FOR ORDER BY hint for MySQL.
func (q *SelectQuery) IgnoreIndexForOrderBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addIgnoreIndexForOrderBy(indexes...)
}
return q
}
// IgnoreIndexForGroupBy adds an IGNORE INDEX FOR GROUP BY hint for MySQL.
func (q *SelectQuery) IgnoreIndexForGroupBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addIgnoreIndexForGroupBy(indexes...)
}
return q
}
// ForceIndex adds a FORCE INDEX hint for MySQL to require index usage.
func (q *SelectQuery) ForceIndex(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addForceIndex(indexes...)
}
return q
}
// ForceIndexForJoin adds a FORCE INDEX FOR JOIN hint for MySQL.
func (q *SelectQuery) ForceIndexForJoin(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addForceIndexForJoin(indexes...)
}
return q
}
// ForceIndexForOrderBy adds a FORCE INDEX FOR ORDER BY hint for MySQL.
func (q *SelectQuery) ForceIndexForOrderBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addForceIndexForOrderBy(indexes...)
}
return q
}
// ForceIndexForGroupBy adds a FORCE INDEX FOR GROUP BY hint for MySQL.
func (q *SelectQuery) ForceIndexForGroupBy(indexes ...string) *SelectQuery {
if q.db.dialect.Name() == dialect.MySQL {
q.addForceIndexForGroupBy(indexes...)
}
return q
}
//------------------------------------------------------------------------------
// Group adds columns to the GROUP BY clause.
func (q *SelectQuery) Group(columns ...string) *SelectQuery {
for _, column := range columns {
q.group = append(q.group, schema.UnsafeIdent(column))
}
return q
}
// GroupExpr adds a GROUP BY expression with optional arguments.
func (q *SelectQuery) GroupExpr(group string, args ...any) *SelectQuery {
q.group = append(q.group, schema.SafeQuery(group, args))
return q
}
// Having adds a HAVING clause condition to filter grouped results.
func (q *SelectQuery) Having(having string, args ...any) *SelectQuery {
q.having = append(q.having, schema.SafeQuery(having, args))
return q
}
// Order adds columns to the ORDER BY clause.
func (q *SelectQuery) Order(orders ...string) *SelectQuery {
q.addOrder(orders...)
return q
}
// OrderBy adds an ORDER BY clause with explicit sort direction.
func (q *SelectQuery) OrderBy(colName string, sortDir Order) *SelectQuery {
q.addOrderBy(colName, sortDir)
return q
}
// OrderExpr adds an ORDER BY expression with optional arguments.
func (q *SelectQuery) OrderExpr(query string, args ...any) *SelectQuery {
q.addOrderExpr(query, args...)
return q
}
// Limit sets the maximum number of rows to return.
func (q *SelectQuery) Limit(n int) *SelectQuery {
q.setLimit(n)
return q
}
// Offset sets the number of rows to skip before returning results.
func (q *SelectQuery) Offset(n int) *SelectQuery {
q.setOffset(n)
return q
}
// For adds a FOR clause for row locking (e.g., "UPDATE", "SHARE").
func (q *SelectQuery) For(s string, args ...any) *SelectQuery {
q.selFor = schema.SafeQuery(s, args)
return q
}
//------------------------------------------------------------------------------
// Union combines this query with another using UNION (removes duplicates).
func (q *SelectQuery) Union(other *SelectQuery) *SelectQuery {
return q.addUnion(" UNION ", other)
}
// UnionAll combines this query with another using UNION ALL (keeps duplicates).
func (q *SelectQuery) UnionAll(other *SelectQuery) *SelectQuery {
return q.addUnion(" UNION ALL ", other)
}
// Intersect returns rows that appear in both this query and another (removes duplicates).
func (q *SelectQuery) Intersect(other *SelectQuery) *SelectQuery {
return q.addUnion(" INTERSECT ", other)
}
// IntersectAll returns rows that appear in both this query and another (keeps duplicates).
func (q *SelectQuery) IntersectAll(other *SelectQuery) *SelectQuery {
return q.addUnion(" INTERSECT ALL ", other)
}
// Except returns rows in this query that are not in another (removes duplicates).
func (q *SelectQuery) Except(other *SelectQuery) *SelectQuery {
return q.addUnion(" EXCEPT ", other)
}
// ExceptAll returns rows in this query that are not in another (keeps duplicates).
func (q *SelectQuery) ExceptAll(other *SelectQuery) *SelectQuery {
return q.addUnion(" EXCEPT ALL ", other)
}
func (q *SelectQuery) addUnion(expr string, other *SelectQuery) *SelectQuery {
q.union = append(q.union, union{
expr: expr,
query: other,
})
return q
}
//------------------------------------------------------------------------------
// Join adds a JOIN clause with the specified join expression.
func (q *SelectQuery) Join(join string, args ...any) *SelectQuery {
q.joins = append(q.joins, joinQuery{
join: schema.SafeQuery(join, args),
})
return q
}
// JoinOn adds an ON condition to the most recent JOIN, combined with AND.
func (q *SelectQuery) JoinOn(cond string, args ...any) *SelectQuery {
return q.joinOn(cond, args, " AND ")
}
// JoinOnOr adds an ON condition to the most recent JOIN, combined with OR.
func (q *SelectQuery) JoinOnOr(cond string, args ...any) *SelectQuery {
return q.joinOn(cond, args, " OR ")
}
func (q *SelectQuery) joinOn(cond string, args []any, sep string) *SelectQuery {
if len(q.joins) == 0 {
q.setErr(errors.New("bun: query has no joins"))
return q
}
j := &q.joins[len(q.joins)-1]
j.on = append(j.on, schema.SafeQueryWithSep(cond, args, sep))
return q
}
//------------------------------------------------------------------------------
// Relation adds a relation to the query.
func (q *SelectQuery) Relation(name string, apply ...func(*SelectQuery) *SelectQuery) *SelectQuery {
if len(apply) > 1 {
panic("only one apply function is supported")
}
if q.tableModel == nil {
q.setErr(errNilModel)
return q
}
join := q.tableModel.join(name)
if join == nil {
q.setErr(fmt.Errorf("%s does not have relation=%q", q.table, name))
return q
}
q.applyToRelation(join, apply...)
return q
}
// RelationOpts configures how a relation is joined in a SelectQuery.
type RelationOpts struct {
// Apply applies additional options to the relation.
Apply func(*SelectQuery) *SelectQuery
// AdditionalJoinOnConditions adds additional conditions to the JOIN ON clause.
AdditionalJoinOnConditions []schema.QueryWithArgs
}
// RelationWithOpts adds a relation to the query with additional options.
func (q *SelectQuery) RelationWithOpts(name string, opts RelationOpts) *SelectQuery {
if q.tableModel == nil {
q.setErr(errNilModel)
return q
}
join := q.tableModel.join(name)
if join == nil {
q.setErr(fmt.Errorf("%s does not have relation=%q", q.table, name))
return q
}
if opts.Apply != nil {
q.applyToRelation(join, opts.Apply)
}
if len(opts.AdditionalJoinOnConditions) > 0 {
join.additionalJoinOnConditions = opts.AdditionalJoinOnConditions
}
return q
}
func (q *SelectQuery) applyToRelation(join *relationJoin, apply ...func(*SelectQuery) *SelectQuery) {
var apply1, apply2 func(*SelectQuery) *SelectQuery
if len(join.Relation.Condition) > 0 {
apply1 = func(q *SelectQuery) *SelectQuery {
for _, opt := range join.Relation.Condition {
q.addWhere(schema.SafeQueryWithSep(opt, nil, " AND "))
}
return q
}
}
if len(apply) == 1 {
apply2 = apply[0]
}
join.apply = func(q *SelectQuery) *SelectQuery {
if apply1 != nil {
q = apply1(q)
}
if apply2 != nil {
q = apply2(q)
}
return q
}
}
func (q *SelectQuery) forEachInlineRelJoin(fn func(*relationJoin) error) error {
if q.tableModel == nil {
return nil
}
return q._forEachInlineRelJoin(fn, q.tableModel.getJoins())
}
func (q *SelectQuery) _forEachInlineRelJoin(fn func(*relationJoin) error, joins []relationJoin) error {
for i := range joins {
j := &joins[i]
switch j.Relation.Type {
case schema.HasOneRelation, schema.BelongsToRelation:
if err := fn(j); err != nil {
return err
}
if err := q._forEachInlineRelJoin(fn, j.JoinModel.getJoins()); err != nil {
return err
}
}
}
return nil
}
func (q *SelectQuery) selectJoins(ctx context.Context, joins []relationJoin) error {
for i := range joins {
j := &joins[i]
var err error
switch j.Relation.Type {
case schema.HasOneRelation, schema.BelongsToRelation:
err = q.selectJoins(ctx, j.JoinModel.getJoins())
case schema.HasManyRelation:
err = j.selectMany(ctx, q.db.NewSelect().Conn(q.conn))
case schema.ManyToManyRelation:
err = j.selectM2M(ctx, q.db.NewSelect().Conn(q.conn))
default:
panic("not reached")
}
if err != nil {
return err
}
}
return nil
}
//------------------------------------------------------------------------------
// Comment adds a comment to the query, wrapped by /* ... */.
func (q *SelectQuery) Comment(comment string) *SelectQuery {
q.comment = comment
return q
}
//------------------------------------------------------------------------------
// Operation returns the query operation name ("SELECT").
func (q *SelectQuery) Operation() string {
return "SELECT"
}
func (q *SelectQuery) AppendQuery(gen schema.QueryGen, b []byte) (_ []byte, err error) {
b = appendComment(b, q.comment)
return q.appendQuery(gen, b, false)
}
func (q *SelectQuery) appendQuery(
gen schema.QueryGen, b []byte, count bool,
) (_ []byte, err error) {
if q.err != nil {
return nil, q.err
}
gen = formatterWithModel(gen, q)
cteCount := count && (len(q.group) > 0 || q.distinctOn != nil)
if cteCount {
b = append(b, "WITH _count_wrapper AS ("...)
}
if len(q.union) > 0 {
b = append(b, '(')
}
b, err = q.appendWith(gen, b)
if err != nil {
return nil, err
}
if err := q.forEachInlineRelJoin(func(j *relationJoin) error {
j.applyTo(q)
return nil
}); err != nil {
return nil, err
}
b = append(b, "SELECT "...)
if len(q.distinctOn) > 0 {
b = append(b, "DISTINCT ON ("...)
for i, app := range q.distinctOn {
if i > 0 {
b = append(b, ", "...)
}
b, err = app.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
b = append(b, ") "...)
} else if q.distinctOn != nil {
b = append(b, "DISTINCT "...)
}
if count && !cteCount {
b = append(b, "count(*)"...)
} else {
// MSSQL: allows Limit() without Order() as per https://stackoverflow.com/a/36156953
if q.limit > 0 && len(q.order) == 0 && gen.Dialect().Name() == dialect.MSSQL {
b = append(b, "0 AS _temp_sort, "...)
}
b, err = q.appendColumns(gen, b)
if err != nil {
return nil, err
}
}
if q.hasTables() {
b, err = q.appendTables(gen, b)
if err != nil {
return nil, err
}
}
b, err = q.appendIndexHints(gen, b)
if err != nil {
return nil, err
}
if err := q.forEachInlineRelJoin(func(j *relationJoin) error {
b = append(b, ' ')
b, err = j.appendHasOneJoin(gen, b, q)
return err
}); err != nil {
return nil, err
}
for _, join := range q.joins {
b, err = join.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
b, err = q.appendWhere(gen, b, true)
if err != nil {
return nil, err
}
if len(q.group) > 0 {
b = append(b, " GROUP BY "...)
for i, f := range q.group {
if i > 0 {
b = append(b, ", "...)
}
b, err = f.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
}
if len(q.having) > 0 {
b = append(b, " HAVING "...)
for i, f := range q.having {
if i > 0 {
b = append(b, " AND "...)
}
b = append(b, '(')
b, err = f.AppendQuery(gen, b)
if err != nil {
return nil, err
}
b = append(b, ')')
}
}
if !count {
b, err = q.appendOrder(gen, b)
if err != nil {
return nil, err
}
b, err = q.appendLimitOffset(gen, b)
if err != nil {
return nil, err
}
if !q.selFor.IsZero() {
b = append(b, " FOR "...)
b, err = q.selFor.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
}
if len(q.union) > 0 {
b = append(b, ')')
for _, u := range q.union {
b = append(b, u.expr...)
b = append(b, '(')
b, err = u.query.AppendQuery(gen, b)
if err != nil {
return nil, err
}
b = append(b, ')')
}
}
if cteCount {
b = append(b, ") SELECT count(*) FROM _count_wrapper"...)
}
return b, nil
}
func (q *SelectQuery) appendColumns(gen schema.QueryGen, b []byte) (_ []byte, err error) {
start := len(b)
switch {
case q.columns != nil:
for i, col := range q.columns {
if i > 0 {
b = append(b, ", "...)
}
if col.Args == nil && q.table != nil {
if field, ok := q.table.FieldMap[col.Query]; ok {
b = append(b, q.table.SQLAlias...)
b = append(b, '.')
b = append(b, field.SQLName...)
continue
}
}
b, err = col.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
case q.table != nil:
if len(q.table.Fields) > 10 && gen.IsNop() {
b = append(b, q.table.SQLAlias...)
b = append(b, '.')
b = gen.Dialect().AppendString(b, fmt.Sprintf("%d columns", len(q.table.Fields)))
} else {
b = appendColumns(b, q.table.SQLAlias, q.table.Fields)
}
default:
b = append(b, '*')
}
if err := q.forEachInlineRelJoin(func(join *relationJoin) error {
if len(b) != start {
b = append(b, ", "...)
start = len(b)
}
b, err = q.appendInlineRelColumns(gen, b, join)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
b = bytes.TrimSuffix(b, []byte(", "))
return b, nil
}
func (q *SelectQuery) appendInlineRelColumns(
gen schema.QueryGen, b []byte, join *relationJoin,
) (_ []byte, err error) {
if join.columns != nil {
table := join.JoinModel.Table()
for i, col := range join.columns {
if i > 0 {
b = append(b, ", "...)
}
if col.Args == nil {
if field, ok := table.FieldMap[col.Query]; ok {
b = join.appendAlias(gen, b)
b = append(b, '.')
b = append(b, field.SQLName...)
b = append(b, " AS "...)
b = join.appendAliasColumn(gen, b, field.Name)
continue
}
}
b, err = col.AppendQuery(gen, b)
if err != nil {
return nil, err
}
}
return b, nil
}
for i, field := range join.JoinModel.Table().Fields {
if i > 0 {
b = append(b, ", "...)
}
b = join.appendAlias(gen, b)
b = append(b, '.')
b = append(b, field.SQLName...)
b = append(b, " AS "...)
b = join.appendAliasColumn(gen, b, field.Name)
}
return b, nil
}
func (q *SelectQuery) appendTables(gen schema.QueryGen, b []byte) (_ []byte, err error) {
b = append(b, " FROM "...)
return q.appendTablesWithAlias(gen, b)
}
//------------------------------------------------------------------------------
// Rows executes the query and returns the result rows for manual scanning.
func (q *SelectQuery) Rows(ctx context.Context) (*sql.Rows, error) {
if q.err != nil {
return nil, q.err
}
if err := q.beforeAppendModel(ctx, q); err != nil {
return nil, err
}
// if a comment is propagated via the context, use it
setCommentFromContext(ctx, q)
queryBytes, err := q.AppendQuery(q.db.gen, q.db.makeQueryBytes())
if err != nil {
return nil, err
}
query := internal.String(queryBytes)
ctx, event := q.db.beforeQuery(ctx, q, query, nil, query, q.model)
rows, err := q.resolveConn(ctx, q).QueryContext(ctx, query)
q.db.afterQuery(ctx, event, nil, err)
return rows, err
}
// Exec executes the query and optionally scans results into dest.
func (q *SelectQuery) Exec(ctx context.Context, dest ...any) (res sql.Result, err error) {
if q.err != nil {
return nil, q.err
}
if err := q.beforeAppendModel(ctx, q); err != nil {
return nil, err
}
// if a comment is propagated via the context, use it
setCommentFromContext(ctx, q)
queryBytes, err := q.AppendQuery(q.db.gen, q.db.makeQueryBytes())
if err != nil {
return nil, err
}
query := internal.String(queryBytes)
if len(dest) > 0 {
model, err := q.getModel(dest)
if err != nil {
return nil, err
}
res, err = q.scan(ctx, q, query, model, true)
if err != nil {
return nil, err
}
} else {
res, err = q.exec(ctx, q, query)
if err != nil {
return nil, err
}
}
return res, nil
}
// Scan executes the query and scans the results into dest.
func (q *SelectQuery) Scan(ctx context.Context, dest ...any) error {
_, err := q.scanResult(ctx, dest...)
return err
}
func (q *SelectQuery) scanResult(ctx context.Context, dest ...any) (sql.Result, error) {
if q.err != nil {
return nil, q.err
}
model, err := q.getModel(dest)
if err != nil {
return nil, err
}
if len(dest) > 0 && q.tableModel != nil && len(q.tableModel.getJoins()) > 0 {
for _, j := range q.tableModel.getJoins() {
switch j.Relation.Type {
case schema.HasManyRelation, schema.ManyToManyRelation:
return nil, fmt.Errorf("When querying has-many or many-to-many relationships, you should use Model instead of the dest parameter in Scan.")
}
}
}
if q.table != nil {
if err := q.beforeSelectHook(ctx); err != nil {
return nil, err
}
}
if err := q.beforeAppendModel(ctx, q); err != nil {
return nil, err
}
// if a comment is propagated via the context, use it
setCommentFromContext(ctx, q)
queryBytes, err := q.AppendQuery(q.db.gen, q.db.makeQueryBytes())
if err != nil {
return nil, err
}
query := internal.String(queryBytes)
res, err := q.scan(ctx, q, query, model, true)
if err != nil {
return nil, err
}
if n, _ := res.RowsAffected(); n > 0 {
if tableModel, ok := model.(TableModel); ok {
if err := q.selectJoins(ctx, tableModel.getJoins()); err != nil {
return nil, err
}
}
}
if q.table != nil {
if err := q.afterSelectHook(ctx); err != nil {
return nil, err
}
}
return res, nil
}
func (q *SelectQuery) beforeSelectHook(ctx context.Context) error {
if hook, ok := q.table.ZeroIface.(BeforeSelectHook); ok {
if err := hook.BeforeSelect(ctx, q); err != nil {
return err
}
}
return nil
}
func (q *SelectQuery) afterSelectHook(ctx context.Context) error {
if hook, ok := q.table.ZeroIface.(AfterSelectHook); ok {
if err := hook.AfterSelect(ctx, q); err != nil {
return err
}
}
return nil
}
// Count executes the query and returns the number of rows that match.
func (q *SelectQuery) Count(ctx context.Context) (int, error) {
if q.err != nil {