Skip to content

Commit

Permalink
preoload not allowd before count (#5023)
Browse files Browse the repository at this point in the history
Co-authored-by: ningfei <accelerator314@outlook.com>
  • Loading branch information
0fv and 0fx authored Jan 30, 2022
1 parent c0bea44 commit 8c36732
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,6 @@ var (
ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
// ErrInvalidValueOfLength invalid values do not match length
ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
// ErrPreloadNotAllowed preload is not allowed when count is used
ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
)
4 changes: 4 additions & 0 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,10 @@ func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB) {

func (db *DB) Count(count *int64) (tx *DB) {
tx = db.getInstance()
if len(tx.Statement.Preloads) > 0 {
tx.AddError(ErrPreloadNotAllowed)
return
}
if tx.Statement.Model == nil {
tx.Statement.Model = tx.Statement.Dest
defer func() {
Expand Down
10 changes: 10 additions & 0 deletions tests/count_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,14 @@ func TestCount(t *testing.T) {
if err := DB.Model(&User{}).Where("name = ?", "count-4").Group("name").Count(&count11).Error; err != nil || count11 != 1 {
t.Fatalf("Count should be 3, but got count: %v err %v", count11, err)
}

var count12 int64
if err := DB.Table("users").
Where("name in ?", []string{user1.Name, user2.Name, user3.Name}).
Preload("Toys", func(db *gorm.DB) *gorm.DB {
return db.Table("toys").Select("name")
}).Count(&count12).Error; err != gorm.ErrPreloadNotAllowed {
t.Errorf("should returns preload not allowed error, but got %v", err)
}

}

0 comments on commit 8c36732

Please # to comment.