Skip to content

feat: Let postgresDefault() and postgresHasDefault() find a local server like other clients - #553

Draft
krlmlr with Copilot wants to merge 11 commits into
mainfrom
copilot/align-postgres-default-settings
Draft

krlmlr with Copilot wants to merge 11 commits into
mainfrom
copilot/align-postgres-default-settings

Conversation

Copilot AI commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

postgresDefault() and postgresHasDefault() now find a local server in the places other PostgreSQL clients look, not only where the libpq that RPostgres links to was built to look. dbConnect() stays fully deterministic and unchanged; its documentation for host and port points to the two functions.

Closes #552.

Behavior

  • Both functions first call dbConnect(Postgres(), ...) exactly as before, so everything libpq does by itself still applies: the PG* environment variables, ~/.pgpass, and libpq's compiled-in defaults.
  • If that attempt reaches no server at all (judged from libpq's messages, read with LANGUAGE=en as a best effort) and no host is chosen, neither in ... (host, hostaddr, service) nor in PGHOST, PGHOSTADDR or PGSERVICE, they also try the socket directories /var/run/postgresql, /private/tmp and /tmp (each only if it holds .s.PGSQL.<port> for the first port, and not the one libpq just tried), then host = "localhost", with connect_timeout = 5 unless a timeout is set. A server that answers with an error, such as failed authentication, ends the search. Users who set PGHOST etc. get the old single attempt.
  • The host a fallback found is remembered for the session; the DBItest context in tests/testthat/helper-DBItest.R reuses it.
  • Not on Windows, where libpq's default is already localhost.
  • It stays fast and quiet when nothing is there: a missing socket fails at once and a closed port on localhost is refused at once (about 30 ms here for postgresHasDefault(port = 1)). CRAN examples and tests keep seeing FALSE and a skip.
  • The postgresHasDefault() message no longer implies that all of PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE must be set; it lists every attempt with the first line of libpq's error and links the libpq environment variable docs.

How other clients decide defaults

  • psycopg (Python), LibPQ.jl (Julia): wrap libpq, so they behave as RPostgres did before: PG* variables, pg_service.conf, ~/.pgpass, and the socket directory compiled into the libpq they load (libpq environment variables, psycopg connection docs).
  • sqlx (Rust): reads PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE and more; without PGHOST it uses the first of /var/run/postgresql, /private/tmp, /tmp holding .s.PGSQL.<port>, else localhost (default_host()). This PR follows it.
  • pgx (Go): "uses the same defaults as libpq" and most PG* variables, .pgpass and the service file; the default host is the first existing directory of /var/run/postgresql, /private/tmp, /tmp, else localhost (defaultHost(), ParseConfig()).
  • tokio-postgres (Rust): reads no environment variables; a host must be given (Config).
  • node-postgres: PG* variables, ~/.pgpass, else localhost:5432 and the OS user, never a Unix socket by default (defaults.js).

Overlap

A separate branch, claude/fix-564-socket-dir, fixes #564 (dbConnect() looking for the socket in /tmp on Debian), which may change libpq's compiled-in socket directory. This PR touches only R/default.R, the host,port documentation in R/dbConnect_PqDriver.R and the generated man pages. With #564 fixed, the first attempt here succeeds more often and the fallbacks matter mostly for a libpq built elsewhere (static or bundled libpq, Homebrew vs. system server).

Tests

  • New tests/testthat/test-default.R: candidate selection with and without a host, first port of a port list, fallback order and error reporting (snapshot), stopping at a server that answered, skipping the socket libpq tried, the exact arguments reaching dbConnect() (host passed once, timeout added), postgresHasDefault() returning FALSE quickly with and without PGHOST, and postgresDefault(timezone = NULL) keeping the database's default time zone.
  • Full suite locally against PostgreSQL 16: no failures.

Review

Three rounds of clean review; nothing above Low remains. Accepted limitations.

History

Copilot started this PR by rewording the postgresHasDefault() message. The branch was then merged with main, whose history had been rewritten, resolving every conflict to main's version.

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

Copilot AI and others added 2 commits February 21, 2026 10:31
Update documentation to accurately reflect libpq's full default chain:
- dbname: mention PGDATABASE env var, then fallback to user name
- user: add OS username fallback when PGUSER is not set
- host,port: add libpq defaults (Unix socket, port 5432) when env vars unset
- service: add PGSERVICE env var mention
- postgresHasDefault(): clarify not all env vars are required

Co-authored-by: krlmlr <[email protected]>
Copilot AI changed the title [WIP] Align postgresDefault() with other Postgres libraries Align postgresDefault() docs with libpq defaults Feb 21, 2026
Copilot AI requested a review from krlmlr February 21, 2026 10:32

@krlmlr krlmlr left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot dbConnect should be fully deterministic and does not need to change. Only postgresDefault() and ...HasDef... should change. The documentation of dbConnect can point to the latter.

…ssage

Per reviewer feedback, dbConnect should remain fully deterministic.
Only the postgresHasDefault() error message in default.R is updated
to clarify libpq defaults. All changes to dbConnect_PqDriver.R and
generated man pages are reverted.

Co-authored-by: krlmlr <[email protected]>

Copilot AI commented Feb 21, 2026

Copy link
Copy Markdown
Contributor Author

@copilot dbConnect should be fully deterministic and does not need to change. Only postgresDefault() and ...HasDef... should change. The documentation of dbConnect can point to the latter.

Reverted all dbConnect_PqDriver.R and man page changes in 7b95542. Only postgresHasDefault() error message in R/default.R is updated now.

Copilot AI changed the title Align postgresDefault() docs with libpq defaults Update postgresHasDefault() error message to document libpq defaults Feb 21, 2026
Copilot AI requested a review from krlmlr February 21, 2026 12:51
main's history was rewritten after the branch was cut,
so every conflict resolves to main's version.
The branch's own change to R/default.R is reworked in the next commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
… server like other clients

When the attempt with libpq's defaults fails and no host is set
in the arguments or in `PGHOST`, `PGHOSTADDR` or `PGSERVICE`,
both functions also try the socket directories `/var/run/postgresql`,
`/private/tmp` and `/tmp`, each only if it holds a socket for the port,
and then `localhost`, as sqlx and pgx do.
`dbConnect()` is unchanged, and its documentation points to them.
The message of `postgresHasDefault()` lists every failed attempt
instead of implying that all `PG*` variables must be set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
@krlmlr krlmlr changed the title Update postgresHasDefault() error message to document libpq defaults feat: Let postgresDefault() and postgresHasDefault() find a local server like other clients Nov 29, 2026

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member

Question: fall back to localhost on Unix?

After the libpq-default attempt and the socket directories, default_host_candidates() also tries host = "localhost". sqlx, pgx and node-postgres do this; psql does not (it uses only libpq's socket). It helps when a server listens only on TCP (Docker with a published port, Postgres.app setups), and costs a refused connection (milliseconds) when nothing listens. TCP may use a different pg_hba.conf rule than the socket (password instead of peer), so postgresDefault() can end up as a different user setup than psql would. If nobody decides, the fallback stays.

  • Keep the localhost fallback, as sqlx and pgx (recommended)
  • Drop it: only socket directories, closer to psql

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Question: fall back after any error, or only after connection failures?

As of a240659, connect_default() moves on to the next candidate only when libpq reached no server at all. It recognizes that from libpq's English messages ("Is the server running", "Connection refused", "No such file or directory", "could not translate host name", "timeout expired") in is_connection_failure(). A server that answers with an error (for example peer or password authentication failed, a missing database, an unknown timezone) ends the search. That avoids silently switching from a socket with peer auth to a different server on TCP localhost, such as a Docker container, that tests would then write to. The cost is matching message text. The attempts run with LANGUAGE=en so that translated libpq and strerror() messages come out in English (not verified here: this machine has no libpq translations); if a message still does not match, there is no fallback, which is the old behavior. Matching on the connection status instead would need a C++ change (for example exposing PQping()). It also skips the socket directory that libpq's own message says it just tried. If nobody decides, it stays as implemented.

  • Fall back only when libpq could not reach a server; stop at once on other errors (recommended, implemented)
  • Fall back after any error, report all attempts

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

…st once

`connect_default()` now stops at a server that answers with an error,
skips the socket directory libpq has just tried,
uses `connect_timeout = 5` for the fallbacks unless a timeout is set,
uses the first port of a list for the socket file name,
keeps the first line of each libpq message,
and no longer passes `host` twice when the caller gives `host = NULL`.
The DBItest context reuses the host the fallback found.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member

Question: should examples gated by postgresHasDefault() connect with postgresDefault()?

postgresHasDefault() can now return TRUE because a fallback host works, while the code it gates still calls plain dbConnect(RPostgres::Postgres()), which tries only libpq's defaults and then fails. The tests are fixed in this PR: the DBItest context in tests/testthat/helper-DBItest.R now gets the host the fallback found from the internal postgres_default_args(), and the remaining tests already use postgresDefault(). The examples (@examplesIf postgresHasDefault() in R/dbConnect_PqDriver.R, R/quote.R, R/tables.R, R/transactions.R, R/PqResult.R, R/PqConnection.R) and vignettes/work-queue.Rmd still call dbConnect(RPostgres::Postgres()). Switching them changes what users copy, since postgresDefault() raises a testthat skip on failure and is documented for tests. This only matters on a machine where libpq's own default fails and a fallback works, mostly when the system libpq and the server disagree on the socket directory (#564). If nobody decides, the examples stay as they are.

  • Leave the examples alone; they matter only where Error in dbConnect(): linux socket location moved #564 bites, and dbConnect() is what users should copy (recommended)
  • Gate the examples with a check that only libpq's defaults are tried (for example an internal postgresHasDefault() variant), so they are skipped instead of failing
  • Switch the examples and vignette to postgresDefault()

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

…ages in English

Dropping every NULL argument turned `timezone = NULL` into the default "UTC".
Only `host` is replaced now.
The connection attempts run with `LANGUAGE=en`,
so that the fallback also works where libpq's messages are translated,
and the remembered host is documented as internal, for tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Accepted limitations

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 19:44
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member

Holding off to better understand the limitations.

@krlmlr
krlmlr marked this pull request as draft November 29, 2026 20:03

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Error in dbConnect(): linux socket location moved Align postgresDefault() with other Postgres libraries

3 participants