@@ -426,10 +426,36 @@ func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder {
426
426
return b
427
427
}
428
428
429
+ // OrderNullsType is used to specify the order of NULLs in ORDER BY clause.
430
+ type OrderNullsType int
431
+
432
+ const (
433
+ OrderNullsUndefined OrderNullsType = iota
434
+ OrderNullsFirst // ORDER BY ... NULLS FIRST
435
+ OrderNullsLast // ORDER BY ... NULLS LAST
436
+ )
437
+
438
+ // String returns the string representation of the order of NULLs.
439
+ func (o OrderNullsType ) String () string {
440
+ if o == OrderNullsFirst {
441
+ return "FIRST"
442
+ }
443
+ if o == OrderNullsLast {
444
+ return "LAST"
445
+ }
446
+ return ""
447
+ }
448
+
449
+ // OrderByCondOption is used to specify additional options for OrderByCond.
450
+ type OrderByCondOption struct {
451
+ ColumnID int
452
+ NullsType OrderNullsType
453
+ }
454
+
429
455
// OrderByCond adds ORDER BY expressions with direction to the query.
430
456
// The columns map is used to map OrderCond.ColumnID to the column name.
431
457
// Can be used to avoid hardcoding column names in the code.
432
- func (b SelectBuilder ) OrderByCond (columns map [int ]string , conds []OrderCond ) SelectBuilder {
458
+ func (b SelectBuilder ) OrderByCond (columns map [int ]string , conds []OrderCond , opts ... OrderByCondOption ) SelectBuilder {
433
459
for i , cond := range conds {
434
460
if pos := slices .IndexFunc (conds [:i ], func (c OrderCond ) bool {
435
461
return c .ColumnID == cond .ColumnID
@@ -442,7 +468,19 @@ func (b SelectBuilder) OrderByCond(columns map[int]string, conds []OrderCond) Se
442
468
panic (fmt .Sprintf ("column id %d not found in columns map %v" , cond .ColumnID , columns ))
443
469
}
444
470
445
- b = b .OrderByClause (fmt .Sprintf ("%s %s" , column , cond .Direction .String ()))
471
+ nullsType := OrderNullsUndefined
472
+ for _ , opt := range opts {
473
+ if opt .ColumnID == cond .ColumnID {
474
+ nullsType = opt .NullsType
475
+ break
476
+ }
477
+ }
478
+
479
+ if nullsType == OrderNullsUndefined {
480
+ b = b .OrderByClause (fmt .Sprintf ("%s %s" , column , cond .Direction .String ()))
481
+ } else {
482
+ b = b .OrderByClause (fmt .Sprintf ("%s %s NULLS %s" , column , cond .Direction .String (), nullsType .String ()))
483
+ }
446
484
}
447
485
448
486
return b
0 commit comments