How do I check if a table is devoid of entries using Repo.one ?

How do I check if a database table is devoid of entries? I could do this with Repo.all but I am already going down the rabbit hole and I am curious how do do it with Repo.one.

pseudo code

    if(App.Testbeds.Testbed) do 

      Repo.one(from x in App.Testbeds.Testbed, order_by: [desc: x.id], limit: 1)

    else

      nil 

    end

Well, the most straightforward approach is to use Repo.exists?/2.

If it must be with Repo.one/2, then wrapping what you have with is_nil would work (no need to specify an order in the query)

1 Like

You should definitely use exists. It will enforce a limit of 1 which is all you need to check existence. Repo.one will fetch all entries and raise if more than one exists. So it is more expensive than you need.