-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
1274 lines (1157 loc) · 36.7 KB
/
query.go
File metadata and controls
1274 lines (1157 loc) · 36.7 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 soy
import (
"context"
"fmt"
"github.com/jmoiron/sqlx"
"github.com/zoobz-io/astql"
"github.com/zoobz-io/atom"
)
// Query provides a focused API for building SELECT queries that return multiple records.
// It wraps ASTQL's SELECT functionality with a simple string-based interface.
// Use this for querying multiple records from the database.
type Query[T any] struct {
instance *astql.ASTQL
builder *astql.Builder
soy soyExecutor // interface for execution
err error // stores first error encountered during building
}
// Fields specifies which fields to select. If not called, selects all fields (*).
// Multiple calls overwrite previous field selections.
//
// Example:
//
// soy.Query().
// Fields("id", "email", "name").
// Where("age", ">=", "min_age").
// Exec(ctx, params)
func (qb *Query[T]) Fields(fields ...string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = fieldsImpl(qb.instance, qb.builder, fields...)
return qb
}
// Where adds a simple WHERE condition with field operator param pattern.
// Multiple calls are combined with AND.
//
// Example:
//
// .Where("age", ">=", "min_age")
func (qb *Query[T]) Where(field, operator, param string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereImpl(qb.instance, qb.builder, field, operator, param)
return qb
}
// WhereAnd adds multiple conditions combined with AND.
//
// Example:
//
// .WhereAnd(
// soy.C("age", ">=", "min_age"),
// soy.C("status", "=", "active"),
// )
func (qb *Query[T]) WhereAnd(conditions ...Condition) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereAndImpl(qb.instance, qb.builder, conditions...)
return qb
}
// WhereOr adds multiple conditions combined with OR.
//
// Example:
//
// .WhereOr(
// soy.C("status", "=", "active"),
// soy.C("status", "=", "pending"),
// )
func (qb *Query[T]) WhereOr(conditions ...Condition) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereOrImpl(qb.instance, qb.builder, conditions...)
return qb
}
// WhereNull adds a WHERE field IS NULL condition.
func (qb *Query[T]) WhereNull(field string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereNullImpl(qb.instance, qb.builder, field)
return qb
}
// WhereNotNull adds a WHERE field IS NOT NULL condition.
func (qb *Query[T]) WhereNotNull(field string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereNotNullImpl(qb.instance, qb.builder, field)
return qb
}
// WhereBetween adds a WHERE field BETWEEN low AND high condition.
// Multiple calls are combined with AND.
//
// Example:
//
// .WhereBetween("age", "min_age", "max_age")
// // params: map[string]any{"min_age": 18, "max_age": 65}
func (qb *Query[T]) WhereBetween(field, lowParam, highParam string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereBetweenImpl(qb.instance, qb.builder, field, lowParam, highParam)
return qb
}
// WhereNotBetween adds a WHERE field NOT BETWEEN low AND high condition.
// Multiple calls are combined with AND.
//
// Example:
//
// .WhereNotBetween("age", "min_age", "max_age")
// // params: map[string]any{"min_age": 18, "max_age": 65}
func (qb *Query[T]) WhereNotBetween(field, lowParam, highParam string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereNotBetweenImpl(qb.instance, qb.builder, field, lowParam, highParam)
return qb
}
// WhereFields adds a WHERE condition comparing two fields.
// Multiple calls are combined with AND.
//
// Example:
//
// .WhereFields("created_at", "<", "updated_at")
// // WHERE "created_at" < "updated_at"
func (qb *Query[T]) WhereFields(leftField, operator, rightField string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = whereFieldsImpl(qb.instance, qb.builder, leftField, operator, rightField)
return qb
}
// OrderBy adds an ORDER BY clause.
// Direction must be "ASC" or "DESC" (case-insensitive).
// Multiple calls add additional sort fields.
//
// Example:
//
// .OrderBy("age", "DESC").OrderBy("name", "ASC")
func (qb *Query[T]) OrderBy(field, direction string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = orderByImpl(qb.instance, qb.builder, field, direction)
return qb
}
// OrderByNulls adds an ORDER BY clause with NULLS FIRST or NULLS LAST.
// Direction must be "asc" or "desc" (case insensitive).
// Nulls must be "first" or "last" (case insensitive).
//
// Example:
//
// .OrderByNulls("created_at", "desc", "last") // ORDER BY "created_at" DESC NULLS LAST
func (qb *Query[T]) OrderByNulls(field, direction, nulls string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = orderByNullsImpl(qb.instance, qb.builder, field, direction, nulls)
return qb
}
// OrderByExpr adds an ORDER BY clause with an expression (field <op> param).
// Useful for vector distance ordering with pgvector.
// Direction must be "ASC" or "DESC" (case-insensitive).
//
// Example:
//
// .OrderByExpr("embedding", "<->", "query_embedding", "ASC")
func (qb *Query[T]) OrderByExpr(field, operator, param, direction string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = orderByExprImpl(qb.instance, qb.builder, field, operator, param, direction)
return qb
}
// SelectExpr adds a binary expression (field <op> param) AS alias to the SELECT clause.
// Useful for retrieving vector distance scores alongside results with pgvector.
//
// Example:
//
// .SelectExpr("embedding", "<=>", "query_vec", "score")
// // SELECT *, "embedding" <=> :query_vec AS "score" FROM ...
func (qb *Query[T]) SelectExpr(field, operator, param, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectExprImpl(qb.instance, qb.builder, field, operator, param, alias)
return qb
}
// Limit adds a LIMIT clause to restrict the number of rows returned.
//
// Example:
//
// .Limit(10)
func (qb *Query[T]) Limit(limit int) *Query[T] {
qb.builder = qb.builder.Limit(limit)
return qb
}
// LimitParam sets the LIMIT clause to a parameterized value.
// Useful for API pagination where limit comes from request parameters.
//
// Example:
//
// .LimitParam("page_size")
// // params: map[string]any{"page_size": 10}
func (qb *Query[T]) LimitParam(param string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = limitParamImpl(qb.instance, qb.builder, param)
return qb
}
// Offset adds an OFFSET clause to skip rows.
//
// Example:
//
// .Limit(10).Offset(20) // page 3 of results
func (qb *Query[T]) Offset(offset int) *Query[T] {
qb.builder = qb.builder.Offset(offset)
return qb
}
// OffsetParam sets the OFFSET clause to a parameterized value.
// Useful for API pagination where offset comes from request parameters.
//
// Example:
//
// .OffsetParam("page_offset")
// // params: map[string]any{"page_offset": 20}
func (qb *Query[T]) OffsetParam(param string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = offsetParamImpl(qb.instance, qb.builder, param)
return qb
}
// Distinct adds DISTINCT to the SELECT query.
func (qb *Query[T]) Distinct() *Query[T] {
qb.builder = qb.builder.Distinct()
return qb
}
// DistinctOn adds DISTINCT ON (PostgreSQL-specific) to the SELECT query.
// Returns only the first row for each distinct combination of the specified fields.
//
// Example:
//
// .DistinctOn("user_id").OrderBy("created_at", "desc") // First row per user_id
func (qb *Query[T]) DistinctOn(fields ...string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = distinctOnImpl(qb.instance, qb.builder, fields...)
return qb
}
// GroupBy adds a GROUP BY clause.
// Multiple calls add additional grouping fields.
//
// Example:
//
// .GroupBy("status").GroupBy("category")
func (qb *Query[T]) GroupBy(fields ...string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = groupByImpl(qb.instance, qb.builder, fields...)
return qb
}
// Having adds a HAVING condition. Must be used after GroupBy.
// Multiple calls are combined with AND.
//
// Example:
//
// .GroupBy("status").Having("age", ">", "min_age")
func (qb *Query[T]) Having(field, operator, param string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = havingImpl(qb.instance, qb.builder, field, operator, param)
return qb
}
// HavingAgg adds an aggregate HAVING condition. Must be used after GroupBy.
// Supports COUNT(*), SUM, AVG, MIN, MAX aggregate functions.
//
// Example:
//
// .GroupBy("status").HavingAgg("count", "", ">", "min_count") // COUNT(*) > :min_count
// .GroupBy("status").HavingAgg("sum", "amount", ">=", "min_total") // SUM("amount") >= :min_total
func (qb *Query[T]) HavingAgg(aggFunc, field, operator, param string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = havingAggImpl(qb.instance, qb.builder, aggFunc, field, operator, param)
return qb
}
// ForUpdate adds FOR UPDATE row locking to the SELECT query.
// Locks selected rows for update, blocking other transactions from modifying them.
func (qb *Query[T]) ForUpdate() *Query[T] {
qb.builder = qb.builder.ForUpdate()
return qb
}
// ForNoKeyUpdate adds FOR NO KEY UPDATE row locking to the SELECT query.
// Similar to FOR UPDATE but allows SELECT FOR KEY SHARE on the same rows.
func (qb *Query[T]) ForNoKeyUpdate() *Query[T] {
qb.builder = qb.builder.ForNoKeyUpdate()
return qb
}
// ForShare adds FOR SHARE row locking to the SELECT query.
// Locks selected rows in share mode, allowing other SELECT FOR SHARE but blocking updates.
func (qb *Query[T]) ForShare() *Query[T] {
qb.builder = qb.builder.ForShare()
return qb
}
// ForKeyShare adds FOR KEY SHARE row locking to the SELECT query.
// The weakest lock level, blocks only FOR UPDATE but allows other locks.
func (qb *Query[T]) ForKeyShare() *Query[T] {
qb.builder = qb.builder.ForKeyShare()
return qb
}
// --- String Expression Methods ---
// SelectUpper adds UPPER(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectUpper("name", "upper_name") // SELECT UPPER("name") AS "upper_name"
func (qb *Query[T]) SelectUpper(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectUpperImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectLower adds LOWER(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLower("email", "lower_email") // SELECT LOWER("email") AS "lower_email"
func (qb *Query[T]) SelectLower(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectLowerImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectLength adds LENGTH(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLength("name", "name_length") // SELECT LENGTH("name") AS "name_length"
func (qb *Query[T]) SelectLength(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectLengthImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectTrim adds TRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectTrim("name", "trimmed_name") // SELECT TRIM("name") AS "trimmed_name"
func (qb *Query[T]) SelectTrim(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectTrimImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectLTrim adds LTRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLTrim("name", "ltrimmed") // SELECT LTRIM("name") AS "ltrimmed"
func (qb *Query[T]) SelectLTrim(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectLTrimImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectRTrim adds RTRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectRTrim("name", "rtrimmed") // SELECT RTRIM("name") AS "rtrimmed"
func (qb *Query[T]) SelectRTrim(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectRTrimImpl(qb.instance, qb.builder, field, alias)
return qb
}
// --- Math Expression Methods ---
// SelectAbs adds ABS(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectAbs("balance", "abs_balance") // SELECT ABS("balance") AS "abs_balance"
func (qb *Query[T]) SelectAbs(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectAbsImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectCeil adds CEIL(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCeil("price", "rounded_up") // SELECT CEIL("price") AS "rounded_up"
func (qb *Query[T]) SelectCeil(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCeilImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectFloor adds FLOOR(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectFloor("price", "rounded_down") // SELECT FLOOR("price") AS "rounded_down"
func (qb *Query[T]) SelectFloor(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectFloorImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectRound adds ROUND(field) AS alias to the SELECT clause (no precision).
//
// Example:
//
// .SelectRound("price", "rounded") // SELECT ROUND("price") AS "rounded"
func (qb *Query[T]) SelectRound(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectRoundImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectSqrt adds SQRT(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectSqrt("variance", "std_dev") // SELECT SQRT("variance") AS "std_dev"
func (qb *Query[T]) SelectSqrt(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectSqrtImpl(qb.instance, qb.builder, field, alias)
return qb
}
// --- Cast Expression Methods ---
// SelectCast adds CAST(field AS type) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCast("age", soy.CastText, "age_str") // SELECT CAST("age" AS TEXT) AS "age_str"
func (qb *Query[T]) SelectCast(field string, castType CastType, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCastImpl(qb.instance, qb.builder, field, castType, alias)
return qb
}
// --- Date Expression Methods (functions that don't need DatePart) ---
// SelectNow adds NOW() AS alias to the SELECT clause.
//
// Example:
//
// .SelectNow("current_time") // SELECT NOW() AS "current_time"
func (qb *Query[T]) SelectNow(alias string) *Query[T] {
qb.builder = qb.builder.SelectExpr(astql.As(astql.Now(), alias))
return qb
}
// SelectCurrentDate adds CURRENT_DATE AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentDate("today") // SELECT CURRENT_DATE AS "today"
func (qb *Query[T]) SelectCurrentDate(alias string) *Query[T] {
qb.builder = qb.builder.SelectExpr(astql.As(astql.CurrentDate(), alias))
return qb
}
// SelectCurrentTime adds CURRENT_TIME AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentTime("now_time") // SELECT CURRENT_TIME AS "now_time"
func (qb *Query[T]) SelectCurrentTime(alias string) *Query[T] {
qb.builder = qb.builder.SelectExpr(astql.As(astql.CurrentTime(), alias))
return qb
}
// SelectCurrentTimestamp adds CURRENT_TIMESTAMP AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentTimestamp("ts") // SELECT CURRENT_TIMESTAMP AS "ts"
func (qb *Query[T]) SelectCurrentTimestamp(alias string) *Query[T] {
qb.builder = qb.builder.SelectExpr(astql.As(astql.CurrentTimestamp(), alias))
return qb
}
// --- Aggregate Expression Methods ---
// SelectCountStar adds COUNT(*) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectCountStar("count") // SELECT COUNT(*) AS "count"
func (qb *Query[T]) SelectCountStar(alias string) *Query[T] {
qb.builder = qb.builder.SelectExpr(astql.As(astql.CountStar(), alias))
return qb
}
// SelectCount adds COUNT(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectCount("id", "count") // SELECT COUNT("id") AS "count"
func (qb *Query[T]) SelectCount(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCountImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectCountDistinct adds COUNT(DISTINCT field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCountDistinct("email", "unique_emails") // SELECT COUNT(DISTINCT "email") AS "unique_emails"
func (qb *Query[T]) SelectCountDistinct(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCountDistinctImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectSum adds SUM(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectSum("amount", "total") // SELECT SUM("amount") AS "total"
func (qb *Query[T]) SelectSum(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectSumImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectAvg adds AVG(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectAvg("age", "avg_age") // SELECT AVG("age") AS "avg_age"
func (qb *Query[T]) SelectAvg(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectAvgImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectMin adds MIN(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectMin("age", "youngest") // SELECT MIN("age") AS "youngest"
func (qb *Query[T]) SelectMin(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectMinImpl(qb.instance, qb.builder, field, alias)
return qb
}
// SelectMax adds MAX(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectMax("age", "oldest") // SELECT MAX("age") AS "oldest"
func (qb *Query[T]) SelectMax(field, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectMaxImpl(qb.instance, qb.builder, field, alias)
return qb
}
// --- Aggregate FILTER Expression Methods ---
// SelectSumFilter adds SUM(field) FILTER (WHERE condition) AS alias to the SELECT clause.
// The filter condition is specified as field operator param.
//
// Example:
//
// .SelectSumFilter("amount", "status", "=", "active", "active_total")
// // SELECT SUM("amount") FILTER (WHERE "status" = :active) AS "active_total"
func (qb *Query[T]) SelectSumFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectSumFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// SelectAvgFilter adds AVG(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectAvgFilter("age", "active", "=", "true", "active_avg_age")
// // SELECT AVG("age") FILTER (WHERE "active" = :true) AS "active_avg_age"
func (qb *Query[T]) SelectAvgFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectAvgFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// SelectMinFilter adds MIN(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectMinFilter("price", "category", "=", "electronics", "min_electronics")
func (qb *Query[T]) SelectMinFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectMinFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// SelectMaxFilter adds MAX(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectMaxFilter("score", "passed", "=", "true", "max_passed")
func (qb *Query[T]) SelectMaxFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectMaxFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// SelectCountFilter adds COUNT(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCountFilter("id", "status", "=", "active", "active_count")
// // SELECT COUNT("id") FILTER (WHERE "status" = :active) AS "active_count"
func (qb *Query[T]) SelectCountFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCountFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// SelectCountDistinctFilter adds COUNT(DISTINCT field) FILTER (WHERE condition) AS alias.
//
// Example:
//
// .SelectCountDistinctFilter("email", "verified", "=", "true", "verified_users")
func (qb *Query[T]) SelectCountDistinctFilter(field, condField, condOp, condParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCountDistinctFilterImpl(qb.instance, qb.builder, field, condField, condOp, condParam, alias)
return qb
}
// --- Additional String Expression Methods ---
// SelectSubstring adds SUBSTRING(field, start, length) AS alias to the SELECT clause.
//
// Example:
//
// .SelectSubstring("name", "start_pos", "substr_len", "short_name")
// // SELECT SUBSTRING("name", :start_pos, :substr_len) AS "short_name"
func (qb *Query[T]) SelectSubstring(field, startParam, lengthParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectSubstringImpl(qb.instance, qb.builder, field, startParam, lengthParam, alias)
return qb
}
// SelectReplace adds REPLACE(field, search, replacement) AS alias to the SELECT clause.
//
// Example:
//
// .SelectReplace("name", "search_str", "replace_str", "replaced_name")
// // SELECT REPLACE("name", :search_str, :replace_str) AS "replaced_name"
func (qb *Query[T]) SelectReplace(field, searchParam, replacementParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectReplaceImpl(qb.instance, qb.builder, field, searchParam, replacementParam, alias)
return qb
}
// SelectConcat adds CONCAT(field1, field2, ...) AS alias to the SELECT clause.
//
// Example:
//
// .SelectConcat("full_name", "name", "email") // SELECT CONCAT("name", "email") AS "full_name"
func (qb *Query[T]) SelectConcat(alias string, fields ...string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectConcatImpl(qb.instance, qb.builder, alias, fields...)
return qb
}
// --- Additional Math Expression Methods ---
// SelectPower adds POWER(field, exponent) AS alias to the SELECT clause.
//
// Example:
//
// .SelectPower("value", "exponent", "powered") // SELECT POWER("value", :exponent) AS "powered"
func (qb *Query[T]) SelectPower(field, exponentParam, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectPowerImpl(qb.instance, qb.builder, field, exponentParam, alias)
return qb
}
// --- Null Handling Expression Methods ---
// SelectCoalesce adds COALESCE(param1, param2, ...) AS alias to the SELECT clause.
// Returns the first non-null value from the parameters.
// Requires at least 2 parameters.
//
// Example:
//
// .SelectCoalesce("display_name", "nickname", "name", "default_name")
// // SELECT COALESCE(:nickname, :name, :default_name) AS "display_name"
func (qb *Query[T]) SelectCoalesce(alias string, params ...string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectCoalesceImpl(qb.instance, qb.builder, alias, params...)
return qb
}
// SelectNullIf adds NULLIF(param1, param2) AS alias to the SELECT clause.
// Returns NULL if param1 equals param2, otherwise returns param1.
//
// Example:
//
// .SelectNullIf("value", "empty_val", "result")
// // SELECT NULLIF(:value, :empty_val) AS "result"
func (qb *Query[T]) SelectNullIf(param1, param2, alias string) *Query[T] {
if qb.err != nil {
return qb
}
qb.builder, qb.err = selectNullIfImpl(qb.instance, qb.builder, param1, param2, alias)
return qb
}
// --- CASE Expression Methods ---
// SelectCase starts building a CASE expression for the SELECT clause.
// Returns a QueryCaseBuilder that allows chaining When/Else/As clauses.
// Call End() to complete the CASE expression and return to the Query builder.
//
// Example:
//
// soy.Query().
// SelectCase().
// When("status", "=", "status_active", "result_active").
// When("status", "=", "status_pending", "result_pending").
// Else("result_default").
// As("status_label").
// End().
// Exec(ctx, params)
func (qb *Query[T]) SelectCase() *QueryCaseBuilder[T] {
return newQueryCaseBuilder(qb)
}
// QueryCaseBuilder is now defined in case.go
// --- Window Function Methods ---
// SelectRowNumber starts building a ROW_NUMBER() window function.
// Returns a QueryWindowBuilder for configuring the window specification.
//
// Example:
//
// soy.Query().
// SelectRowNumber().
// OrderBy("created_at", "DESC").
// As("row_num").
// End()
func (qb *Query[T]) SelectRowNumber() *QueryWindowBuilder[T] {
return newQueryWindowBuilder(qb, createRowNumberWindow(qb.instance))
}
// SelectRank starts building a RANK() window function.
//
// Example:
//
// .SelectRank().OrderBy("score", "DESC").As("rank").End()
func (qb *Query[T]) SelectRank() *QueryWindowBuilder[T] {
return newQueryWindowBuilder(qb, createRankWindow(qb.instance))
}
// SelectDenseRank starts building a DENSE_RANK() window function.
//
// Example:
//
// .SelectDenseRank().OrderBy("score", "DESC").As("dense_rank").End()
func (qb *Query[T]) SelectDenseRank() *QueryWindowBuilder[T] {
return newQueryWindowBuilder(qb, createDenseRankWindow(qb.instance))
}
// SelectNtile starts building an NTILE(n) window function.
//
// Example:
//
// .SelectNtile("num_buckets").OrderBy("value", "ASC").As("quartile").End()
func (qb *Query[T]) SelectNtile(nParam string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createNtileWindow(qb.instance, nParam))
}
// SelectLag starts building a LAG(field, offset) window function.
//
// Example:
//
// .SelectLag("price", "offset").OrderBy("date", "ASC").As("prev_price").End()
func (qb *Query[T]) SelectLag(field, offsetParam string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createLagWindow(qb.instance, field, offsetParam))
}
// SelectLead starts building a LEAD(field, offset) window function.
//
// Example:
//
// .SelectLead("price", "offset").OrderBy("date", "ASC").As("next_price").End()
func (qb *Query[T]) SelectLead(field, offsetParam string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createLeadWindow(qb.instance, field, offsetParam))
}
// SelectFirstValue starts building a FIRST_VALUE(field) window function.
//
// Example:
//
// .SelectFirstValue("price").OrderBy("date", "ASC").As("first_price").End()
func (qb *Query[T]) SelectFirstValue(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createFirstValueWindow(qb.instance, field))
}
// SelectLastValue starts building a LAST_VALUE(field) window function.
//
// Example:
//
// .SelectLastValue("price").OrderBy("date", "ASC").As("last_price").End()
func (qb *Query[T]) SelectLastValue(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createLastValueWindow(qb.instance, field))
}
// SelectSumOver starts building a SUM(field) OVER window function.
//
// Example:
//
// .SelectSumOver("amount").PartitionBy("category").As("running_total").End()
func (qb *Query[T]) SelectSumOver(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createSumOverWindow(qb.instance, field))
}
// SelectAvgOver starts building an AVG(field) OVER window function.
//
// Example:
//
// .SelectAvgOver("score").PartitionBy("category").As("avg_score").End()
func (qb *Query[T]) SelectAvgOver(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createAvgOverWindow(qb.instance, field))
}
// SelectCountOver starts building a COUNT(*) OVER window function.
//
// Example:
//
// .SelectCountOver().PartitionBy("category").As("category_count").End()
func (qb *Query[T]) SelectCountOver() *QueryWindowBuilder[T] {
return newQueryWindowBuilder(qb, createCountOverWindow(qb.instance))
}
// SelectMinOver starts building a MIN(field) OVER window function.
//
// Example:
//
// .SelectMinOver("price").PartitionBy("category").As("min_price").End()
func (qb *Query[T]) SelectMinOver(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createMinOverWindow(qb.instance, field))
}
// SelectMaxOver starts building a MAX(field) OVER window function.
//
// Example:
//
// .SelectMaxOver("price").PartitionBy("category").As("max_price").End()
func (qb *Query[T]) SelectMaxOver(field string) *QueryWindowBuilder[T] {
if qb.err != nil {
return newQueryWindowBuilder(qb, newWindowStateWithError(qb.instance, qb.err))
}
return newQueryWindowBuilder(qb, createMaxOverWindow(qb.instance, field))
}
// QueryWindowBuilder is now defined in window.go
// Exec executes the SELECT query with values from the provided params map.
// Returns a slice of pointers to all matching records.
//
// Example:
//
// params := map[string]any{"min_age": 18, "status": "active"}
// users, err := soy.Query().
// Where("age", ">=", "min_age").