Merge pull request #1243 from smacker/raw_first_last

db.Raw().First() makes wrong sql fix #1214
This commit is contained in:
Jinzhu 2016-11-03 21:45:29 +08:00 committed by GitHub
commit f2fe351aa0
2 changed files with 25 additions and 2 deletions

View File

@ -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) { func TestUIntPrimaryKey(t *testing.T) {
var animal Animal var animal Animal
DB.First(&animal, uint64(1)) DB.First(&animal, uint64(1))

View File

@ -329,7 +329,12 @@ func (scope *Scope) QuotedTableName() (name string) {
// CombinedConditionSql return combined condition sql // CombinedConditionSql return combined condition sql
func (scope *Scope) CombinedConditionSql() string { 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() scope.havingSQL() + scope.orderSQL() + scope.limitAndOffsetSQL()
} }
@ -792,7 +797,7 @@ func (scope *Scope) joinsSQL() string {
func (scope *Scope) prepareQuerySQL() { func (scope *Scope) prepareQuerySQL() {
if scope.Search.raw { if scope.Search.raw {
scope.Raw(strings.TrimSuffix(strings.TrimPrefix(scope.CombinedConditionSql(), " WHERE ("), ")")) scope.Raw(scope.CombinedConditionSql())
} else { } else {
scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql())) scope.Raw(fmt.Sprintf("SELECT %v FROM %v %v", scope.selectSQL(), scope.QuotedTableName(), scope.CombinedConditionSql()))
} }