From 8c3673286dc6091967e2349687f0dbbaa55d66f8 Mon Sep 17 00:00:00 2001 From: Ning Date: Sun, 30 Jan 2022 18:17:06 +0800 Subject: [PATCH] preoload not allowd before count (#5023) Co-authored-by: ningfei --- errors.go | 2 ++ finisher_api.go | 4 ++++ tests/count_test.go | 10 ++++++++++ 3 files changed, 16 insertions(+) diff --git a/errors.go b/errors.go index 145614d9..49cbfe64 100644 --- a/errors.go +++ b/errors.go @@ -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") ) diff --git a/finisher_api.go b/finisher_api.go index 355d89bd..cbbd48cb 100644 --- a/finisher_api.go +++ b/finisher_api.go @@ -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() { diff --git a/tests/count_test.go b/tests/count_test.go index 27d7ee60..b63a55fc 100644 --- a/tests/count_test.go +++ b/tests/count_test.go @@ -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) + } + }