Skip to content

Commit

Permalink
Add ORDER BY sql expression support
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jun 28, 2016
1 parent 321d10b commit c1c4f9f
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 10 deletions.
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,10 @@ func (s *DB) Offset(offset interface{}) *DB {
}

// Order specify order when retrieve records from database, set reorder to `true` to overwrite defined conditions
func (s *DB) Order(value string, reorder ...bool) *DB {
// db.Order("name DESC")
// db.Order("name DESC", true) // reorder
// db.Order(gorm.Expr("name = ? DESC", "first")) // sql expression
func (s *DB) Order(value interface{}, reorder ...bool) *DB {
return s.clone().search.Order(value, reorder...).db
}

Expand Down
6 changes: 6 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,12 @@ func TestOrderAndPluck(t *testing.T) {
DB.Save(&user1).Save(&user2).Save(&user3)
scopedb := DB.Model(&User{}).Where("name like ?", "%OrderPluckUser%")

var user User
scopedb.Order(gorm.Expr("name = ? DESC", "OrderPluckUser2")).First(&user)
if user.Name != "OrderPluckUser2" {
t.Errorf("Order with sql expression")
}

var ages []int64
scopedb.Order("age desc").Pluck("age", &ages)
if ages[0] != 20 {
Expand Down
10 changes: 9 additions & 1 deletion scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,15 @@ func (scope *Scope) orderSQL() string {

var orders []string
for _, order := range scope.Search.orders {
orders = append(orders, scope.quoteIfPossible(order))
if str, ok := order.(string); ok {
orders = append(orders, scope.quoteIfPossible(str))
} else if expr, ok := order.(*expr); ok {
exp := expr.expr
for _, arg := range expr.args {
exp = strings.Replace(exp, "?", scope.AddToVars(arg), 1)
}
orders = append(orders, exp)
}
}
return " ORDER BY " + strings.Join(orders, ",")
}
Expand Down
14 changes: 6 additions & 8 deletions search.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type search struct {
assignAttrs []interface{}
selects map[string]interface{}
omits []string
orders []string
orders []interface{}
preload []searchPreload
offset interface{}
limit interface{}
Expand Down Expand Up @@ -59,14 +59,12 @@ func (s *search) Assign(attrs ...interface{}) *search {
return s
}

func (s *search) Order(value string, reorder ...bool) *search {
func (s *search) Order(value interface{}, reorder ...bool) *search {
if len(reorder) > 0 && reorder[0] {
if value != "" {
s.orders = []string{value}
} else {
s.orders = []string{}
}
} else if value != "" {
s.orders = []interface{}{}
}

if value != nil {
s.orders = append(s.orders, value)
}
return s
Expand Down

0 comments on commit c1c4f9f

Please sign in to comment.