Skip to content

Commit

Permalink
Support Scopes in group conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Apr 20, 2022
1 parent b49ae84 commit 88c26b6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions statement.go
Expand Up @@ -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 {
Expand Down
15 changes: 15 additions & 0 deletions tests/sql_builder_test.go
Expand Up @@ -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) {
Expand Down

0 comments on commit 88c26b6

Please sign in to comment.