Apply gorm:query_option in Count() (#2410)

Apply gorm:query_option in Count()
This commit is contained in:
Emir Beganović 2019-04-30 17:47:00 +04:00 committed by GitHub
commit 2cd73627bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -1,6 +1,9 @@
package gorm package gorm
import "database/sql" import (
"database/sql"
"fmt"
)
// Define callbacks for row query // Define callbacks for row query
func init() { func init() {
@ -20,6 +23,9 @@ type RowsQueryResult struct {
func rowQueryCallback(scope *Scope) { func rowQueryCallback(scope *Scope) {
if result, ok := scope.InstanceGet("row_query_result"); ok { if result, ok := scope.InstanceGet("row_query_result"); ok {
scope.prepareQuerySQL() scope.prepareQuerySQL()
if str, ok := scope.Get("gorm:query_option"); ok {
scope.SQL += addExtraSpaceIfExist(fmt.Sprint(str))
}
if rowResult, ok := result.(*RowQueryResult); ok { if rowResult, ok := result.(*RowQueryResult); ok {
rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...) rowResult.Row = scope.SQLDB().QueryRow(scope.SQL, scope.SQLVars...)

View File

@ -1110,6 +1110,29 @@ func TestCountWithHaving(t *testing.T) {
} }
} }
func TestCountWithQueryOption(t *testing.T) {
db := DB.New()
db.Delete(User{})
defer db.Delete(User{})
DB.Create(&User{Name: "user1"})
DB.Create(&User{Name: "user2"})
DB.Create(&User{Name: "user3"})
var count int
err := db.Model(User{}).Select("users.id").
Set("gorm:query_option", "WHERE users.name='user2'").
Count(&count).Error
if err != nil {
t.Error("Unexpected error on query count with query_option")
}
if count != 1 {
t.Error("Unexpected result on query count with query_option")
}
}
func BenchmarkGorm(b *testing.B) { func BenchmarkGorm(b *testing.B) {
b.N = 2000 b.N = 2000
for x := 0; x < b.N; x++ { for x := 0; x < b.N; x++ {