How to handle is_nil/1 with this ecto query

hi

I have a simple query like this


 def user_type_name(%{user_type_id: user_type_id}) do
    from(sc in UserType, where: sc.id == ^user_type_id, select: sc.name) |> Repo.one()
  end

and I’m getting this error

→ comparison with nil is forbidden as it is unsafe. If you want to check if a value is nil, use is_nil/1 instead

how do I solve this?

1 Like
def user_type_name(%{user_type_id: nil}) do
  from(sc in UserType, where: is_nil(sc.id), select: sc.name) |> Repo.one()
end

def user_type_name(%{user_type_id: user_type_id}) do
  from(sc in UserType, where: sc.id == ^user_type_id, select: sc.name) |> Repo.one()
end
3 Likes

It solves the problem but I want to know about that error also. I have used this query before but why particularly on this?

The error happens because when you run it the value of user_type_id is nil. Whenever you were using it before it seems like it was never nil.

2 Likes

And expanding to what @iangl said, it is because in SQL using = comparator on NULL will return NULL which is falsey value. This mean that SELECT … WHERE x = NULL will return nothing, as the WHERE is always false.

5 Likes