diff --git a/changelog.rst b/changelog.rst index fc362092b..66ef7db85 100644 --- a/changelog.rst +++ b/changelog.rst @@ -16,6 +16,11 @@ 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. 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 972b3c670..028cc5bdb 100644 --- a/pgcli/main.py +++ b/pgcli/main.py @@ -2273,31 +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": - service_file = os.getenv("PGSYSCONFDIR") + "\\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 57ba8afe8..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 @@ -754,6 +755,78 @@ 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 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")))