Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion asyncpg/connect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,33 @@ def _dot_postgresql_path(filename) -> typing.Optional[pathlib.Path]:
return (homedir / '.postgresql' / filename).resolve()


def _parse_dsn(dsn):
try:
return urllib.parse.urlparse(dsn)
except ValueError:
scheme, sep, rest = dsn.partition('://')
if not sep or scheme.lower() not in {'postgresql', 'postgres'}:
raise

netloc, *suffix = re.split(r'([/?#])', rest, maxsplit=1)
userinfo, at, hostlist = netloc.rpartition('@')
hosts = hostlist.split(',')
if len(hosts) < 2 or not all(hosts):
raise

# urllib validates the authority as a single host and port.
for host in hosts:
name, colon, port = host.rpartition(':')
if colon and ']' not in port:
decoded_port = urllib.parse.unquote(port)
if decoded_port.isascii() and decoded_port.isdecimal():
host = name + colon + decoded_port
urllib.parse.urlparse(f'{scheme}://{userinfo}{at}{host}')

parsed = urllib.parse.urlparse(f'{scheme}://{"".join(suffix)}')
return parsed._replace(netloc=netloc)


def _parse_connect_dsn_and_args(*, dsn, host, port, user,
password, passfile, database, ssl,
service, servicefile,
Expand All @@ -292,7 +319,7 @@ def _parse_connect_dsn_and_args(*, dsn, host, port, user,
sslnegotiation = None

if dsn:
parsed = urllib.parse.urlparse(dsn)
parsed = _parse_dsn(dsn)

query = None
if parsed.query:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,18 @@ class TestConnectParams(tb.TestCase):
})
},

{
'name': 'dsn_multi_host_mixed_ipv6_and_ipv4',
'dsn': 'postgresql://user@[::1]:1111,127.0.0.1/d%62'
'?application_name=test',
'result': ([('::1', 1111), ('127.0.0.1', 5432)], {
'database': 'db',
'user': 'user',
'server_settings': {'application_name': 'test'},
'target_session_attrs': 'any',
})
},

{
'name': 'target_session_attrs',
'dsn': 'postgresql://user@host1:1111,host2:2222/db'
Expand Down