fixed: clauseSelect.Columns missed when use Join And execute multiple query. (#4757)

This commit is contained in:
kinggo 2021-10-09 16:55:45 +08:00 committed by GitHub
parent bfda75d099
commit 418c60c83c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 7 deletions

View File

@ -95,7 +95,12 @@ func BuildQuerySQL(db *gorm.DB) {
}
// inline joins
if len(db.Statement.Joins) != 0 {
joins := []clause.Join{}
if fromClause, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok {
joins = fromClause.Joins
}
if len(db.Statement.Joins) != 0 || len(joins) != 0 {
if len(db.Statement.Selects) == 0 && db.Statement.Schema != nil {
clauseSelect.Columns = make([]clause.Column, len(db.Statement.Schema.DBNames))
for idx, dbName := range db.Statement.Schema.DBNames {
@ -103,12 +108,6 @@ func BuildQuerySQL(db *gorm.DB) {
}
}
joins := []clause.Join{}
if fromClause, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok {
joins = fromClause.Joins
}
for _, join := range db.Statement.Joins {
if db.Statement.Schema == nil {
joins = append(joins, clause.Join{

View File

@ -157,3 +157,30 @@ func TestJoinsWithSelect(t *testing.T) {
t.Errorf("Should find all two pets with Join select, got %+v", results)
}
}
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)
}
}