Skip to content

Commit

Permalink
fix: AfterQuery should clear FROM Clause's Joins rather than the Stat…
Browse files Browse the repository at this point in the history
…ement
  • Loading branch information
贾一饼 authored and 贾一饼 committed May 17, 2024
1 parent 5e599a0 commit 93e9d08
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
6 changes: 5 additions & 1 deletion callbacks/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,11 @@ func Preload(db *gorm.DB) {

func AfterQuery(db *gorm.DB) {
// clear the joins after query because preload need it
db.Statement.Joins = nil
if v, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok {
fromClause := db.Statement.Clauses["FROM"]
fromClause.Expression = clause.From{Tables: v.Tables}
db.Statement.Clauses["FROM"] = fromClause
}
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 {
callMethod(db, func(value interface{}, tx *gorm.DB) bool {
if i, ok := value.(AfterFindInterface); ok {
Expand Down
8 changes: 5 additions & 3 deletions tests/joins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,21 +184,23 @@ func TestJoinCount(t *testing.T) {
DB.Create(&user)

query := DB.Model(&User{}).Joins("Company")
// Bug happens when .Count is called on a query.
// Removing the below two lines or downgrading to gorm v1.20.12 will make this test pass.

var total int64
query.Count(&total)

var result User

// Incorrectly generates a 'SELECT *' query which causes companies.id to overwrite users.id
if err := query.First(&result, user.ID).Error; err != nil {
t.Fatalf("Failed, got error: %v", err)
}

if result.ID != user.ID {
t.Fatalf("result's id, %d, doesn't match user's id, %d", result.ID, user.ID)
}
// should find company
if result.Company.ID != *user.CompanyID {
t.Fatalf("result's id, %d, doesn't match user's company id, %d", result.Company.ID, *user.CompanyID)
}
}

func TestJoinWithSoftDeleted(t *testing.T) {
Expand Down

0 comments on commit 93e9d08

Please sign in to comment.