Skip to content

Commit

Permalink
fix: not clause with or condition
Browse files Browse the repository at this point in the history
  • Loading branch information
a631807682 committed Apr 22, 2024
1 parent d0b4ceb commit 63e7c2b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion clause/where.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,12 @@ func (not NotConditions) Build(builder Builder) {

for idx, c := range not.Exprs {
if idx > 0 {
builder.WriteString(AndWithSpace)
switch c.(type) {
case OrConditions:
builder.WriteString(OrWithSpace)
default:
builder.WriteString(AndWithSpace)
}
}

e, wrapInParentheses := c.(Expr)
Expand Down
16 changes: 16 additions & 0 deletions clause/where_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,22 @@ func TestWhere(t *testing.T) {
"SELECT * FROM `users` WHERE NOT (`score` <= ? AND `age` <= ?)",
[]interface{}{100, 60},
},
{
[]clause.Interface{clause.Select{}, clause.From{}, clause.Where{
Exprs: []clause.Expression{
clause.Not(clause.AndConditions{
Exprs: []clause.Expression{
clause.Eq{Column: clause.PrimaryColumn, Value: "1"},
clause.Gt{Column: "age", Value: 18},
}}, clause.OrConditions{
Exprs: []clause.Expression{
clause.Lt{Column: "score", Value: 100},
},
}),
}}},
"SELECT * FROM `users` WHERE NOT ((`users`.`id` = ? AND `age` > ?) OR `score` < ?)",
[]interface{}{"1", 18, 100},
},
}

for idx, result := range results {
Expand Down
5 changes: 5 additions & 0 deletions tests/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,11 @@ func TestNot(t *testing.T) {
if !regexp.MustCompile("SELECT \\* FROM .*users.* WHERE NOT \\(manager IS NULL AND age >= .+\\) AND .users.\\..deleted_at. IS NULL").MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
}

result = dryDB.Not(DB.Where("manager IS NULL").Or("age >= ?", 20)).Find(&User{})
if !regexp.MustCompile(`SELECT \* FROM .*users.* WHERE NOT \(manager IS NULL OR age >= .+\) AND .users.\..deleted_at. IS NULL`).MatchString(result.Statement.SQL.String()) {
t.Fatalf("Build NOT condition, but got %v", result.Statement.SQL.String())
}
}

func TestNotWithAllFields(t *testing.T) {
Expand Down

0 comments on commit 63e7c2b

Please sign in to comment.