Skip to content

Commit ae45a3f

Browse files
Implement $exists
1 parent bbadf91 commit ae45a3f

File tree

4 files changed

+47
-0
lines changed

4 files changed

+47
-0
lines changed

filter/converter.go

+18
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,24 @@ func (c *Converter) convertFilter(filter map[string]any, paramIndex int) (string
150150
v[operator] = c.arrayDriver(v[operator])
151151
}
152152
values = append(values, v[operator])
153+
case "$exists":
154+
// $exists only works on jsonb columns, so we need to check if the key is in the JSONB data first.
155+
isNestedColumn := c.nestedColumn != ""
156+
for _, exemption := range c.nestedExemptions {
157+
if exemption == key {
158+
isNestedColumn = false
159+
break
160+
}
161+
}
162+
if !isNestedColumn {
163+
// There is no way in Postgres to check if a column exists on a table.
164+
return "", nil, fmt.Errorf("$exists operator not supported on non-nested jsonb columns")
165+
}
166+
neg := ""
167+
if v[operator] == false {
168+
neg = "NOT "
169+
}
170+
inner = append(inner, fmt.Sprintf("(%sjsonb_path_match(%s, 'exists($.%s)'))", neg, c.nestedColumn, key))
153171
default:
154172
value := v[operator]
155173
op, ok := BasicOperatorMap[operator]

filter/converter_test.go

+16
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+
"$exists on normal column",
213+
nil,
214+
`{"name": {"$exists": false}}`,
215+
``,
216+
nil,
217+
fmt.Errorf("$exists operator not supported on non-nested jsonb columns"),
218+
},
219+
{
220+
"$exists jsonb column",
221+
filter.WithNestedJSONB("meta"),
222+
`{"name": {"$exists": false}}`,
223+
`(NOT jsonb_path_match(meta, 'exists($.name)'))`,
224+
nil,
225+
nil,
226+
},
211227
}
212228

213229
for _, tt := range tests {

fuzz/fuzz_test.go

+1
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": {"$exists": false}}`,
3637
}
3738
for _, tc := range tcs {
3839
f.Add(tc)

integration/postgres_test.go

+12
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+
`jsonb exists`,
302+
`{"pet": {"$exists": false}}`,
303+
[]int{9},
304+
nil,
305+
},
306+
{
307+
`jsonb exists`,
308+
`{"pet": {"$exists": true}}`,
309+
[]int{1, 2, 3, 4, 5, 6, 7, 8, 10},
310+
nil,
311+
},
300312
}
301313

302314
for _, tt := range tests {

0 commit comments

Comments
 (0)