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: generate sql incorrect when use soft_delete and only one OR #4969

Merged
merged 3 commits into from Dec 30, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 7 additions & 2 deletions clause/where.go
Expand Up @@ -92,9 +92,14 @@ func (where Where) MergeClause(clause *Clause) {
func And(exprs ...Expression) Expression {
if len(exprs) == 0 {
return nil
} else if len(exprs) == 1 {
return exprs[0]
}

if len(exprs) == 1 {
if _, ok := exprs[0].(OrConditions); !ok {
return exprs[0]
}
}

return AndConditions{Exprs: exprs}
}

Expand Down
2 changes: 1 addition & 1 deletion soft_delete.go
Expand Up @@ -65,7 +65,7 @@ func (sd SoftDeleteQueryClause) MergeClause(*clause.Clause) {
func (sd SoftDeleteQueryClause) ModifyStatement(stmt *Statement) {
if _, ok := stmt.Clauses["soft_delete_enabled"]; !ok && !stmt.Statement.Unscoped {
if c, ok := stmt.Clauses["WHERE"]; ok {
if where, ok := c.Expression.(clause.Where); ok && len(where.Exprs) > 1 {
if where, ok := c.Expression.(clause.Where); ok && len(where.Exprs) >= 1 {
for _, expr := range where.Exprs {
if orCond, ok := expr.(clause.OrConditions); ok && len(orCond.Exprs) == 1 {
where.Exprs = []clause.Expression{clause.And(where.Exprs...)}
Expand Down
10 changes: 10 additions & 0 deletions tests/soft_delete_test.go
Expand Up @@ -83,3 +83,13 @@ func TestDeletedAtUnMarshal(t *testing.T) {
t.Errorf("Failed, result.DeletedAt: %v is not same as expected.DeletedAt: %v", result.DeletedAt, expected.DeletedAt)
}
}

func TestDeletedAtOneOr(t *testing.T) {
actualSQL := DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Or("id = ?", 1).Find(&User{})
})

if !regexp.MustCompile(` WHERE id = 1 AND .users.\..deleted_at. IS NULL`).MatchString(actualSQL) {
t.Fatalf("invalid sql generated, got %v", actualSQL)
}
}