Error when using Ecto to check presence of record: (ArgumentError) comparison with nil is forbidden as it is unsafe

Hello !,

I am unable to fix below error I face in Ecto.

Code:

39   def insert_or_get_record(attrs) do
 40     chunk_no = Map.get(attrs, :chunk_no)
 41     topic_id = Map.get(attrs, :topic_id)
 42 
 43 
 44     query =
 45       from c in __MODULE__,
 46       where: c.chunk_no == ^chunk_no and c.topic_id == ^topic_id,
 47       limit: 1
 48 
 49     record = Repo.one(query)
 50     if record do
 51       {:ok, record}
 52     else
 53       cs = changeset(%__MODULE__{}, attrs)
 54       Repo.insert(cs)
 55     end
 56 
 57   end

This is the error I get

** (ArgumentError) comparison with nil is forbidden as it is unsafe. If you want to check if a value is nil, use is_nil/1 instead
    (ecto 3.11.2) lib/ecto/query/builder.ex:1069: Ecto.Query.Builder.not_nil!/1
    (thiruvinai 0.1.0) lib/thiruvinai/entities/chunk.ex:45: Thiruvinai.Chunk.insert_or_get_record/1
    (thiruvinai 0.1.0) lib/thiruvinai/utils/load_util.ex:74: Thiruvinai.LoadUtil.load_questions/1
    (thiruvinai 0.1.0) lib/thiruvinai/utils/load_util.ex:39: Thiruvinai.LoadUtil.process_json_file/2
    (thiruvinai 0.1.0) lib/thiruvinai/utils/load_util.ex:26: Thiruvinai.LoadUtil.process_json_file/1
    (elixir 1.15.5) lib/enum.ex:1693: Enum."-map/2-lists^map/1-1-"/2

I find this baffling since I do not perform any nil check.

Kindly help !

Thank you !

Sreeram

Likely either chunk_no or topic_id are nil when the code is ran.

3 Likes

Thank you - that was the issue indeed !