diff --git a/pgstmt/cond.go b/pgstmt/cond.go index 85d6435..569d9b4 100644 --- a/pgstmt/cond.go +++ b/pgstmt/cond.go @@ -28,6 +28,7 @@ type Cond interface { IsNull(field string) IsNotNull(field string) Raw(sql string) + Not(f func(b Cond)) And(f func(b Cond)) Or(f func(b Cond)) Mode() CondMode @@ -188,6 +189,17 @@ func (st *cond) Raw(sql string) { st.ops.push(sql) } +func (st *cond) Not(b func(b Cond)) { + var x cond + x.ops.sep = " and " + x.nested = true + b(&x) + + if !x.empty() { + st.ops.push(withParen(" ", "not", &x)) + } +} + func (st *cond) And(f func(b Cond)) { var x cond x.ops.sep = " and " diff --git a/pgstmt/select_test.go b/pgstmt/select_test.go index 7d22f0c..ef3707e 100644 --- a/pgstmt/select_test.go +++ b/pgstmt/select_test.go @@ -483,6 +483,25 @@ func TestSelect(t *testing.T) { `, nil, }, + { + "select where not", + pgstmt.Select(func(b pgstmt.SelectStatement) { + b.Columns("*") + b.From("table1") + b.Where(func(b pgstmt.Cond) { + b.Eq("id", 1) + b.Not(func(b pgstmt.Cond) { + b.Op("tags", "@>", pq.Array([]string{"a", "b"})) + }) + }) + }), + ` + select * + from table1 + where (id = $1 and (not (tags @> $2))) + `, + []any{1, pq.Array([]string{"a", "b"})}, + }, } for _, tC := range cases {