Repository navigation
fix(config): accept multi-host PostgreSQL URLs - #2387
Conversation
Merging this PR will not alter performance1 warning
Comparing |
|
Thanks @waketzheng, done: moved to Added, the port check now starts at 1 with the new message, and a test covers port 0. |
|
The three review points are addressed in 9cf39dd (port range starts at 1 with the new message, port 0 test, changelog under Added). Could you re-review and approve the CI run when you have time? Thanks. |
A URL such as postgres://u:p@host1,host2:5432/db is libpq's failover syntax. urlparse reads "host1,host2" back as one hostname, so asyncpg tried to resolve it as a single DNS name and failed. Split the host part of postgres, postgresql, asyncpg and psycopg URLs on commas, each entry with its own optional port (a bare host takes the port of the query string or 5432), and pass lists to the clients. asyncpg takes the lists as they are; psycopg gets the comma joined strings libpq expects. psycopg also reads target_session_attrs from the URL query, as asyncpg already did through its connect arguments. Single-host URLs are unchanged. Fixes tortoise#1924
9cf39dd to
d560038
Compare
- params: replace manual loop with dict(...) - expand_db_url: use try/except KeyError instead of pre-check + index - re.match: replace type: ignore with explicit None guard - DB_LOOKUP: mark Final, restore postgres/postgresql aliases in one line
|
The changes you asked for are in (port range from 1, test for port 0, changelog under Added). Could you re-run CI and take another look when you have time? Thanks. |
|
Good job! Verified multi-host failover on fix/1924-multi-host-postgres-dsn Test matrix:
asyncpg traverses the full host list in order, preferring the first reachable Manually verified using the following steps:
services:
postgres-primary:
image: postgres:latest
container_name: tortoise-pg-primary
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: appdb
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
interval: 3s
timeout: 3s
retries: 10
networks:
- dbnet
postgres-replica-1:
image: postgres:latest
container_name: tortoise-pg-replica-1
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: appdb
ports:
- "5433:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
interval: 3s
timeout: 3s
retries: 10
networks:
- dbnet
postgres-replica-2:
image: postgres:latest
container_name: tortoise-pg-replica-2
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: appdb
ports:
- "5434:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
interval: 3s
timeout: 3s
retries: 10
networks:
- dbnet
verifier:
build: .
container_name: tortoise-multi-host-verifier
volumes:
- .:/app
- /app/.venv
depends_on:
postgres-primary:
condition: service_healthy
postgres-replica-1:
condition: service_healthy
postgres-replica-2:
condition: service_healthy
networks:
- dbnet
networks:
dbnet:
driver: bridge
import asyncio
import logging
import os
import platform
import tortoise
from tortoise import Model, Tortoise, connections, fields
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("verify-multi-host")
class DummyModel(Model):
id = fields.IntField(pk=True)
created_at = fields.DatetimeField(auto_now_add=True, null=True)
# Multi-host DSN: a comma-separated list of host:port pairs.
DEFAULT_DSN = (
"postgres://postgres:postgres@"
"postgres-primary," # port 5432 can be omitted
"postgres-replica-1:5433,"
"postgres-replica-2:5434"
"/appdb?target_session_attrs=read-write"
)
if platform.system() != "Linux":
for host in ("postgres-primary", "postgres-replica-1", "postgres-replica-2"):
DEFAULT_DSN = DEFAULT_DSN.replace(host, "localhost")
else:
for port in ("5433", "5434"):
DEFAULT_DSN = DEFAULT_DSN.replace(port, "5432")
MULTI_HOST_DSN = os.getenv("MULTI_HOST_DSN", DEFAULT_DSN)
async def main() -> None:
logger.info("Tortoise-ORM version: %s", getattr(tortoise, "__version__", "unknown"))
logger.info("Using multi-host DSN: %s", MULTI_HOST_DSN)
config = {
"connections": {"default": MULTI_HOST_DSN},
"apps": {
"models": {
"models": ["__main__"],
"default_connection": "default",
}
},
}
await Tortoise.init(config=config)
try:
conn = connections.get("default")
logger.info("Connection pool created. Running verification queries...")
affected, rows = await conn.execute_query("SELECT 1 AS ping;")
logger.info("Ping query succeeded: affected=%s rows=%s", affected, rows)
affected, rows = await conn.execute_query(
"SELECT "
"inet_server_addr()::text AS server_addr, "
"inet_server_port() AS server_port, "
"current_database() AS db, "
"current_user AS usr, "
"pg_backend_pid() AS backend_pid;"
)
logger.info("Connected server info: %s", rows)
logger.info("MULTI-HOST VERIFICATION PASSED")
except Exception:
logger.exception("MULTI-HOST VERIFICATION FAILED")
raise
finally:
await Tortoise.close_connections()
logger.info("Connections closed.")
if __name__ == "__main__":
asyncio.run(main())
docker compose up -d --build --wait
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.pyResult:
docker compose stop postgres-primary
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.pyResult:
docker compose stop postgres-replica-1
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.pyResult:
|
Description
Accept libpq style multi-host PostgreSQL URLs,
postgres://user:pass@host1:5432,host2:5433/db?target_session_attrs=read-write, for thepostgres,postgresql,asyncpgandpsycopgschemes. The host part is split on commas, each entry takes its own optional port, and a bare host takes the port from the query string or5432. A single-host URL gives exactly the same result as before. When a URL lists several hosts, a?host=value in its query string is ignored.The clients take the lists as they are for asyncpg, and psycopg joins them with commas for libpq. psycopg also reads
target_session_attrsfrom the URL, which asyncpg already accepted through its connect arguments, so the example above works with both drivers.Motivation and Context
Fixes #1924.
urlparsereturnshost1,host2as one hostname, so asyncpg tried to resolve it as a single DNS name and failed withsocket.gaierror. psycopg already worked for a shared port (libpq splits the string itself) but not for per-host ports. The closed attempt in #2267 split hosts for asyncpg only; this also covers per-host ports, IPv6 literals, psycopg and thetarget_session_attrsparameter from the issue's own URL.How Has This Been Tested?
tests/backends/test_db_url.py(shared port, per-host ports, query parameters, IPv6, the query port as default, invalid port and empty host, other schemes unchanged) andtests/backends/test_connection_params.py(the host and port lists reach asyncpg, the joined strings reach psycopg's conninfo, single-host types staystrandint). Twelve of them fail ondevelopand all pass with the change.tests/backendson Linux against PostgreSQL 17: 93 passed, 6 skipped, 1 xfailed.host:54399,host:54320), with and without?target_session_attrs=read-write: asyncpg and psycopg both connect to the second host on Linux. On Windows, psycopg's own connection pool fails the same way with a dead first host outside Tortoise, so that case was not used there.mypy tortoise/backendsis clean andruffreports nothing new on the touched files.Checklist: