-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselect.go
More file actions
1260 lines (1138 loc) · 37.6 KB
/
select.go
File metadata and controls
1260 lines (1138 loc) · 37.6 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"
"time"
"github.com/jmoiron/sqlx"
"github.com/zoobz-io/astql"
"github.com/zoobz-io/atom"
"github.com/zoobz-io/capitan"
"github.com/zoobz-io/sentinel"
"github.com/zoobz-io/soy/internal/scanner"
)
// soyExecutor provides the interface for executing queries.
// This allows s to access DB and table info without circular dependencies.
type soyExecutor interface {
execer() sqlx.ExtContext
getTableName() string
renderer() astql.Renderer
atomScanner() *scanner.Scanner
getMetadata() sentinel.Metadata
getInstance() *astql.ASTQL
callOnScan(ctx context.Context, result any) error
callOnRecord(ctx context.Context, record any) error
}
// Select provides a focused API for building SELECT queries that return a single record.
// It wraps ASTQL's functionality with a simple string-based interface.
// Use this for queries expected to return exactly one row (e.g., GET by ID, fetch one record).
type Select[T any] struct {
instance *astql.ASTQL
builder *astql.Builder
soy soyExecutor // interface for execution
err error // stores first error encountered during building
}
// Condition represents a WHERE condition with string-based components.
type Condition struct {
field string
operator string
param string
isNull bool
isBetween bool // true for BETWEEN/NOT BETWEEN
lowParam string // low value param for BETWEEN
highParam string // high value param for BETWEEN
}
// Note: operatorMap, directionMap, nullsMap, and validate* functions
// are defined in builder.go to avoid duplication.
// Fields specifies which fields to select. Field names must exist in the schema.
// If not called, SELECT * is used by default.
func (sb *Select[T]) Fields(fields ...string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = fieldsImpl(sb.instance, sb.builder, fields...)
return sb
}
// Where adds a simple WHERE condition with field = param pattern.
// Multiple calls are combined with AND.
//
// Example:
//
// .Where("email", "=", "user_email")
func (sb *Select[T]) Where(field, operator, param string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereImpl(sb.instance, sb.builder, field, operator, param)
return sb
}
// WhereAnd adds multiple conditions combined with AND.
//
// Example:
//
// .WhereAnd(
// soy.C("age", ">=", "min_age"),
// soy.C("age", "<=", "max_age"),
// )
func (sb *Select[T]) WhereAnd(conditions ...Condition) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereAndImpl(sb.instance, sb.builder, conditions...)
return sb
}
// WhereOr adds multiple conditions combined with OR.
//
// Example:
//
// .WhereOr(
// soy.C("status", "=", "active"),
// soy.C("status", "=", "pending"),
// )
func (sb *Select[T]) WhereOr(conditions ...Condition) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereOrImpl(sb.instance, sb.builder, conditions...)
return sb
}
// WhereNull adds a WHERE field IS NULL condition.
func (sb *Select[T]) WhereNull(field string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereNullImpl(sb.instance, sb.builder, field)
return sb
}
// WhereNotNull adds a WHERE field IS NOT NULL condition.
func (sb *Select[T]) WhereNotNull(field string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereNotNullImpl(sb.instance, sb.builder, field)
return sb
}
// 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 (sb *Select[T]) WhereBetween(field, lowParam, highParam string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereBetweenImpl(sb.instance, sb.builder, field, lowParam, highParam)
return sb
}
// 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 (sb *Select[T]) WhereNotBetween(field, lowParam, highParam string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereNotBetweenImpl(sb.instance, sb.builder, field, lowParam, highParam)
return sb
}
// 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 (sb *Select[T]) WhereFields(leftField, operator, rightField string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = whereFieldsImpl(sb.instance, sb.builder, leftField, operator, rightField)
return sb
}
// OrderBy adds an ORDER BY clause.
// Direction must be "asc" or "desc" (case insensitive).
func (sb *Select[T]) OrderBy(field string, direction string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = orderByImpl(sb.instance, sb.builder, field, direction)
return sb
}
// 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 (sb *Select[T]) OrderByNulls(field, direction, nulls string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = orderByNullsImpl(sb.instance, sb.builder, field, direction, nulls)
return sb
}
// 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 (sb *Select[T]) OrderByExpr(field, operator, param, direction string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = orderByExprImpl(sb.instance, sb.builder, field, operator, param, direction)
return sb
}
// 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 (sb *Select[T]) SelectExpr(field, operator, param, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectExprImpl(sb.instance, sb.builder, field, operator, param, alias)
return sb
}
// Limit sets the LIMIT clause to a static integer value.
func (sb *Select[T]) Limit(n int) *Select[T] {
sb.builder = sb.builder.Limit(n)
return sb
}
// 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 (sb *Select[T]) LimitParam(param string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = limitParamImpl(sb.instance, sb.builder, param)
return sb
}
// Offset sets the OFFSET clause to a static integer value.
func (sb *Select[T]) Offset(n int) *Select[T] {
sb.builder = sb.builder.Offset(n)
return sb
}
// 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 (sb *Select[T]) OffsetParam(param string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = offsetParamImpl(sb.instance, sb.builder, param)
return sb
}
// Distinct adds DISTINCT to the SELECT query.
func (sb *Select[T]) Distinct() *Select[T] {
sb.builder = sb.builder.Distinct()
return sb
}
// 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 (sb *Select[T]) DistinctOn(fields ...string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = distinctOnImpl(sb.instance, sb.builder, fields...)
return sb
}
// GroupBy adds a GROUP BY clause.
// Multiple calls add additional grouping fields.
//
// Example:
//
// .GroupBy("status").GroupBy("category")
func (sb *Select[T]) GroupBy(fields ...string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = groupByImpl(sb.instance, sb.builder, fields...)
return sb
}
// Having adds a HAVING condition. Must be used after GroupBy.
// Multiple calls are combined with AND.
//
// Example:
//
// .GroupBy("status").Having("age", ">", "min_age")
func (sb *Select[T]) Having(field, operator, param string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = havingImpl(sb.instance, sb.builder, field, operator, param)
return sb
}
// 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 (sb *Select[T]) HavingAgg(aggFunc, field, operator, param string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = havingAggImpl(sb.instance, sb.builder, aggFunc, field, operator, param)
return sb
}
// ForUpdate adds FOR UPDATE row locking to the SELECT query.
// Locks selected rows for update, blocking other transactions from modifying them.
func (sb *Select[T]) ForUpdate() *Select[T] {
sb.builder = sb.builder.ForUpdate()
return sb
}
// 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 (sb *Select[T]) ForNoKeyUpdate() *Select[T] {
sb.builder = sb.builder.ForNoKeyUpdate()
return sb
}
// 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 (sb *Select[T]) ForShare() *Select[T] {
sb.builder = sb.builder.ForShare()
return sb
}
// ForKeyShare adds FOR KEY SHARE row locking to the SELECT query.
// The weakest lock level, blocks only FOR UPDATE but allows other locks.
func (sb *Select[T]) ForKeyShare() *Select[T] {
sb.builder = sb.builder.ForKeyShare()
return sb
}
// --- 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 (sb *Select[T]) SelectUpper(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectUpperImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectLower adds LOWER(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLower("email", "lower_email") // SELECT LOWER("email") AS "lower_email"
func (sb *Select[T]) SelectLower(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectLowerImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectLength adds LENGTH(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLength("name", "name_length") // SELECT LENGTH("name") AS "name_length"
func (sb *Select[T]) SelectLength(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectLengthImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectTrim adds TRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectTrim("name", "trimmed_name") // SELECT TRIM("name") AS "trimmed_name"
func (sb *Select[T]) SelectTrim(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectTrimImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectLTrim adds LTRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectLTrim("name", "ltrimmed") // SELECT LTRIM("name") AS "ltrimmed"
func (sb *Select[T]) SelectLTrim(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectLTrimImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectRTrim adds RTRIM(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectRTrim("name", "rtrimmed") // SELECT RTRIM("name") AS "rtrimmed"
func (sb *Select[T]) SelectRTrim(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectRTrimImpl(sb.instance, sb.builder, field, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectAbs(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectAbsImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectCeil adds CEIL(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCeil("price", "rounded_up") // SELECT CEIL("price") AS "rounded_up"
func (sb *Select[T]) SelectCeil(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCeilImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectFloor adds FLOOR(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectFloor("price", "rounded_down") // SELECT FLOOR("price") AS "rounded_down"
func (sb *Select[T]) SelectFloor(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectFloorImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectRound adds ROUND(field) AS alias to the SELECT clause (no precision).
//
// Example:
//
// .SelectRound("price", "rounded") // SELECT ROUND("price") AS "rounded"
func (sb *Select[T]) SelectRound(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectRoundImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectSqrt adds SQRT(field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectSqrt("variance", "std_dev") // SELECT SQRT("variance") AS "std_dev"
func (sb *Select[T]) SelectSqrt(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectSqrtImpl(sb.instance, sb.builder, field, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectCast(field string, castType CastType, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCastImpl(sb.instance, sb.builder, field, castType, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectNow(alias string) *Select[T] {
sb.builder = sb.builder.SelectExpr(astql.As(astql.Now(), alias))
return sb
}
// SelectCurrentDate adds CURRENT_DATE AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentDate("today") // SELECT CURRENT_DATE AS "today"
func (sb *Select[T]) SelectCurrentDate(alias string) *Select[T] {
sb.builder = sb.builder.SelectExpr(astql.As(astql.CurrentDate(), alias))
return sb
}
// SelectCurrentTime adds CURRENT_TIME AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentTime("now_time") // SELECT CURRENT_TIME AS "now_time"
func (sb *Select[T]) SelectCurrentTime(alias string) *Select[T] {
sb.builder = sb.builder.SelectExpr(astql.As(astql.CurrentTime(), alias))
return sb
}
// SelectCurrentTimestamp adds CURRENT_TIMESTAMP AS alias to the SELECT clause.
//
// Example:
//
// .SelectCurrentTimestamp("ts") // SELECT CURRENT_TIMESTAMP AS "ts"
func (sb *Select[T]) SelectCurrentTimestamp(alias string) *Select[T] {
sb.builder = sb.builder.SelectExpr(astql.As(astql.CurrentTimestamp(), alias))
return sb
}
// --- Aggregate Expression Methods ---
// SelectCountStar adds COUNT(*) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectCountStar("count") // SELECT COUNT(*) AS "count"
func (sb *Select[T]) SelectCountStar(alias string) *Select[T] {
sb.builder = sb.builder.SelectExpr(astql.As(astql.CountStar(), alias))
return sb
}
// SelectCount adds COUNT(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectCount("id", "count") // SELECT COUNT("id") AS "count"
func (sb *Select[T]) SelectCount(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCountImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectCountDistinct adds COUNT(DISTINCT field) AS alias to the SELECT clause.
//
// Example:
//
// .SelectCountDistinct("email", "unique_emails") // SELECT COUNT(DISTINCT "email") AS "unique_emails"
func (sb *Select[T]) SelectCountDistinct(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCountDistinctImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectSum adds SUM(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectSum("amount", "total") // SELECT SUM("amount") AS "total"
func (sb *Select[T]) SelectSum(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectSumImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectAvg adds AVG(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectAvg("age", "avg_age") // SELECT AVG("age") AS "avg_age"
func (sb *Select[T]) SelectAvg(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectAvgImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectMin adds MIN(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectMin("age", "youngest") // SELECT MIN("age") AS "youngest"
func (sb *Select[T]) SelectMin(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectMinImpl(sb.instance, sb.builder, field, alias)
return sb
}
// SelectMax adds MAX(field) AS alias to the SELECT clause.
//
// Example:
//
// .GroupBy("status").SelectMax("age", "oldest") // SELECT MAX("age") AS "oldest"
func (sb *Select[T]) SelectMax(field, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectMaxImpl(sb.instance, sb.builder, field, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectSumFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectSumFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// 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 (sb *Select[T]) SelectAvgFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectAvgFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// SelectMinFilter adds MIN(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectMinFilter("price", "category", "=", "electronics", "min_electronics")
func (sb *Select[T]) SelectMinFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectMinFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// SelectMaxFilter adds MAX(field) FILTER (WHERE condition) AS alias to the SELECT clause.
//
// Example:
//
// .SelectMaxFilter("score", "passed", "=", "true", "max_passed")
func (sb *Select[T]) SelectMaxFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectMaxFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// 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 (sb *Select[T]) SelectCountFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCountFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// SelectCountDistinctFilter adds COUNT(DISTINCT field) FILTER (WHERE condition) AS alias.
//
// Example:
//
// .SelectCountDistinctFilter("email", "verified", "=", "true", "verified_users")
func (sb *Select[T]) SelectCountDistinctFilter(field, condField, condOp, condParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCountDistinctFilterImpl(sb.instance, sb.builder, field, condField, condOp, condParam, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectSubstring(field, startParam, lengthParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectSubstringImpl(sb.instance, sb.builder, field, startParam, lengthParam, alias)
return sb
}
// 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 (sb *Select[T]) SelectReplace(field, searchParam, replacementParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectReplaceImpl(sb.instance, sb.builder, field, searchParam, replacementParam, alias)
return sb
}
// 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 (sb *Select[T]) SelectConcat(alias string, fields ...string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectConcatImpl(sb.instance, sb.builder, alias, fields...)
return sb
}
// --- 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 (sb *Select[T]) SelectPower(field, exponentParam, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectPowerImpl(sb.instance, sb.builder, field, exponentParam, alias)
return sb
}
// --- 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 (sb *Select[T]) SelectCoalesce(alias string, params ...string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectCoalesceImpl(sb.instance, sb.builder, alias, params...)
return sb
}
// 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 (sb *Select[T]) SelectNullIf(param1, param2, alias string) *Select[T] {
if sb.err != nil {
return sb
}
sb.builder, sb.err = selectNullIfImpl(sb.instance, sb.builder, param1, param2, alias)
return sb
}
// --- CASE Expression Methods ---
// SelectCase starts building a CASE expression for the SELECT clause.
// Returns a SelectCaseBuilder that allows chaining When/Else/As clauses.
// Call End() to complete the CASE expression and return to the Select builder.
//
// Example:
//
// soy.Select().
// SelectCase().
// When("status", "=", "status_active", "result_active").
// When("status", "=", "status_pending", "result_pending").
// Else("result_default").
// As("status_label").
// End().
// Exec(ctx, params)
func (sb *Select[T]) SelectCase() *SelectCaseBuilder[T] {
return newSelectCaseBuilder(sb)
}
// SelectCaseBuilder is now defined in case.go
// --- Window Function Methods ---
// SelectRowNumber starts building a ROW_NUMBER() window function.
// Returns a SelectWindowBuilder for configuring the window specification.
//
// Example:
//
// soy.Select().
// SelectRowNumber().
// OrderBy("created_at", "DESC").
// As("row_num").
// End()
func (sb *Select[T]) SelectRowNumber() *SelectWindowBuilder[T] {
return newSelectWindowBuilder(sb, createRowNumberWindow(sb.instance))
}
// SelectRank starts building a RANK() window function.
//
// Example:
//
// .SelectRank().OrderBy("score", "DESC").As("rank").End()
func (sb *Select[T]) SelectRank() *SelectWindowBuilder[T] {
return newSelectWindowBuilder(sb, createRankWindow(sb.instance))
}
// SelectDenseRank starts building a DENSE_RANK() window function.
//
// Example:
//
// .SelectDenseRank().OrderBy("score", "DESC").As("dense_rank").End()
func (sb *Select[T]) SelectDenseRank() *SelectWindowBuilder[T] {
return newSelectWindowBuilder(sb, createDenseRankWindow(sb.instance))
}
// SelectNtile starts building an NTILE(n) window function.
//
// Example:
//
// .SelectNtile("num_buckets").OrderBy("value", "ASC").As("quartile").End()
func (sb *Select[T]) SelectNtile(nParam string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createNtileWindow(sb.instance, nParam))
}
// SelectLag starts building a LAG(field, offset) window function.
//
// Example:
//
// .SelectLag("price", "offset").OrderBy("date", "ASC").As("prev_price").End()
func (sb *Select[T]) SelectLag(field, offsetParam string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createLagWindow(sb.instance, field, offsetParam))
}
// SelectLead starts building a LEAD(field, offset) window function.
//
// Example:
//
// .SelectLead("price", "offset").OrderBy("date", "ASC").As("next_price").End()
func (sb *Select[T]) SelectLead(field, offsetParam string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createLeadWindow(sb.instance, field, offsetParam))
}
// SelectFirstValue starts building a FIRST_VALUE(field) window function.
//
// Example:
//
// .SelectFirstValue("price").OrderBy("date", "ASC").As("first_price").End()
func (sb *Select[T]) SelectFirstValue(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createFirstValueWindow(sb.instance, field))
}
// SelectLastValue starts building a LAST_VALUE(field) window function.
//
// Example:
//
// .SelectLastValue("price").OrderBy("date", "ASC").As("last_price").End()
func (sb *Select[T]) SelectLastValue(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createLastValueWindow(sb.instance, field))
}
// SelectSumOver starts building a SUM(field) OVER window function.
//
// Example:
//
// .SelectSumOver("amount").PartitionBy("category").As("running_total").End()
func (sb *Select[T]) SelectSumOver(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createSumOverWindow(sb.instance, field))
}
// SelectAvgOver starts building an AVG(field) OVER window function.
//
// Example:
//
// .SelectAvgOver("score").PartitionBy("category").As("avg_score").End()
func (sb *Select[T]) SelectAvgOver(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createAvgOverWindow(sb.instance, field))
}
// SelectCountOver starts building a COUNT(*) OVER window function.
//
// Example:
//
// .SelectCountOver().PartitionBy("category").As("category_count").End()
func (sb *Select[T]) SelectCountOver() *SelectWindowBuilder[T] {
return newSelectWindowBuilder(sb, createCountOverWindow(sb.instance))
}
// SelectMinOver starts building a MIN(field) OVER window function.
//
// Example:
//
// .SelectMinOver("price").PartitionBy("category").As("min_price").End()
func (sb *Select[T]) SelectMinOver(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createMinOverWindow(sb.instance, field))
}
// SelectMaxOver starts building a MAX(field) OVER window function.
//
// Example:
//
// .SelectMaxOver("price").PartitionBy("category").As("max_price").End()
func (sb *Select[T]) SelectMaxOver(field string) *SelectWindowBuilder[T] {
if sb.err != nil {
return newSelectWindowBuilder(sb, newWindowStateWithError(sb.instance, sb.err))
}
return newSelectWindowBuilder(sb, createMaxOverWindow(sb.instance, field))
}