The simplest thing you can do in this particular situation, is refactor the code a little to move out the expressions which you are doing in either branch of the code:
def search(search_term) do
wildcard_search = "%#{search_term}%"
query = case Decimal.parse(search_term) do
{amount_decimal, _} ->
# Input is decimal
from(ce in CashflowEntry,
where: ce.amount == ^amount_decimal or ilike(ce.note, ^wildcard_search)
)
_ ->
# Input is alphanumeric
from(ce in CashflowEntry, where: ilike(ce.note, ^wildcard_search))
end
Repo.all(query)
end
And at this point, you might as well move the case statement to a helper function:
def search(search_term) do
search_term
|> search_query()
|> Repo.all()
end
# You might consider making this function public to test it separately
defp search_query(search_term) do
wildcard_search = "%#{search_term}%"
query = case Decimal.parse(search_term) do
{amount_decimal, _} ->
# Input is decimal
from(ce in CashflowEntry,
where: ce.amount == ^amount_decimal or ilike(ce.note, ^wildcard_search)
)
_ ->
# Input is alphanumeric
from(ce in CashflowEntry, where: ilike(ce.note, ^wildcard_search))
end
end
There is to my knowledge no simple possibility to move the check of whether the input is a string or a number into the query to turn this code into a single query. (At least not without writing a raw SQL fragment, which is usually not recommended).






















