Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: AfterQuery should clear FROM Clause's Joins rather than the Stat… #7027

Merged
merged 1 commit into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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, Joins: v.Joins[:len(v.Joins)-len(db.Statement.Joins)]} // keep the original From Joins
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
Loading