Skip to content

Commit 8dde09e

Browse files
author
kinggo
authored
fix: generate sql incorrect when use soft_delete and only one OR (#4969)
* fix: generate sql incorrect when use soft_delete and only one OR
1 parent 2c3fc2d commit 8dde09e

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

clause/where.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,14 @@ func (where Where) MergeClause(clause *Clause) {
9292
func And(exprs ...Expression) Expression {
9393
if len(exprs) == 0 {
9494
return nil
95-
} else if len(exprs) == 1 {
96-
return exprs[0]
9795
}
96+
97+
if len(exprs) == 1 {
98+
if _, ok := exprs[0].(OrConditions); !ok {
99+
return exprs[0]
100+
}
101+
}
102+
98103
return AndConditions{Exprs: exprs}
99104
}
100105

soft_delete.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func (sd SoftDeleteQueryClause) MergeClause(*clause.Clause) {
6565
func (sd SoftDeleteQueryClause) ModifyStatement(stmt *Statement) {
6666
if _, ok := stmt.Clauses["soft_delete_enabled"]; !ok && !stmt.Statement.Unscoped {
6767
if c, ok := stmt.Clauses["WHERE"]; ok {
68-
if where, ok := c.Expression.(clause.Where); ok && len(where.Exprs) > 1 {
68+
if where, ok := c.Expression.(clause.Where); ok && len(where.Exprs) >= 1 {
6969
for _, expr := range where.Exprs {
7070
if orCond, ok := expr.(clause.OrConditions); ok && len(orCond.Exprs) == 1 {
7171
where.Exprs = []clause.Expression{clause.And(where.Exprs...)}

tests/soft_delete_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,13 @@ func TestDeletedAtUnMarshal(t *testing.T) {
8383
t.Errorf("Failed, result.DeletedAt: %v is not same as expected.DeletedAt: %v", result.DeletedAt, expected.DeletedAt)
8484
}
8585
}
86+
87+
func TestDeletedAtOneOr(t *testing.T) {
88+
actualSQL := DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
89+
return tx.Or("id = ?", 1).Find(&User{})
90+
})
91+
92+
if !regexp.MustCompile(` WHERE id = 1 AND .users.\..deleted_at. IS NULL`).MatchString(actualSQL) {
93+
t.Fatalf("invalid sql generated, got %v", actualSQL)
94+
}
95+
}

0 commit comments

Comments
 (0)