fix empty QueryClauses in association (#5502) (#5503)

* fix empty QueryClauses in association (#5502)

* test: empty QueryClauses in association (#5502)

* style: empty QueryClauses in association (#5502)

* style: empty QueryClauses in association (#5502)
This commit is contained in:
Goxiaoy 2022-07-15 11:15:18 +08:00 committed by GitHub
parent 099813bf11
commit 2ba599e8b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 1 deletions

View File

@ -507,7 +507,9 @@ func (association *Association) buildCondition() *DB {
joinStmt.AddClause(queryClause)
}
joinStmt.Build("WHERE")
tx.Clauses(clause.Expr{SQL: strings.Replace(joinStmt.SQL.String(), "WHERE ", "", 1), Vars: joinStmt.Vars})
if len(joinStmt.SQL.String()) > 0 {
tx.Clauses(clause.Expr{SQL: strings.Replace(joinStmt.SQL.String(), "WHERE ", "", 1), Vars: joinStmt.Vars})
}
}
tx = tx.Session(&Session{QueryFields: true}).Clauses(clause.From{Joins: []clause.Join{{

View File

@ -4,6 +4,8 @@ import (
"testing"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
. "gorm.io/gorm/utils/tests"
)
@ -284,3 +286,65 @@ func TestAssociationError(t *testing.T) {
err = DB.Model(&emptyUser).Association("Languages").Delete(&user1.Languages)
AssertEqual(t, err, gorm.ErrPrimaryKeyRequired)
}
type (
myType string
emptyQueryClause struct {
Field *schema.Field
}
)
func (myType) QueryClauses(f *schema.Field) []clause.Interface {
return []clause.Interface{emptyQueryClause{Field: f}}
}
func (sd emptyQueryClause) Name() string {
return "empty"
}
func (sd emptyQueryClause) Build(clause.Builder) {
}
func (sd emptyQueryClause) MergeClause(*clause.Clause) {
}
func (sd emptyQueryClause) ModifyStatement(stmt *gorm.Statement) {
// do nothing
}
func TestAssociationEmptyQueryClause(t *testing.T) {
type Organization struct {
gorm.Model
Name string
}
type Region struct {
gorm.Model
Name string
Organizations []Organization `gorm:"many2many:region_orgs;"`
}
type RegionOrg struct {
RegionId uint
OrganizationId uint
Empty myType
}
if err := DB.SetupJoinTable(&Region{}, "Organizations", &RegionOrg{}); err != nil {
t.Fatalf("Failed to set up join table, got error: %s", err)
}
if err := DB.Migrator().DropTable(&Organization{}, &Region{}); err != nil {
t.Fatalf("Failed to migrate, got error: %s", err)
}
if err := DB.AutoMigrate(&Organization{}, &Region{}); err != nil {
t.Fatalf("Failed to migrate, got error: %v", err)
}
region := &Region{Name: "Region1"}
if err := DB.Create(region).Error; err != nil {
t.Fatalf("fail to create region %v", err)
}
var orgs []Organization
if err := DB.Model(&Region{}).Association("Organizations").Find(&orgs); err != nil {
t.Fatalf("fail to find region organizations %v", err)
} else {
AssertEqual(t, len(orgs), 0)
}
}