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
This commit is contained in:
kinggo 2021-12-30 11:47:14 +08:00 committed by GitHub
parent 2c3fc2db28
commit 8dde09e0be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 3 deletions

View File

@ -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 {
}
if len(exprs) == 1 {
if _, ok := exprs[0].(OrConditions); !ok {
return exprs[0]
}
}
return AndConditions{Exprs: exprs}
}

View File

@ -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...)}

View File

@ -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)
}
}