Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion R/dbConnect_PqDriver.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@
#' If `NULL`, will be retrieved from `PGUSER` and `PGPASSWORD` envvars, or from the appropriate line in `~/.pgpass`.
#' See <https://www.postgresql.org/docs/current/libpq-pgpass.html> for more details.
#' @param host,port Host and port.
#' If `NULL`, will be retrieved from `PGHOST` and `PGPORT` env vars.
#' If `NULL`, will be retrieved from `PGHOST` and `PGPORT` env vars,
#' or left to the defaults libpq was built with.
#' `dbConnect()` makes a single attempt with exactly these parameters;
#' [postgresDefault()] and [postgresHasDefault()], meant for examples and tests,
#' also look for a local server in other places.
#' @param service Name of service to connect as.
#' If `NULL`, will be ignored.
#' Otherwise, connection parameters will be loaded from the pg_service.conf file and used.
Expand Down
167 changes: 159 additions & 8 deletions R/default.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,43 @@
#' Check if default database is available.
#'
#' RPostgres examples and tests connect to a default database via `dbConnect(`[RPostgres::Postgres()]`)`.
#' This function checks if that database is available, and if not, displays an informative message.
#' RPostgres examples and tests connect to a default database via
#' `postgresDefault()`.
#' `postgresHasDefault()` checks if that database is available,
#' and if not, displays an informative message.
#'
#' Both functions first call `dbConnect(`[RPostgres::Postgres()]`, ...)`,
#' which leaves every unset connection parameter to libpq:
#' the `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE`
#' and other `PG*` environment variables, `~/.pgpass`,
#' and the defaults libpq was built with.
#' See <https://www.postgresql.org/docs/current/libpq-envars.html>.
#'
#' The libpq that RPostgres uses may look for the local server's socket
#' in another directory than the server and `psql` use,
#' for instance `/tmp` instead of `/var/run/postgresql`.
#' If that first attempt reaches no server at all and no host is given,
#' neither in `...` (`host`, `hostaddr`, `service`)
#' nor in the `PGHOST`, `PGHOSTADDR` or `PGSERVICE` environment variables,
#' both functions also try, in this order:
#'
#' - the socket directories `/var/run/postgresql`, `/private/tmp` and `/tmp`,
#' each only if it holds a socket file for the port,
#' - `host = "localhost"`.
#'
#' These extra attempts use `connect_timeout = 5`
#' unless `connect_timeout` or `PGCONNECT_TIMEOUT` is set.
#' A server that answers with an error, such as a failed authentication
#' or a missing database, ends the search.
#' The attempts run with `LANGUAGE=en`, on a best-effort basis,
#' so that libpq's messages can be told apart;
#' a message that is still translated means no fallback.
#'
#' Other PostgreSQL clients, such as sqlx for Rust and pgx for Go,
#' look for the local server in the same places.
#' These extra attempts are not made on Windows,
#' where libpq connects to `localhost` by default.
#' Unlike `dbConnect()`, which is fully deterministic,
#' these functions are meant for examples and tests only.
#'
#' @param ... Additional arguments passed on to [dbConnect()]
#' @export
Expand All @@ -20,12 +56,14 @@ postgresHasDefault <- function(...) {
dbDisconnect(con)
TRUE
},
error = function(...) {
error = function(e) {
message(
"Could not initialise default postgres database. If postgres is running\n",
"check that the environment variables PGHOST, PGPORT, \n",
"PGUSER, PGPASSWORD, and PGDATABASE, are defined and\n",
"point to your database."
"Could not connect to the default PostgreSQL database.\n",
conditionMessage(e),
"\n",
"Set the PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE ",
"environment variables as needed, see ",
"https://www.postgresql.org/docs/current/libpq-envars.html."
)
FALSE
}
Expand All @@ -49,5 +87,118 @@ postgresDefault <- function(...) {
}

connect_default <- function(...) {
dbConnect(Postgres(), ...)
# Keep NULL arguments: `timezone = NULL` differs from the default.
# connect_host() replaces a `host = NULL` entry.
args <- list(...)
hosts <- default_host_candidates(args)

errors <- character()
while (length(hosts) > 0) {
host <- hosts[[1]]
hosts <- hosts[-1]
# Best effort: English messages, so that is_connection_failure() can read
# them. gettext reads LANGUAGE on each call, but glibc caches translations,
# so a message translated earlier in the process may stay translated.
con <- withr::with_envvar(
c(LANGUAGE = "en"),
tryCatch(connect_host(host, args), error = identity)
)
if (!inherits(con, "error")) {
the$default_host <- host
return(con)
}

message <- conditionMessage(con)
label <- if (is.null(host)) "libpq defaults" else paste0("host ", host)
first_line <- trimws(strsplit(message, "\n", fixed = TRUE)[[1]][[1]])
errors[[length(errors) + 1]] <- paste0("* ", label, ": ", first_line)

# A server that answered (wrong password, missing database, bad option)
# is the one meant, so do not look for another one.
if (!is_connection_failure(message)) {
break
}
# Do not try the socket directory libpq has just tried.
if (is.null(host)) {
tried <- function(h) {
grepl(paste0("\"", h, "/.s.PGSQL."), message, fixed = TRUE)
}
hosts <- Filter(Negate(tried), hosts)
}
}

stop(paste(errors, collapse = "\n"), call. = FALSE)
}

connect_host <- function(host, args) {
if (!is.null(host)) {
args$host <- host
if (
is.null(args[["connect_timeout"]]) &&
!nzchar(Sys.getenv("PGCONNECT_TIMEOUT"))
) {
args$connect_timeout <- "5"
}
}
do.call(dbConnect, c(list(Postgres()), args))
}

# libpq's messages when no server could be reached at all.
# With translated messages, this does not match, and there is no fallback.
is_connection_failure <- function(message) {
grepl(
"Is the server running|Connection refused|No such file or directory|could not translate host name|timeout expired",
message
)
}

# The first candidate, `NULL`, leaves the host to libpq.
# The others are only tried when nothing selects a host.
default_host_candidates <- function(args) {
if (has_default_target(args) || .Platform$OS.type == "windows") {
return(list(NULL))
}

socket <- paste0(".s.PGSQL.", default_port(args[["port"]]))
dirs <- c("/var/run/postgresql", "/private/tmp", "/tmp")
dirs <- dirs[file.exists(file.path(dirs, socket))]

c(list(NULL), as.list(dirs), list("localhost"))
}

# The first port of a list such as "5432,5433", as libpq would use first.
default_port <- function(port = NULL) {
if (is.null(port)) {
port <- Sys.getenv("PGPORT")
}
port <- trimws(strsplit(as.character(port), ",", fixed = TRUE)[[1]][1])
if (is.na(port) || !nzchar(port)) {
port <- "5432"
}
port
}

has_default_target <- function(args) {
arg_names <- c("host", "hostaddr", "service")
if (any(lengths(args[intersect(names(args), arg_names)]) > 0)) {
return(TRUE)
}
env_vars <- c("PGHOST", "PGHOSTADDR", "PGSERVICE")
any(nzchar(Sys.getenv(env_vars)))
}

# Internal, for tests only: holds the host of the last successful
# connect_default() call (`NULL` for libpq's defaults).
# It is not tied to PGHOST or the port and never cleared,
# so it is only meant for one test run with fixed settings.
the <- new.env(parent = emptyenv())

# Connection arguments for code that cannot call postgresDefault(),
# such as a DBItest context: the host a fallback found, or none.
postgres_default_args <- function() {
if (!exists("default_host", envir = the)) {
try(dbDisconnect(connect_default()), silent = TRUE)
}
host <- get0("default_host", envir = the)
if (is.null(host)) NULL else list(host = host)
}
6 changes: 5 additions & 1 deletion man/Postgres.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion man/Redshift.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 40 additions & 2 deletions man/postgresHasDefault.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions tests/testthat/_snaps/default.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# connect_default() reports every failed attempt, first lines only

Code
connect_default()
Condition
Error:
! * libpq defaults: Connection refused
* host /a: Connection refused
* host localhost: Connection refused

3 changes: 2 additions & 1 deletion tests/testthat/helper-DBItest.R
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
if (rlang::is_installed("DBItest")) {
DBItest::make_context(
Postgres(),
NULL,
# The host postgresDefault() found, if it needed a fallback
postgres_default_args(),
name = "RPostgres",

# Redshift:
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/helper-default.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Restores the host that postgresDefault() remembers when the test ends.
local_default_host <- function(.env = parent.frame()) {
old <- as.list(the)
withr::defer(
{
rm(list = ls(the), envir = the)
list2env(old, the)
},
envir = .env
)
}
Loading