Skip to content

Commit e99cd30

Browse files
Support comparing to null
1 parent a827073 commit e99cd30

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
@@ -216,6 +216,22 @@ func TestConverter_Convert(t *testing.T) {
216216
nil,
217217
fmt.Errorf("invalid column name: \"bla = 1 --"),
218218
},
219+
{
220+
"null nornal column",
221+
nil,
222+
`{"name": null}`,
223+
`("name" IS NULL)`,
224+
nil,
225+
nil,
226+
},
227+
{
228+
"null jsonb column",
229+
filter.WithNestedJSONB("meta"),
230+
`{"name": null}`,
231+
`(jsonb_path_match(meta, 'exists($.name)') AND "meta"->>'name' IS NULL)`,
232+
nil,
233+
nil,
234+
},
219235
}
220236

221237
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
@@ -303,6 +303,18 @@ func TestIntegration_BasicOperators(t *testing.T) {
303303
[]int{7, 8, 9, 10},
304304
nil,
305305
},
306+
{
307+
`column equal to null`,
308+
`{"mount": null}`,
309+
[]int{3, 4},
310+
nil,
311+
},
312+
{
313+
`jsonb equal to null`,
314+
`{"pet": null}`,
315+
[]int{10},
316+
nil,
317+
},
306318
}
307319

308320
for _, tt := range tests {

0 commit comments

Comments
 (0)