From 35ebfe68740ef8d1ff3fde2037fbba34d802e287 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 20 Jan 2021 18:24:05 +0800 Subject: [PATCH] Support group conditions with single OR condition --- statement.go | 5 +++++ tests/query_test.go | 12 +++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/statement.go b/statement.go index 3617d7ed..de1b300f 100644 --- a/statement.go +++ b/statement.go @@ -261,6 +261,11 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] case *DB: if cs, ok := v.Statement.Clauses["WHERE"]; ok { if where, ok := cs.Expression.(clause.Where); ok { + if len(where.Exprs) == 1 { + if orConds, ok := where.Exprs[0].(clause.OrConditions); ok { + where.Exprs[0] = clause.AndConditions{Exprs: orConds.Exprs} + } + } conds = append(conds, clause.And(where.Exprs...)) } else if cs.Expression != nil { conds = append(conds, cs.Expression) diff --git a/tests/query_test.go b/tests/query_test.go index 50522f71..c6c7acb0 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -475,7 +475,17 @@ func TestNotWithAllFields(t *testing.T) { func TestOr(t *testing.T) { dryDB := DB.Session(&gorm.Session{DryRun: true}) - result := dryDB.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&User{}) + result := dryDB.Where("role = ?", "admin").Where(DB.Or("role = ?", "super_admin")).Find(&User{}) + if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ AND .*role.* = .+").MatchString(result.Statement.SQL.String()) { + t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String()) + } + + result = dryDB.Where("role = ?", "admin").Where(DB.Or("role = ?", "super_admin").Or("role = ?", "admin")).Find(&User{}) + if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ AND (.*role.* = .+ OR .*role.* = .+)").MatchString(result.Statement.SQL.String()) { + t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String()) + } + + result = dryDB.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&User{}) if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE .*role.* = .+ OR .*role.* = .+").MatchString(result.Statement.SQL.String()) { t.Fatalf("Build OR condition, but got %v", result.Statement.SQL.String()) }