Skip to content

Commit

Permalink
feat(#282): allow ordering by case expression
Browse files Browse the repository at this point in the history
  • Loading branch information
doug-martin committed Aug 28, 2021
1 parent ce33bd7 commit dd8222f
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
3 changes: 3 additions & 0 deletions exp/case.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,6 @@ func (c caseExpression) Else(result interface{}) CaseExpression {
c.elseCondition = NewCaseElse(result)
return c
}

func (c caseExpression) Asc() OrderedExpression { return asc(c) }
func (c caseExpression) Desc() OrderedExpression { return desc(c) }
10 changes: 10 additions & 0 deletions exp/case_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ func (ces *caseExpressionSuite) TestElse() {
ces.Nil(ce.GetElse())
}

func (ces *caseExpressionSuite) TestAsc() {
ce := exp.NewCaseExpression()
ces.Equal(exp.NewOrderedExpression(ce, exp.AscDir, exp.NoNullsSortType), ce.Asc())
}

func (ces *caseExpressionSuite) TestDesc() {
ce := exp.NewCaseExpression()
ces.Equal(exp.NewOrderedExpression(ce, exp.DescSortDir, exp.NoNullsSortType), ce.Desc())
}

type caseWhenSuite struct {
suite.Suite
}
Expand Down
1 change: 1 addition & 0 deletions exp/exp.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,7 @@ type (
CaseExpression interface {
Expression
Aliaseable
Orderable
GetValue() interface{}
GetWhens() []CaseWhen
GetElse() CaseElse
Expand Down
8 changes: 8 additions & 0 deletions select_dataset_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,14 @@ func ExampleSelectDataset_Order() {
// SELECT * FROM "test" ORDER BY "a" ASC
}

func ExampleSelectDataset_Order_caseExpression() {
ds := goqu.From("test").Order(goqu.Case().When(goqu.C("num").Gt(10), 0).Else(1).Asc())
sql, _, _ := ds.ToSQL()
fmt.Println(sql)
// Output:
// SELECT * FROM "test" ORDER BY CASE WHEN ("num" > 10) THEN 0 ELSE 1 END ASC
}

func ExampleSelectDataset_OrderAppend() {
ds := goqu.From("test").Order(goqu.C("a").Asc())
sql, _, _ := ds.OrderAppend(goqu.C("b").Desc().NullsLast()).ToSQL()
Expand Down

0 comments on commit dd8222f

Please sign in to comment.