Fix Count with order by for PostgreSQL
This commit is contained in:
parent
9ff9be09c1
commit
c8a16ad75f
@ -321,16 +321,23 @@ func (db *DB) Count(count *int64) (tx *DB) {
|
||||
expr = clause.Expr{SQL: "COUNT(?)", Vars: []interface{}{clause.Column{Name: dbName}}}
|
||||
}
|
||||
}
|
||||
|
||||
tx.Statement.AddClause(clause.Select{Expression: expr})
|
||||
defer tx.Statement.AddClause(clause.Select{})
|
||||
}
|
||||
|
||||
// Count without ORDER BY for PostgreSQL
|
||||
orderBy := tx.Statement.Clauses["ORDER BY"]
|
||||
delete(tx.Statement.Clauses, "ORDER BY")
|
||||
defer func() {
|
||||
tx.Statement.Clauses["ORDER BY"] = orderBy
|
||||
}()
|
||||
|
||||
tx.Statement.Dest = count
|
||||
tx.callbacks.Query().Execute(tx)
|
||||
if tx.RowsAffected != 1 {
|
||||
*count = tx.RowsAffected
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -36,9 +36,12 @@ func TestCount(t *testing.T) {
|
||||
t.Errorf("Count() method should get correct value, expect: %v, got %v", count, len(users))
|
||||
}
|
||||
|
||||
if err := DB.Model(&User{}).Where("name = ?", user1.Name).Order("id desc").Count(&count).Find(&users).Error; err != nil {
|
||||
if err := DB.Model(&User{}).Where("id in ?", []uint{user1.ID, user2.ID, user3.ID}).Order("id DESC").Count(&count).Find(&users).Error; err != nil {
|
||||
t.Errorf(fmt.Sprintf("Count with order by should work, but got err %v", err))
|
||||
}
|
||||
if users[0].ID != user3.ID {
|
||||
t.Errorf(fmt.Sprintf("Find order by after Count, first item should id: %d, but got id: %d", user3.ID, users[0].ID))
|
||||
}
|
||||
|
||||
DB.Model(&User{}).Where("name = ?", user1.Name).Count(&count1).Or("name in ?", []string{user2.Name, user3.Name}).Count(&count2)
|
||||
if count1 != 1 || count2 != 3 {
|
||||
|
@ -7,9 +7,9 @@ require (
|
||||
github.com/jinzhu/now v1.1.1
|
||||
github.com/lib/pq v1.6.0
|
||||
gorm.io/driver/mysql v1.0.2
|
||||
gorm.io/driver/postgres v1.0.2
|
||||
gorm.io/driver/postgres v1.0.3
|
||||
gorm.io/driver/sqlite v1.1.3
|
||||
gorm.io/driver/sqlserver v1.0.4
|
||||
gorm.io/driver/sqlserver v1.0.5
|
||||
gorm.io/gorm v1.20.2
|
||||
)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user