From 14f3cc300b40d27e1ed7790e59075ff9da10c881 Mon Sep 17 00:00:00 2001 From: itisrmk Date: Sat, 28 Nov 2026 08:05:13 +0000 Subject: [PATCH] Preserve multi-host DSN parsing on Python 3.16 --- asyncpg/connect_utils.py | 29 ++++++++++++++++++++++++++++- tests/test_connect.py | 12 ++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/asyncpg/connect_utils.py b/asyncpg/connect_utils.py index e215391b..557bdcd6 100644 --- a/asyncpg/connect_utils.py +++ b/asyncpg/connect_utils.py @@ -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, @@ -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: diff --git a/tests/test_connect.py b/tests/test_connect.py index 1c25d8d6..b5ed0e11 100644 --- a/tests/test_connect.py +++ b/tests/test_connect.py @@ -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'