Skip to content

Commit

Permalink
Skip order sql when quering with distinct
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Dec 1, 2016
1 parent 066abce commit eb06255
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 8 deletions.
6 changes: 3 additions & 3 deletions preload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,11 +595,11 @@ func TestNestedPreload9(t *testing.T) {
Level2_1: Level2_1{
Level1s: []Level1{
{
Value: "value3-3",
Value: "value3-3",
Level0s: []Level0{},
},
{
Value: "value4-4",
Value: "value4-4",
Level0s: []Level0{},
},
},
Expand Down Expand Up @@ -664,7 +664,7 @@ func TestNestedPreload10(t *testing.T) {
},
},
{
Value: "bar 2",
Value: "bar 2",
LevelA3s: []*LevelA3{},
},
}
Expand Down
4 changes: 2 additions & 2 deletions scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ func (scope *Scope) selectSQL() string {
}

func (scope *Scope) orderSQL() string {
if len(scope.Search.orders) == 0 || scope.Search.countingQuery {
if len(scope.Search.orders) == 0 || scope.Search.ignoreOrderQuery {
return ""
}

Expand Down Expand Up @@ -927,7 +927,7 @@ func (scope *Scope) count(value interface{}) *Scope {
if query, ok := scope.Search.selects["query"]; !ok || !regexp.MustCompile("(?i)^count(.+)$").MatchString(fmt.Sprint(query)) {
scope.Search.Select("count(*)")
}
scope.Search.countingQuery = true
scope.Search.ignoreOrderQuery = true
scope.Err(scope.row().Scan(value))
return scope
}
Expand Down
13 changes: 11 additions & 2 deletions search.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package gorm

import "fmt"
import (
"fmt"
"regexp"
)

type search struct {
db *DB
Expand All @@ -21,7 +24,7 @@ type search struct {
tableName string
raw bool
Unscoped bool
countingQuery bool
ignoreOrderQuery bool
}

type searchPreload struct {
Expand Down Expand Up @@ -70,7 +73,13 @@ func (s *search) Order(value interface{}, reorder ...bool) *search {
return s
}

var distinctSQLRegexp = regexp.MustCompile(`(?i)distinct[^a-z]+[a-z]+`)

func (s *search) Select(query interface{}, args ...interface{}) *search {
if distinctSQLRegexp.MatchString(fmt.Sprint(query)) {
s.ignoreOrderQuery = true
}

s.selects = map[string]interface{}{"query": query, "args": args}
return s
}
Expand Down
2 changes: 1 addition & 1 deletion utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func toQueryMarks(primaryValues [][]interface{}) string {

for _, primaryValue := range primaryValues {
var marks []string
for _,_ = range primaryValue {
for _, _ = range primaryValue {
marks = append(marks, "?")
}

Expand Down

0 comments on commit eb06255

Please sign in to comment.