Skip to content

Commit

Permalink
Return ArgumentError when missing :database key in config (#671)
Browse files Browse the repository at this point in the history
* Return ArgumentError when missing `:database` key in config

Sample message printed by DbConnection:

[error] Postgrex.Protocol (#PID<0.387.0>) failed to connect: ** (ArgumentError)
missing the :database key in options for repo TestEctoIssue.Repo

* Better formatting

* fix
  • Loading branch information
v0idpwn authored Apr 16, 2024
1 parent 715787d commit 3af848b
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/postgrex/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,12 @@ defmodule Postgrex.Protocol do
%{opts: opts, types_mod: types_mod} = status,
previous_errors
) do
types_key = if types_mod, do: {host, port, Keyword.fetch!(opts, :database)}
opts = Config.Reader.merge(opts, extra_opts)

status = %{status | types_key: types_key, opts: opts}

case connect_and_handshake(host, port, sock_opts, timeout, s, status) do
{:ok, _} = ret ->
ret

with {:ok, database} <- fetch_database(opts),
opts = Config.Reader.merge(opts, extra_opts),
status = %{status | types_key: if(types_mod, do: {host, port, database}), opts: opts},
{:ok, ret} <- connect_and_handshake(host, port, sock_opts, timeout, s, status) do
{:ok, ret}
else
{:error, err} ->
connect_endpoints(
remaining_endpoints,
Expand All @@ -205,6 +202,17 @@ defmodule Postgrex.Protocol do
{:error, %Postgrex.Error{message: message}}
end

defp fetch_database(opts) do
case Keyword.fetch(opts, :database) do
{:ok, value} ->
{:ok, value}

:error ->
message = "missing the :database key in options for #{inspect(opts[:repo])}"
{:error, %ArgumentError{message: message}}
end
end

defp connect_and_handshake(host, port, sock_opts, timeout, s, status) do
case connect(host, port, sock_opts, timeout, s) do
{:ok, s} ->
Expand Down

0 comments on commit 3af848b

Please sign in to comment.