From c88cb82742480cd9bfd09682d861c024678b2df4 Mon Sep 17 00:00:00 2001 From: b84330808 Date: Tue, 27 Oct 2026 23:55:14 +0900 Subject: [PATCH 1/2] Fix service connections on Windows without PGSYSCONFDIR On Windows, parse_service_info() built the service file path as os.getenv("PGSYSCONFDIR") + "\pg_service.conf", so `pgcli service=foo` or PGSERVICE crashed with a TypeError whenever PGSYSCONFDIR was unset, which is the default. Fall back to libpq's per-user service file on Windows, %APPDATA%\postgresql\.pg_service.conf, when PGSYSCONFDIR is not set. Co-Authored-By: Claude Opus 5.5 --- changelog.rst | 3 +++ pgcli/main.py | 5 ++++- tests/test_main.py | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/changelog.rst b/changelog.rst index fc362092b..439bb0193 100644 --- a/changelog.rst +++ b/changelog.rst @@ -16,6 +16,9 @@ Bug fixes: created by ``uv venv``. * Read ``alias_map_file`` as UTF-8 (with or without a BOM) instead of the locale encoding, which made non-ASCII aliases fail on Windows. +* Fix a crash on Windows when connecting with ``service=...`` or ``PGSERVICE`` + while neither ``PGSERVICEFILE`` nor ``PGSYSCONFDIR`` is set. The service file + is now read from ``%APPDATA%\postgresql\.pg_service.conf``, as libpq does. Internal: --------- diff --git a/pgcli/main.py b/pgcli/main.py index 972b3c670..a94019410 100644 --- a/pgcli/main.py +++ b/pgcli/main.py @@ -2278,8 +2278,11 @@ def parse_service_info(service): service_file = os.getenv("PGSERVICEFILE") if not service_file: # try ~/.pg_service.conf (if that exists) - if platform.system() == "Windows": + if platform.system() == "Windows" and os.getenv("PGSYSCONFDIR"): service_file = os.getenv("PGSYSCONFDIR") + "\\pg_service.conf" + elif platform.system() == "Windows": + # libpq's per-user service file on Windows + service_file = os.path.join(os.getenv("APPDATA", ""), "postgresql", ".pg_service.conf") elif os.getenv("PGSYSCONFDIR"): service_file = os.path.join(os.getenv("PGSYSCONFDIR"), ".pg_service.conf") else: diff --git a/tests/test_main.py b/tests/test_main.py index 57ba8afe8..4075e6cfe 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -754,6 +754,22 @@ def test_pg_service_file(tmpdir): del os.environ["PGSERVICEFILE"] +def test_pg_service_file_windows_default_location(tmp_path, monkeypatch): + # Without PGSERVICEFILE or PGSYSCONFDIR, libpq reads + # %APPDATA%\postgresql\.pg_service.conf on Windows. + service_dir = tmp_path / "postgresql" + service_dir.mkdir() + (service_dir / ".pg_service.conf").write_text("[myservice]\nhost=a_host\ndbname=a_dbname\n") + cli = PGCli(pgclirc_file=str(tmp_path / "rcfile")) + monkeypatch.delenv("PGSERVICEFILE", raising=False) + monkeypatch.delenv("PGSYSCONFDIR", raising=False) + monkeypatch.setenv("APPDATA", str(tmp_path)) + monkeypatch.setattr("pgcli.main.platform.system", lambda: "Windows") + with mock.patch.object(cli, "connect") as mock_connect: + cli.connect_service("myservice", "a_user") + mock_connect.assert_called_with(database="a_dbname", host="a_host", user="a_user", port=None, passwd=None) + + def test_ssl_db_uri(tmpdir): with mock.patch.object(PGCli, "connect") as mock_connect: cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile"))) From 4ff7c7391fcd0c36b5fa2c6d155a66d24ecae839 Mon Sep 17 00:00:00 2001 From: b84330808 Date: Thu, 5 Nov 2026 23:08:31 +0900 Subject: [PATCH 2/2] Look up service files the way libpq does Read the per-user file first and fall back to $PGSYSCONFDIR/pg_service.conf when the service isn't there. The system file has no leading dot. With APPDATA unset on Windows there is no per-user file, instead of a path relative to the current directory. --- changelog.rst | 6 +++-- pgcli/main.py | 55 +++++++++++++++++++++++--------------------- tests/test_main.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 28 deletions(-) diff --git a/changelog.rst b/changelog.rst index 439bb0193..66ef7db85 100644 --- a/changelog.rst +++ b/changelog.rst @@ -17,8 +17,10 @@ Bug fixes: * Read ``alias_map_file`` as UTF-8 (with or without a BOM) instead of the locale encoding, which made non-ASCII aliases fail on Windows. * Fix a crash on Windows when connecting with ``service=...`` or ``PGSERVICE`` - while neither ``PGSERVICEFILE`` nor ``PGSYSCONFDIR`` is set. The service file - is now read from ``%APPDATA%\postgresql\.pg_service.conf``, as libpq does. + while neither ``PGSERVICEFILE`` nor ``PGSYSCONFDIR`` is set. Service files are + now looked up as libpq does: the per-user file first + (``%APPDATA%\postgresql\.pg_service.conf`` on Windows), then + ``$PGSYSCONFDIR/pg_service.conf`` if the service isn't there. Internal: --------- diff --git a/pgcli/main.py b/pgcli/main.py index a94019410..028cc5bdb 100644 --- a/pgcli/main.py +++ b/pgcli/main.py @@ -2273,34 +2273,37 @@ def format_status(cur, status): return output +def service_file_paths(): + """Return the service files libpq reads, in order: the per-user file, then the system one.""" + paths = [] + if os.getenv("PGSERVICEFILE"): + paths.append(os.getenv("PGSERVICEFILE")) + elif platform.system() == "Windows": + if os.getenv("APPDATA"): + paths.append(os.path.join(os.getenv("APPDATA"), "postgresql", ".pg_service.conf")) + else: + paths.append(os.path.expanduser("~/.pg_service.conf")) + if os.getenv("PGSYSCONFDIR"): + paths.append(os.path.join(os.getenv("PGSYSCONFDIR"), "pg_service.conf")) + return paths + + def parse_service_info(service): service = service or os.getenv("PGSERVICE") - service_file = os.getenv("PGSERVICEFILE") - if not service_file: - # try ~/.pg_service.conf (if that exists) - if platform.system() == "Windows" and os.getenv("PGSYSCONFDIR"): - service_file = os.getenv("PGSYSCONFDIR") + "\\pg_service.conf" - elif platform.system() == "Windows": - # libpq's per-user service file on Windows - service_file = os.path.join(os.getenv("APPDATA", ""), "postgresql", ".pg_service.conf") - elif os.getenv("PGSYSCONFDIR"): - service_file = os.path.join(os.getenv("PGSYSCONFDIR"), ".pg_service.conf") - else: - service_file = os.path.expanduser("~/.pg_service.conf") - if not service or not os.path.exists(service_file): - # nothing to do - return None, service_file - with open(service_file, newline="") as f: - skipped_lines = skip_initial_comment(f) - try: - service_file_config = ConfigObj(f) - except ParseError as err: - err.line_number += skipped_lines - raise err - if service not in service_file_config: - return None, service_file - service_conf = service_file_config.get(service) - return service_conf, service_file + service_files = service_file_paths() + for service_file in service_files: + if not service or not os.path.exists(service_file): + continue + with open(service_file, newline="") as f: + skipped_lines = skip_initial_comment(f) + try: + service_file_config = ConfigObj(f) + except ParseError as err: + err.line_number += skipped_lines + raise err + if service in service_file_config: + return service_file_config.get(service), service_file + return None, " or ".join(service_files) or "any service file" def duration_in_words(duration_in_seconds: float) -> str: diff --git a/tests/test_main.py b/tests/test_main.py index 4075e6cfe..2dfcce70f 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -24,6 +24,7 @@ notify_callback, PGCli, OutputSettings, + parse_service_info, COLOR_CODE_REGEX, ) from pgcli.pgexecute import PGExecute @@ -770,6 +771,62 @@ def test_pg_service_file_windows_default_location(tmp_path, monkeypatch): mock_connect.assert_called_with(database="a_dbname", host="a_host", user="a_user", port=None, passwd=None) +def service_cli(tmp_path, monkeypatch, system="Windows"): + cli = PGCli(pgclirc_file=str(tmp_path / "rcfile")) + monkeypatch.delenv("PGSERVICEFILE", raising=False) + monkeypatch.delenv("PGSYSCONFDIR", raising=False) + monkeypatch.delenv("APPDATA", raising=False) + monkeypatch.setattr("pgcli.main.platform.system", lambda: system) + return cli + + +def write_service(path, service, host): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"[{service}]\nhost={host}\ndbname=a_dbname\n") + + +@pytest.mark.parametrize("system", ["Windows", "Linux"]) +def test_pg_service_file_user_file_comes_first(tmp_path, monkeypatch, system): + cli = service_cli(tmp_path, monkeypatch, system) + user_file = tmp_path / "user" / ".pg_service.conf" + write_service(user_file, "myservice", "user_host") + write_service(tmp_path / "etc" / "pg_service.conf", "myservice", "system_host") + monkeypatch.setenv("PGSERVICEFILE", str(user_file)) + monkeypatch.setenv("PGSYSCONFDIR", str(tmp_path / "etc")) + with mock.patch.object(cli, "connect") as mock_connect: + cli.connect_service("myservice", "a_user") + assert mock_connect.call_args.kwargs["host"] == "user_host" + + +@pytest.mark.parametrize("system", ["Windows", "Linux"]) +def test_pg_service_file_falls_back_to_system_file(tmp_path, monkeypatch, system): + cli = service_cli(tmp_path, monkeypatch, system) + user_file = tmp_path / "user" / ".pg_service.conf" + write_service(user_file, "other_service", "user_host") + write_service(tmp_path / "etc" / "pg_service.conf", "myservice", "system_host") + monkeypatch.setenv("PGSERVICEFILE", str(user_file)) + monkeypatch.setenv("PGSYSCONFDIR", str(tmp_path / "etc")) + with mock.patch.object(cli, "connect") as mock_connect: + cli.connect_service("myservice", "a_user") + assert mock_connect.call_args.kwargs["host"] == "system_host" + + +def test_pg_service_file_system_file_has_no_leading_dot(tmp_path, monkeypatch): + service_cli(tmp_path, monkeypatch, "Linux") + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("USERPROFILE", str(tmp_path / "home")) + write_service(tmp_path / "etc" / ".pg_service.conf", "myservice", "dotted_host") + monkeypatch.setenv("PGSYSCONFDIR", str(tmp_path / "etc")) + assert parse_service_info("myservice")[0] is None + + +def test_pg_service_file_windows_without_appdata_ignores_cwd(tmp_path, monkeypatch): + service_cli(tmp_path, monkeypatch) + write_service(tmp_path / "postgresql" / ".pg_service.conf", "myservice", "cwd_host") + monkeypatch.chdir(tmp_path) + assert parse_service_info("myservice")[0] is None + + def test_ssl_db_uri(tmpdir): with mock.patch.object(PGCli, "connect") as mock_connect: cli = PGCli(pgclirc_file=str(tmpdir.join("rcfile")))