Skip to content

Commit 7a67f48

Browse files
Support comparing to null
1 parent bbadf91 commit 7a67f48

File tree

4 files changed

+44
-0
lines changed

4 files changed

+44
-0
lines changed

filter/converter.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,21 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
166166
innerResult = "(" + innerResult + ")"
167167
}
168168
conditions = append(conditions, innerResult)
169+
case nil:
170+
// Comparing a column to NULL needs a different implementation depending on if the column is in JSONB or not.
171+
// JSONB columns are NULL even if they don't exist, so we need to check if the column exists first.
172+
isNestedColumn := c.nestedColumn != ""
173+
for _, exemption := range c.nestedExemptions {
174+
if exemption == key {
175+
isNestedColumn = false
176+
break
177+
}
178+
}
179+
if isNestedColumn {
180+
conditions = append(conditions, fmt.Sprintf("(jsonb_path_match(%s, 'exists($.%s)') AND %s IS NULL)", c.nestedColumn, key, c.columnName(key)))
181+
} else {
182+
conditions = append(conditions, fmt.Sprintf("(%s IS NULL)", c.columnName(key)))
183+
}
169184
default:
170185
conditions = append(conditions, fmt.Sprintf("(%s = $%d)", c.columnName(key), paramIndex))
171186
paramIndex++

filter/converter_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,22 @@ func TestConverter_Convert(t *testing.T) {
208208
nil,
209209
fmt.Errorf("empty objects not allowed"),
210210
},
211+
{
212+
"null nornal column",
213+
nil,
214+
`{"name": null}`,
215+
`("name" IS NULL)`,
216+
nil,
217+
nil,
218+
},
219+
{
220+
"null jsonb column",
221+
filter.WithNestedJSONB("meta"),
222+
`{"name": null}`,
223+
`(jsonb_path_match(meta, 'exists($.name)') AND "meta"->>'name' IS NULL)`,
224+
nil,
225+
nil,
226+
},
211227
}
212228

213229
for _, tt := range tests {

fuzz/fuzz_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ func FuzzConverter(f *testing.F) {
3333
`{"name": {}}`,
3434
`{"$or": []}`,
3535
`{"status": {"$in": []}}`,
36+
`{"name": null}`,
3637
}
3738
for _, tc := range tcs {
3839
f.Add(tc)

integration/postgres_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,18 @@ func TestIntegration_BasicOperators(t *testing.T) {
297297
[]int{},
298298
nil,
299299
},
300+
{
301+
`column equal to null`,
302+
`{"mount": null}`,
303+
[]int{3, 4},
304+
nil,
305+
},
306+
{
307+
`jsonb equal to null`,
308+
`{"pet": null}`,
309+
[]int{10},
310+
nil,
311+
},
300312
}
301313

302314
for _, tt := range tests {

0 commit comments

Comments
 (0)