From 88c26b62ee63863932e001be21e05a4ef43d03c2 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 20 Apr 2022 17:21:38 +0800 Subject: [PATCH] Support Scopes in group conditions --- statement.go | 4 ++++ tests/sql_builder_test.go | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/statement.go b/statement.go index 9fcee09c..d0c691d8 100644 --- a/statement.go +++ b/statement.go @@ -312,6 +312,10 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) [] case clause.Expression: conds = append(conds, v) case *DB: + for _, scope := range v.Statement.scopes { + v = scope(v) + } + if cs, ok := v.Statement.Clauses["WHERE"]; ok { if where, ok := cs.Expression.(clause.Where); ok { if len(where.Exprs) == 1 { diff --git a/tests/sql_builder_test.go b/tests/sql_builder_test.go index a7630271..a9b920dc 100644 --- a/tests/sql_builder_test.go +++ b/tests/sql_builder_test.go @@ -243,6 +243,21 @@ func TestGroupConditions(t *testing.T) { if !strings.HasSuffix(result, expects) { t.Errorf("expects: %v, got %v", expects, result) } + + stmt2 := dryRunDB.Where( + DB.Scopes(NameIn1And2), + ).Or( + DB.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"), + ).Find(&Pizza{}).Statement + + execStmt2 := dryRunDB.Exec(`WHERE name in ? OR (pizza = ? AND size = ?)`, []string{"ScopeUser1", "ScopeUser2"}, "hawaiian", "xlarge").Statement + + result2 := DB.Dialector.Explain(stmt2.SQL.String(), stmt2.Vars...) + expects2 := DB.Dialector.Explain(execStmt2.SQL.String(), execStmt2.Vars...) + + if !strings.HasSuffix(result2, expects2) { + t.Errorf("expects: %v, got %v", expects2, result2) + } } func TestCombineStringConditions(t *testing.T) {