Skip to content

Commit

Permalink
Allow passing args to Order (#630)
Browse files Browse the repository at this point in the history
  • Loading branch information
duckbrain authored Apr 13, 2021
1 parent fbf43b4 commit 1b7b5ef
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
8 changes: 4 additions & 4 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,19 +145,19 @@ func (q *Query) Where(stmt string, args ...interface{}) *Query {
// Order will append an order clause to the query.
//
// c.Order("name desc")
func (c *Connection) Order(stmt string) *Query {
return Q(c).Order(stmt)
func (c *Connection) Order(stmt string, args ...interface{}) *Query {
return Q(c).Order(stmt, args...)
}

// Order will append an order clause to the query.
//
// q.Order("name desc")
func (q *Query) Order(stmt string) *Query {
func (q *Query) Order(stmt string, args ...interface{}) *Query {
if q.RawSQL.Fragment != "" {
log(logging.Warn, "Query is setup to use raw SQL")
return q
}
q.orderClauses = append(q.orderClauses, clause{stmt, []interface{}{}})
q.orderClauses = append(q.orderClauses, clause{stmt, args})
return q
}

Expand Down
28 changes: 28 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,34 @@ func Test_Order(t *testing.T) {
a.Equal(ts("SELECT enemies.A FROM enemies AS enemies ORDER BY id desc, name desc"), sql)
}

func Test_Order_With_Args(t *testing.T) {
if PDB == nil {
t.Skip("skipping integration tests")
}
r := require.New(t)
transaction(func(tx *Connection) {
u1 := &Song{Title: "A"}
u2 := &Song{Title: "B"}
u3 := &Song{Title: "C"}
err := tx.Create(u1)
r.NoError(err)
err = tx.Create(u2)
r.NoError(err)
err = tx.Create(u3)
r.NoError(err)

var songs []Song
err = tx.Where("id in (?)", []uuid.UUID{u1.ID, u2.ID, u3.ID}).
Order("title > ? DESC", "A").Order("title").
All(&songs)
r.NoError(err)
r.Len(songs, 3)
r.Equal("B", songs[0].Title)
r.Equal("C", songs[1].Title)
r.Equal("A", songs[2].Title)
})
}

func Test_GroupBy(t *testing.T) {
if PDB == nil {
t.Skip("skipping integration tests")
Expand Down

0 comments on commit 1b7b5ef

Please sign in to comment.