Repo.get_by returns nil

I need to update a record in the DB, however, I get nil although I am sure that record is there:

#this would return nil, although I am sure that the record is there
Repo.get_by(MyApp.Schools.Process, process_name: process_name)

then, I though I can retry, until I can read, as:

defp set_process_done process_name, total_entries, status, attempt_number do
alias MyApp.Schools.Repo, as: Repo

process = Repo.get_by(MyApp.Schools.Process, process_name: process_name)
if process == nil do
  Logger.info "TRY TO SET PROCESS#{process_name} , attempt_number #{attempt_number}"
  set_process_done(process_name, total_entries, status, attempt_number+ 1)
else
  process = Ecto.Changeset.change process, status: "done"
  process = Ecto.Changeset.change process, operation_details: %{total_entries: total_entries, processed_entries: status[:processed_entries]}

  case Repo.update process do
    {:ok, struct}       -> Logger.info "CSV process #{process_name} marked as done."
    {:error, changeset} -> Logger.info "CSV failed to set process #{process_name} as done."
  end
end
end

I reached attempt_number 62, and still getting nil, so, what could be the issue? (although sometimes, I can read the record in less attempts!)

I am sure that I am connecting to the right DB, and I already inserted records, how can I debug that? to know what is exactly the issue?

You can print the process_name variable. You can also run Repo.all(MyApp.Schools.Process) to check if the record is there when fetching everything.

Thanks, but how would I iterate over records when using Repo.all(MyApp.Schools.Process) ?

Are you sure that your MyApp.Schools.Process has schema long_backend_process? Usually schemas have plural names and ones that reflect name of the module.

Checkout the Enum module. In this case I would use Enum.each/2 if you just want to print things:

Enum.each(Repo.all(MyApp.Schools.Process), fn process ->
  IO.inspect(process.process_name)
end)
1 Like

Thanks, I will check now.
@PatNowak here is my model:

 defmodule MyApp.Schools.Process do
   use MyApp.Web, :model

   schema "long_backend_process" do
     field :process_name, :string
     field :status, :string
     field :operation_details, :map
   end

 end

It looks ok. As @ericmj proposed, please try to get all structs from repo.
Maybe you have your entry in other MIX_ENV’s DB.

Oh, yes, it was not set properly in my dev.exs, sorry, my bad :relaxed: