Skip to content
Merged
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
4 changes: 3 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ Imports:
hms (>= 1.0.0),
lubridate,
methods,
rlang (>= 1.0.0),
withr
Suggests:
callr,
covr,
DBItest (>= 1.7.3),
knitr,
nanoarrow,
rlang,
rmarkdown,
testthat (>= 3.0.0)
LinkingTo:
Expand Down Expand Up @@ -109,7 +109,9 @@ Collate:
'default.R'
'export.R'
'quote.R'
'rethrow.R'
'show_PqConnection.R'
'signal_pq_error.R'
'sqlData_PqConnection.R'
'tables.R'
'transactions.R'
Expand Down
2 changes: 1 addition & 1 deletion R/dbBind_PqResult.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ dbBind_PqResult <- function(res, params, ...) {
params <- difftime_to_hms(params)
params <- fix_numeric(params)
params <- prepare_for_binding(params)
result_bind(res@ptr, params)
rethrow(result_bind(res@ptr, params))
invisible(res)
}

Expand Down
2 changes: 1 addition & 1 deletion R/dbFetch_PqResult.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ dbFetch_PqResult <- function(res, n = -1, ..., row.names = FALSE) {
if (trunc(n) != n) {
stopc("n must be a whole number")
}
ret <- sqlColumnToRownames(result_fetch(res@ptr, n = n), row.names)
ret <- sqlColumnToRownames(rethrow(result_fetch(res@ptr, n = n)), row.names)
ret <- convert_bigint(ret, res@bigint)
ret <- finalize_types(ret, res@conn)
ret <- fix_timezone(ret, res@conn)
Expand Down
2 changes: 1 addition & 1 deletion R/dbSendQuery_PqConnection.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ dbSendQuery_PqConnection <- function(
rs <- new(
"PqResult",
conn = conn,
ptr = result_create(conn@ptr, statement, immediate),
ptr = rethrow(result_create(conn@ptr, statement, immediate)),
sql = statement,
bigint = conn@bigint
)
Expand Down
46 changes: 46 additions & 0 deletions R/rethrow.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Restore the user-facing call on errors raised from C++.
#
# Server errors are signalled by `signal_pq_error()` (see `R/signal_pq_error.R`),
# which `DbConnection::result_stop()` calls through a `cpp11::function`.
# cpp11 evaluates that call in the global environment,
# so the condition is created detached from the frames of the DBI verb and its `call` is empty.
#
# The condition survives the trip back through C++ because R finds its handlers when it is signalled,
# while the C++ frames are still on the stack:
# the calling handler installed here runs first, before anything unwinds.
# It sets the call and signals the same condition again with `stop()`,
# which jumps to the user's handler or to the top level.
# cpp11's unwind protection intercepts that jump at the C++ frames,
# runs their destructors, and resumes it past the `.Call()` boundary.
# The class, the fields and the backtrace captured by `rlang::abort()` stay as they were;
# only the `call` changes.
#
# `rethrow()` wraps the cpp11 entry points that can raise an `RPostgres_error`.
#
# Base `withCallingHandlers()` rather than `rlang::try_fetch()`:
# it runs on every `dbFetch()`, and costs about 2 instead of 12 microseconds.
rethrow <- function(expr, call = dbi_call(parent.frame())) {
withCallingHandlers(
expr,
RPostgres_error = function(cnd) {
cnd$call <- call
stop(cnd)
}
)
}

# The call that invoked the frame `env`, normally a DBI method.
# S4 wraps a method that has extra formals, such as `dbSendQuery()`'s `immediate`,
# in a `.local()` closure; the call above that one is the DBI verb.
dbi_call <- function(env) {
i <- which(vapply(sys.frames(), identical, logical(1), env))
if (length(i) == 0L) {
return(NULL)
}
i <- max(i)
call <- sys.call(i)
if (is.call(call) && identical(call[[1L]], quote(.local))) {
call <- sys.call(sys.parents()[[i]])
}
call
}
149 changes: 149 additions & 0 deletions R/signal_pq_error.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#' RPostgres error conditions
#'
#' @description
#' When the server reports an error,
#' RPostgres raises an [rlang::abort()] condition
#' that carries PostgreSQL's `SQLSTATE` code
#' and the other diagnostic fields reported by libpq.
#' The class vector of the condition is
#' `c("RPostgres_error_<SQLSTATE>", "RPostgres_error", "rlang_error", "error", "condition")`,
#' so handlers can dispatch on a specific code or on all RPostgres errors.
#' Branch on the code rather than on the message,
#' which the server may translate according to its `lc_messages` setting.
#'
#' @details
#' An error raised while a statement runs names the DBI method that ran it,
#' such as [DBI::dbSendQuery()], [DBI::dbFetch()], [DBI::dbBind()] or [DBI::dbAppendTable()].
#' That can be a method DBI calls internally:
#' an error in [DBI::dbGetQuery()] or [DBI::dbExecute()] names `dbSendQuery()`,
#' or `dbBind()` when `params` are given.
#'
#' # Message
#'
#' The first line of the message is the step that failed, such as "Failed to fetch row",
#' followed by the server's primary message.
#' Each field below that is set follows as an `i` bullet,
#' in place of the `DETAIL:`, `HINT:` and `CONTEXT:` lines of libpq's own text:
#'
#' ```
#' Error in `dbSendQuery()`:
#' ! Failed to fetch row : duplicate key value violates unique constraint "t_pkey"
#' i SQLSTATE: 23505
#' i Detail: Key (id)=(1) already exists.
#' i Schema: public
#' i Table: t
#' i Constraint: t_pkey
#' ```
#'
#' [conditionMessage()] returns all of these lines.
#'
#' # Fields
#'
#' The following fields are attached to the condition object,
#' each `NULL` when libpq did not supply a value:
#' `sqlstate`, `detail`, `hint`, `position`, `context`, `schema`, `table`, `column`, `datatype`, and `constraint`.
#' They map to the corresponding `PG_DIAG_*` fields of libpq's `PQresultErrorField()`;
#' `position` is the character offset into the statement, as a string.
#' See <https://www.postgresql.org/docs/current/errcodes-appendix.html> for the codes.
#'
#' # Errors without a code
#'
#' An error detected by libpq rather than reported by the server,
#' such as a lost connection,
#' still carries the `RPostgres_error` class but has no `sqlstate`.
#' Its message is the step that failed followed by libpq's text, without bullets.
#' A lost connection detected outside of running a statement,
#' for instance while quoting, has no call.
#' Errors raised by [DBI::dbConnect()], by [postgresImportLargeObject()] and [postgresExportLargeObject()],
#' and by checks of the arguments in R or C++
#' are ordinary errors without these classes and fields.
#'
#' @examples
#' \dontrun{
#' # Dispatch on a specific SQLSTATE
#' tryCatch(
#' dbGetQuery(con, "SELECT * FROM no_such_table"),
#' RPostgres_error_42P01 = function(e) e$sqlstate
#' )
#'
#' # Read the SQLSTATE programmatically
#' cnd <- tryCatch(
#' dbGetQuery(con, "SELECT * FROM no_such_table"),
#' RPostgres_error = identity
#' )
#' cnd$sqlstate
#' }
#' @name RPostgres-conditions
NULL

# Build a classed rlang error carrying libpq diagnostic fields and signal it.
# Called from C++ by `DbConnection::result_stop()`.
# `step` names what failed, such as "Failed to fetch row".
# `message` is that step followed by libpq's full message.
# `fields` is a named list; any element may be NULL (absent libpq field).
#
# cpp11 evaluates this helper in the global environment,
# so it runs detached from the caller's frames and cannot find the user-facing call.
# The error is therefore raised with `call = NULL`,
# and `rethrow()` around the C++ entry points fills in the call; see `R/rethrow.R`.
signal_pq_error <- function(step, message, fields = list()) {
sqlstate <- fields$sqlstate

# rlang::abort() appends "rlang_error", "error", and "condition" itself.
classes <- c(
if (!is.null(sqlstate) && nzchar(sqlstate)) {
paste0("RPostgres_error_", sqlstate)
},
"RPostgres_error"
)

# A server error is printed as its primary text, and the diagnostic fields
# as bullets below it, instead of libpq's DETAIL, HINT and CONTEXT lines.
# An error that libpq produced itself has no SQLSTATE and keeps its text.
body <- NULL
if (!is.null(sqlstate) && !is.null(fields$primary)) {
message <- paste0(step, " : ", fields$primary)
body <- pq_error_bullets(fields)
}

rlang::abort(
message,
class = classes,
call = NULL,
body = body,
sqlstate = sqlstate,
detail = fields$detail,
hint = fields$hint,
position = fields$position,
context = fields$context,
schema = fields$schema,
table = fields$table,
column = fields$column,
datatype = fields$datatype,
constraint = fields$constraint
)
}

# One `i` bullet per diagnostic field that is set, in a fixed order.
pq_error_bullets <- function(fields) {
labels <- c(
sqlstate = "SQLSTATE",
detail = "Detail",
hint = "Hint",
position = "Position",
context = "Context",
schema = "Schema",
table = "Table",
column = "Column",
datatype = "Data type",
constraint = "Constraint"
)
values <- fields[names(labels)]
set <- !vapply(values, is.null, logical(1))
# A multi-line value, such as a context with several frames,
# is indented under its bullet.
text <- gsub("\n", "\n ", unlist(values[set]), fixed = TRUE)
bullets <- paste0(labels[set], ": ", text)
names(bullets) <- rep("i", length(bullets))
bullets
}
11 changes: 9 additions & 2 deletions R/tables.R
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,14 @@ format_keep_na <- function(x, ...) {
ret
}

db_append_table <- function(conn, name, value, copy, warn) {
db_append_table <- function(
conn,
name,
value,
copy,
warn,
call = dbi_call(parent.frame())
) {
value <- factor_to_string(value, warn = warn)

if (is.null(copy)) {
Expand All @@ -113,7 +120,7 @@ db_append_table <- function(conn, name, value, copy, warn) {
")",
" FROM STDIN"
)
connection_copy_data(conn@ptr, sql, value)
rethrow(connection_copy_data(conn@ptr, sql, value), call = call)
} else {
sql <- sqlAppendTable(conn, name, value, row.names = FALSE)
dbExecute(conn, sql)
Expand Down
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ reference:
desc: Functions specific to Postgres
contents:
- '`RPostgres-package`'
- '`RPostgres-conditions`'
- postgresHasDefault
- postgresWaitForNotify
- postgresImportLargeObject
Expand Down
78 changes: 78 additions & 0 deletions man/RPostgres-conditions.Rd

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

Loading