My second example is for a case not supported by libpq. I _think_ that
this means that
URI.parse("postgresql://user:password@host1:123,:password@host2:456/somedb?target_session_attrs=any&application_name=myapp")
%URI{
authority: "user:password@host1:123,:password@host2:456",
fragment: nil,
host: "host2",
path: "/somedb",
port: 456,
query: "target_session_attrs=any&application_name=myapp",
scheme: "postgresql",
userinfo: "user:password@host1:123,:password"
}
would be legitimate, but I’m not sure. One alternative (not compatible
with libpq) would be to accept a url list instead of just a single url
string, such that an environment variable might contain
"postgresql://user:password@host1:123/somedb?target_session_attrs=any&application_name=myapp,postgresql://user:password@host2:456/somedb?target_session_attrs=any&application_name=myapp"
and then be turned into a list
["postgresql://user:password@host1:123/somedb?target_session_attrs=any&application_name=myapp",
"postgresql://user:password@host2:456/somedb?target_session_attrs=any&application_name=myapp"]
-a
Here’s the relevant section from the libpq documentation:
33.1.1.3. Specifying Multiple Hosts
It is possible to specify multiple hosts to connect to, so that they
are tried in the given order. In the Keyword/Value format, the host,
hostaddr, and port options accept comma-separated lists of values. The
same number of elements must be given in each option that is
specified, such that e.g., the first hostaddr corresponds to the first
host name, the second hostaddr corresponds to the second host name,
and so forth. As an exception, if only one port is specified, it
applies to all the hosts.
In the connection URI format, you can list multiple host:port pairs
separated by commas in the host component of the URI.
In either format, a single host name can translate to multiple network
addresses. A common example of this is a host that has both an IPv4
and an IPv6 address.
When multiple hosts are specified, or when a single host name is
translated to multiple addresses, all the hosts and addresses will be
tried in order, until one succeeds. If none of the hosts can be
reached, the connection fails. If a connection is established
successfully, but authentication fails, the remaining hosts in the
list are not tried.
If a password file is used, you can have different passwords for
different hosts. All the other connection options are the same for
every host in the list; it is not possible to e.g., specify different
usernames for different hosts.