Have Ecto wait for DB to spin up?

I haven’t really solved it yet. I’ve got an acceptable (for our purposes) workaround, but it’s not great. In my application’s Ecto.Repo implementation, I added two functions:

  def wait_for_connection do
    Logger.info("Waiting for active database connection...")
    canary() |> WaitForIt.wait(timeout: 60_000, frequency: 1_000)
  end

  defp canary do
    case __MODULE__.query("SELECT 1") do
      {:ok, %{rows: [[1]]}} -> :ok
      _ -> :error
    end
  rescue
    _ in DBConnection.ConnectionError -> :error
  end

Then I updated my Application module to start the repo alone under a DynamicSupervisor and call its wait_for_connection() before starting any of the application’s other child processes. I still get a lot of junk in the log while it waits for the DB to spin up, but it works reasonably well.

Note: This solution requires the wait_for_it hex package.