Skip to content

Commit

Permalink
Add parens when using NOT around a junction
Browse files Browse the repository at this point in the history
  • Loading branch information
hlubek committed Jul 20, 2023
1 parent 33b7544 commit d72aa78
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
9 changes: 9 additions & 0 deletions builder/op.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,16 @@ func (u unaryExp) WriteSQL(sb *SQLBuilder) {
sb.WriteString(u.prefix)
sb.WriteRune(' ')
}

_, needsParens := u.exp.(junctionExp)
if needsParens {
sb.WriteRune('(')
}
u.exp.WriteSQL(sb)
if needsParens {
sb.WriteRune(')')
}

if u.suffix != "" {
sb.WriteRune(' ')
sb.WriteString(u.suffix)
Expand Down
4 changes: 4 additions & 0 deletions root.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ func Or(exps ...builder.Exp) builder.Exp {
return builder.Or(exps...)
}

func Not(exp builder.Exp) builder.Exp {
return builder.Not(exp)
}

func Case(exp ...builder.Exp) builder.CaseBuilder {
return builder.Case(exp...)
}
Expand Down
39 changes: 39 additions & 0 deletions select_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,45 @@ func TestSelectBuilder_Where(t *testing.T) {
q,
)
})

t.Run("where with negated junction", func(t *testing.T) {
q := qrb.Select(qrb.N("*")).
From(qrb.N("accounts")).
Where(qrb.Not(qrb.And(
qrb.N("is_active").Eq(qrb.Bool(true)),
qrb.N("username").Eq(qrb.Arg("admin")),
)))

testhelper.AssertSQLWriterEquals(
t,
`
SELECT *
FROM accounts
WHERE NOT (is_active = true AND username = $1)
`,
[]any{"admin"},
q,
)
})

t.Run("where with negated comparison", func(t *testing.T) {
q := qrb.Select(qrb.N("*")).
From(qrb.N("accounts")).
Where(qrb.Not(
qrb.N("is_active").Eq(qrb.Bool(true)),
))

testhelper.AssertSQLWriterEquals(
t,
`
SELECT *
FROM accounts
WHERE NOT is_active = true
`,
nil,
q,
)
})
}

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

0 comments on commit d72aa78

Please sign in to comment.