fix: generate sql incorrect when use soft_delete and only one OR

This commit is contained in:
longlihale 2021-12-29 22:24:48 +08:00
parent 2c3fc2db28
commit d69be45dd2
3 changed files with 15 additions and 2 deletions

View File

@ -92,9 +92,12 @@ func (where Where) MergeClause(clause *Clause) {
func And(exprs ...Expression) Expression {
if len(exprs) == 0 {
return nil
} else if len(exprs) == 1 {
}
if _, ok := exprs[0].(OrConditions); !ok && len(exprs) == 1 {
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)
}
}