From cf7fbb56d5d24487edebf38c34c52b71c466d13b Mon Sep 17 00:00:00 2001 From: smacker Date: Wed, 26 Oct 2016 21:30:20 +0700 Subject: [PATCH] db.Raw().First() makes wrong sql fix #1214 --- query_test.go | 18 ++++++++++++++++++ scope.go | 9 +++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/query_test.go b/query_test.go index 854beb6d..0aceaf80 100644 --- a/query_test.go +++ b/query_test.go @@ -55,6 +55,24 @@ func TestFirstAndLastWithNoStdPrimaryKey(t *testing.T) { } } +func TestFirstAndLastWithRaw(t *testing.T) { + user1 := User{Name: "user", Emails: []Email{{Email: "user1@example.com"}}} + user2 := User{Name: "user", Emails: []Email{{Email: "user2@example.com"}}} + DB.Save(&user1) + DB.Save(&user2) + + var user3, user4 User + DB.Raw("select * from users WHERE name = ?", "user").First(&user3) + if user3.Id != user1.Id { + t.Errorf("Find first record with raw") + } + + DB.Raw("select * from users WHERE name = ?", "user").Last(&user4) + if user4.Id != user2.Id { + t.Errorf("Find last record with raw") + } +} + func TestUIntPrimaryKey(t *testing.T) { var animal Animal DB.First(&animal, uint64(1)) diff --git a/scope.go b/scope.go index 4c9c7922..0240ed09 100644 --- a/scope.go +++ b/scope.go @@ -329,7 +329,12 @@ func (scope *Scope) QuotedTableName() (name string) { // CombinedConditionSql return combined condition sql func (scope *Scope) CombinedConditionSql() string { - return scope.joinsSQL() + scope.whereSQL() + scope.groupSQL() + + joinSql := scope.joinsSQL() + whereSql := scope.whereSQL() + if scope.Search.raw { + whereSql = strings.TrimSuffix(strings.TrimPrefix(whereSql, "WHERE ("), ")") + } + return joinSql + whereSql + scope.groupSQL() + scope.havingSQL() + scope.orderSQL() + scope.limitAndOffsetSQL() } @@ -792,7 +797,7 @@ func (scope *Scope) joinsSQL() string { func (scope *Scope) prepareQuerySQL() { if scope.Search.raw { - scope.Raw(strings.TrimSuffix(strings.TrimPrefix(scope.CombinedConditionSql(), " WHERE ("), ")")) + scope.Raw(scope.CombinedConditionSql()) } else { scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql())) }