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 : clauseSelect.Columns missed when use Join And execute multiple query. #4757

Merged
merged 1 commit into from Oct 9, 2021
Merged

fix : clauseSelect.Columns missed when use Join And execute multiple query. #4757

merged 1 commit into from Oct 9, 2021

Conversation

ghost
Copy link

@ghost ghost commented Oct 9, 2021

  • [] Do only one thing
  • [] Non breaking API changes
  • [] Tested

What did this pull request do?

fixed: clauseSelect.Columns missed when use Join And execute multiple query.

PR for #4746

User Case Description

run following code:

func TestJoinCount(t *testing.T) {
	companyA := Company{Name: "A"}
	companyB := Company{Name: "B"}
	DB.Create(&companyA)
	DB.Create(&companyB)

	user := User{Name: "kingGo", CompanyID: &companyB.ID}
	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)
	}
}

run it use gorm v1.21.15 will failed, actual query SQL:

SELECT * FROM `users` LEFT JOIN `companies` `Company`
ON `users`.`company_id` = `Company`.`id`
WHERE `users`.`deleted_at` IS NULL AND `users`.`id` = 1 ORDER BY `users`.`id` LIMIT 1

run it use gorm v1.20.12 will succeed, actual query SQL:

SELECT `users`.`id`,`users`.`created_at`,`users`.`updated_at`,`users`.`deleted_at`,`users`.`name`,`users`.`age`,`users`.`birthday`,`users`.`company_id`,`users`.`manager_id`,`users`.`active`,`Company`.`id` AS `Company__id`,`Company`.`name` AS `Company__name`
FROM `users` LEFT JOIN `companies` `Company`
ON `users`.`company_id` = `Company`.`id`
WHERE `users`.`id` = 1 AND `users`.`deleted_at` IS NULL ORDER BY `users`.`id` LIMIT 1

@ghost ghost changed the title fixed: clauseSelect.Columns missed when use Join And execute multiple query. fix : clauseSelect.Columns missed when use Join And execute multiple query. Oct 9, 2021
@jinzhu jinzhu merged commit 418c60c into go-gorm:master Oct 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants