Skip to content

Commit d909a88

Browse files
committed
Improve data queries so that they return FALSE instead of NULL when querying non-existing data fields
1 parent fca9d5c commit d909a88

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

Diff for: lib/keila/contacts/query.ex

+6-3
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,19 @@ defmodule Keila.Contacts.Query do
161161
defp build_data_condition(path, %{"$in" => value}) when is_list(value),
162162
do: dynamic([c], fragment("?#>?", c.data, ^path) in ^value)
163163

164-
defp build_data_condition(path, %{"$like" => value}),
165-
do: dynamic([c], ilike(fragment("?#>>?", c.data, ^path), ^value))
164+
defp build_data_condition(path, %{"$like" => value}) do
165+
ilike = dynamic([c], ilike(fragment("?#>>?", c.data, ^path), ^value))
166+
167+
dynamic([c], fragment("coalesce(?, FALSE)", ^ilike))
168+
end
166169

167170
defp build_data_condition(path, value) when is_binary(value) or is_number(value) do
168171
value_in_array = [value]
169172
string_value = to_string(value)
170173

171174
equals_string = dynamic([c], fragment("?#>>?", c.data, ^path) == ^string_value)
172175
array_contains = dynamic([c], fragment("?#>? @> ?", c.data, ^path, ^value_in_array))
173-
dynamic([c], ^equals_string or ^array_contains)
176+
dynamic([c], fragment("coalesce(?, FALSE)", ^equals_string or ^array_contains))
174177
end
175178

176179
defp build_data_condition(path, value) when is_map(value) or is_list(value) do

Diff for: test/keila/contacts/contacts_query_test.exs

+6
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ defmodule Keila.ContactsQueryTest do
163163
insert!(:contact, %{
164164
data: %{
165165
"string" => "bar",
166+
"stringOnly2" => "yes",
166167
"array" => [4, 5, 6],
167168
"object" => %{"d" => %{"e" => "f"}},
168169
"objects" => [%{"e" => "f"}]
@@ -197,6 +198,11 @@ defmodule Keila.ContactsQueryTest do
197198
# Like operator
198199
assert [c1] == filter_contacts(%{"data.string" => %{"$like" => "%o%"}})
199200
assert [c2] == filter_contacts(%{"data.string" => %{"$like" => "%A%"}})
201+
202+
# Not operator
203+
assert [c1, c2] == filter_contacts(%{"$not" => %{"data.string" => "no_match"}})
204+
assert [c1, c2] == filter_contacts(%{"$not" => %{"data.stringOnly2" => "no_match"}})
205+
assert [c1] == filter_contacts(%{"$not" => %{"data.stringOnly2" => "yes"}})
200206
end
201207

202208
@tag :contacts_query

0 commit comments

Comments
 (0)