From d21eed4b6623ab76f67977fc1f151a43a1541480 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 5 Aug 2015 15:58:11 +0800 Subject: [PATCH] Don't include Order for counting sql --- scope_private.go | 20 ++++++++++++-------- search.go | 1 + 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/scope_private.go b/scope_private.go index 1d906e76..08da634e 100644 --- a/scope_private.go +++ b/scope_private.go @@ -206,15 +206,19 @@ func (scope *Scope) whereSql() (sql string) { return } +var hasCountRegexp = regexp.MustCompile(`(?i)count(.+)`) + func (scope *Scope) selectSql() string { if len(scope.Search.selects) == 0 { return "*" } + sql := scope.buildSelectQuery(scope.Search.selects) + scope.Search.countingQuery = hasCountRegexp.MatchString(sql) return scope.buildSelectQuery(scope.Search.selects) } func (scope *Scope) orderSql() string { - if len(scope.Search.orders) == 0 { + if len(scope.Search.orders) == 0 || scope.Search.countingQuery { return "" } return " ORDER BY " + strings.Join(scope.Search.orders, ",") @@ -466,14 +470,14 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope { } /** - Return the table options string or an empty string if the table options does not exist + Return the table options string or an empty string if the table options does not exist */ -func (scope *Scope) getTableOptions() string{ - tableOptions, ok := scope.Get("gorm:table_options") - if !ok { - return "" - } - return tableOptions.(string) +func (scope *Scope) getTableOptions() string { + tableOptions, ok := scope.Get("gorm:table_options") + if !ok { + return "" + } + return tableOptions.(string) } func (scope *Scope) createJoinTable(field *StructField) { diff --git a/search.go b/search.go index 2c3df2d1..ee3d494c 100644 --- a/search.go +++ b/search.go @@ -21,6 +21,7 @@ type search struct { tableName string raw bool Unscoped bool + countingQuery bool } type searchPreload struct {