From eb06255b667da417d982c6412c4602e932cc5283 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 1 Dec 2016 16:16:20 +0800 Subject: [PATCH] Skip order sql when quering with distinct --- preload_test.go | 6 +++--- scope.go | 4 ++-- search.go | 13 +++++++++++-- utils.go | 2 +- 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/preload_test.go b/preload_test.go index 6ca6980c..8b8b39b8 100644 --- a/preload_test.go +++ b/preload_test.go @@ -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{}, }, }, @@ -664,7 +664,7 @@ func TestNestedPreload10(t *testing.T) { }, }, { - Value: "bar 2", + Value: "bar 2", LevelA3s: []*LevelA3{}, }, } diff --git a/scope.go b/scope.go index fccb8134..ebde05a0 100644 --- a/scope.go +++ b/scope.go @@ -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 "" } @@ -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 } diff --git a/search.go b/search.go index 8ddc5b29..8a4f4df6 100644 --- a/search.go +++ b/search.go @@ -1,6 +1,9 @@ package gorm -import "fmt" +import ( + "fmt" + "regexp" +) type search struct { db *DB @@ -21,7 +24,7 @@ type search struct { tableName string raw bool Unscoped bool - countingQuery bool + ignoreOrderQuery bool } type searchPreload struct { @@ -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 } diff --git a/utils.go b/utils.go index ba1f08ab..8f3d0f38 100644 --- a/utils.go +++ b/utils.go @@ -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, "?") }