mirror of https://github.com/go-gorm/gorm.git
db.Raw().First() makes wrong sql fix #1214
This commit is contained in:
parent
56a7d1b69e
commit
cf7fbb56d5
|
@ -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))
|
||||||
|
|
9
scope.go
9
scope.go
|
@ -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()))
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue