Repository navigation
feat: Expose the PostgreSQL SQLSTATE and diagnostic fields on errors - #666
Conversation
Server errors now raise a classed rlang error,
`c("RPostgres_error_<SQLSTATE>", "RPostgres_error", "rlang_error", "error", "condition")`,
that carries the SQLSTATE and the other libpq diagnostic fields.
A `rethrow()` wrapper around the C++ entry points restores the calling context.
Ported from #581 onto the current main.
The one conflict, in `DbConnection::conn_stop()`, is resolved in favor of the new `result_stop()`,
whose fallback now passes the message as a `"%s"` argument as #665 requires.
Co-authored-by: Kirill Müller <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
`dbAppendTable()` and `dbWriteTable()` with `copy = TRUE` now pass the result of the failing `COPY ... FROM STDIN` to `result_stop()`, so an unknown column or a missing table also carries its SQLSTATE. `result_stop()` is declared `[[noreturn]]`, which documents that the `PQclear()` after each call is never reached for the result it owns. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
…able()` `rethrow()` finds the call from the frame of its caller and skips the `.local()` wrapper that S4 adds, which also works when the C++ entry point sits in a helper such as `db_append_table()`. Its comment now explains why the condition survives the trip through C++. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Require rlang 1.0.0 for `rlang::try_fetch()`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
The snapshot sets `lc_messages` to C so that the server's text does not depend on its locale, and skips where the role may not set it. The redundant `local_edition(3)` is gone, since DESCRIPTION selects edition 3. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
`pg_terminate_backend()` returns once it has signalled the backend, so the next query could still reach it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
`result_stop()` copies the diagnostic fields into C++ strings and calls `PQclear()` first, so an R error while building the field list cannot leak the `PGresult`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Question: How far should this PR follow duckdb's rethrow scheme?
Going the full way here means a generator script, wrappers for about 25 entry points, and changed class and call for every C++ error, which widens the change well beyond #579. Keeping the scope means those other errors stay
Generated by Claude Code |
Question: Accept that server errors are no longer
|
Question: Should
|
Question: Accept the
|
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Superseded: Accepted limitationsSuperseded by the new Accepted limitations comment.
Generated by Claude Code |
A message from the server is UTF-8, the client encoding RPostgres sets, but one that libpq produces itself, such as for a lost connection, is native, as `cpp11::stop()` treated it before. `signal_pq_error()` is now looked up on every error instead of cached in a static, so a reloaded namespace is honored. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
`rlang::try_fetch()` added about 12 microseconds to every `dbFetch()`; the base function adds about 2. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
`?RPostgres-conditions` says that `dbGetQuery()` and `dbExecute()` report `dbSendQuery()` or `dbBind()`, and that large object import and export errors stay plain. A test checks the diagnostic fields with `lc_messages` set to C. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Question: Should the error name the verb the user called, or the DBI method that ran the statement?
The fix would walk up the frames to the outermost call of a DBI generic and report that one. It costs about ten lines, runs only on errors, and depends on recognizing DBI generics by name, which has its own edge cases: a user wrapper named like a generic, or dbplyr calling
Generated by Claude Code |
Question: Accept the handler cost on every
|
Superseded: Accepted limitationsSuperseded by #666 (comment).
Generated by Claude Code |
| dbGetQuery(con, "SELECT * FROM no_such_table_579") | ||
| Condition | ||
| Error in `dbSendQuery()`: | ||
| ! Failed to prepare query : ERROR: relation "no_such_table_579" does not exist |
There was a problem hiding this comment.
Is there an easy way to show the sqlstate and other fields in this output by default?
There was a problem hiding this comment.
Yes: rlang can print the SQLSTATE and the fields as ℹ bullets under the message (a body in abort() or a cnd_body() method). The trade-off is that conditionMessage() then includes those lines too, and libpq already prints DETAIL/HINT/CONTEXT. Options in #666 (comment).
Generated by Claude Code
Resolved: Should the printed error show the SQLSTATE and the other diagnostic fields?Asked in this review comment. Today the printed error is the libpq message alone, e.g.
Kirill decided (#666 (comment)): "Restructure, with tests that show where it matters." Generated by Claude Code |
Accepted limitations
Generated by Claude Code |
|
Restructure, with tests that show where it matters. |
…s bullets A server error now reads as the failing step and the primary message, followed by an `i` bullet for each field that is set: SQLSTATE, detail, hint, position, context, schema, table, column, data type and constraint. These replace the DETAIL, HINT and CONTEXT lines of libpq's text, so nothing is printed twice. The condition gains a `position` field. Errors that libpq produced itself, recognized by the missing SQLSTATE, keep their text and stay in the native encoding. Snapshot tests with `lc_messages` set to C show the output for undefined objects, syntax and type errors, unique, not-null, check and domain violations, COPY, PL/pgSQL with a custom code, and a context over several lines. Another test pins what `conditionMessage()` returns. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
No conflicts with the deferred warnings of #669. An RPostgres_error leaves any warnings queued by the failing call in the queue; the next entry point that raises deferred warnings clears it first, so they never surface in a later call. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Server errors now also carry `internal_query` and `internal_position`, so that an error in dynamic SQL, such as a string run by `EXECUTE` in PL/pgSQL, shows the failing statement again. A position is followed by the line of the statement it points into with a caret below, like libpq's `LINE n:` excerpt. Warnings queued during the failing call, such as a failed `PQcancel()`, are signaled before the error instead of being dropped by the next call. The snapshots no longer depend on server wording that differs between PostgreSQL versions. Follow-up to #666. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
…#671) * chore: Start the follow-up to #666 [ci skip] Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc * fix: Show the internal query and statement excerpt in server errors Server errors now also carry `internal_query` and `internal_position`, so that an error in dynamic SQL, such as a string run by `EXECUTE` in PL/pgSQL, shows the failing statement again. A position is followed by the line of the statement it points into with a caret below, like libpq's `LINE n:` excerpt. Warnings queued during the failing call, such as a failed `PQcancel()`, are signaled before the error instead of being dropped by the next call. The snapshots no longer depend on server wording that differs between PostgreSQL versions. Follow-up to #666. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc * fix: Attach queued warnings to the error instead of signaling them first Signaling a queued warning, such as a failed `PQcancel()`, before the server error let `options(warn = 2)` or a warning handler replace the error. The error now carries them in a `warnings` field and as `i Warning:` bullets, and the "Interrupted." error appends them to its message. Every connection entry point that can raise such an error clears the queue on entry. The statement excerpt no longer splits the whole statement into characters: it finds the line with one regular expression and works on the characters around the caret. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc * chore: Auto-update from GitHub Actions Run: https://github.com/r-dbi/RPostgres/actions/runs/46296273200 * fix: Class the remaining libpq errors and let them carry queued warnings Errors detected by libpq while waiting for data or notifications, and a failed `PQgetCancel()`, now go through `conn_stop()`, so that they are `RPostgres_error`s with libpq's text and carry queued warnings. "Interrupted." and a failed `select()` are classed the same way, without libpq's text. The statement excerpt is skipped for a statement that is not valid in its encoding. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc --------- Co-authored-by: Claude <[email protected]>
Picks up #581 by David Schoch (
schochastics) as a PR we own, ported onto the currentmain. The first commit carries his code with him as author; the commits on top address the review on #581.Closes #579.
What it does
When the server reports an error, RPostgres now raises an rlang error of class
c("RPostgres_error_<SQLSTATE>", "RPostgres_error", "rlang_error", "error", "condition")with the fieldssqlstate,detail,hint,position,context,schema,table,column,datatypeandconstraint(eachNULLwhen libpq has no value). Handlers can dispatch on a code,tryCatch(..., RPostgres_error_23505 = ...), or readcnd$sqlstate, including custom codes fromRAISE EXCEPTION ... USING ERRCODE.?RPostgres-conditionsdocuments this.The printed message is the failing step and the server's primary text, followed by one
ibullet per field that is set. These bullets replace libpq'sDETAIL:,HINT:andCONTEXT:lines, so nothing is printed twice; theLINE 1: ... ^pointer becomes thePositionbullet. I kept the existing step prefix, such as "Failed to fetch row" or "COPY returned error", because it tells prepare, fetch and COPY apart, and kept its " : " separator so that the first line looks as before for code that matches on it.conditionMessage()returns all of these lines. Errors that libpq produces itself, such as a lost connection, have no SQLSTATE: they carryRPostgres_errorwithout a code and keep libpq's text, without bullets.Covered paths:
prepare(),step_run()(send, fetch and bind), and both COPY results indbAppendTable()/dbWriteTable(), the start of the COPY included. The error names the DBI method that ran the statement; fordbGetQuery()anddbExecute()that isdbSendQuery()ordbBind(), as in duckdb-r.dbConnect()failures, large object import and export, and argument checks stay plain errors.How the review on #581 is addressed
signal_pq_error()raises withrlang::abort(); rlang moves from Suggests to Imports (>= 1.0.0, whichabort(body = )needs). It is no new install: hms already imports it.tests/testthat/_snaps/sqlstate.mdshows the printed output where the bullets matter: undefined table and column, syntax error, invalid input for a type, unique, not-null and check violations, the same through COPY, a domain constraint (data type), a customRAISEwith code, detail and hint, a context over several lines from a function, and an error at fetch time. A separate test pins whatconditionMessage()returns.local_edition(3)is not needed, since DESCRIPTION sets edition 3. The tests setlc_messagesto C (skipping where the role may not), so the snapshots do not depend on the server's locale.rethrow(), cf. duckdb's generatedrethrow_rapi_*()) puts the DBI call intocall. Two differences: duckdb wraps everyrapi_*entry point by a generated file and catches every error, rebuilding it with a freshrlang::abort(); here four entry points are wrapped by hand, onlyRPostgres_erroris caught, and the original condition is re-signalled with itscallset, so its fields and backtrace stay as captured. Whether to go all the way to duckdb's scheme is a question below.rethrow()runs first, setscall, and re-signals the same object withstop(), which jumps to the user's handler or to the top level. cpp11's unwind protection (R_UnwindProtect()) intercepts that jump at the C++ frames, turns it into a C++ exception so destructors run, and resumes it withR_ContinueUnwind()past.Call(). The object itself never crosses C++. The captured backtrace shows the helper as a separate top-level branch, because cpp11 evaluates it in the global environment:RPostgres-conditionsis listed in_pkgdown.yml;pkgdown::check_pkgdown()finds no problems.Changes beyond #581
cpp11::stop()passes the message as a"%s"argument.dbAppendTable()anddbWriteTable()errors name the DBI verb instead of the internaldb_append_table();rethrow()finds the call from its caller's frame and skips S4's.local().result_stop()copies the fields and frees thePGresultbefore allocating R objects, and is[[noreturn]]. A server message is marked UTF-8 (the client encoding), while a message libpq produces itself stays native, as before. The R helper is looked up per error rather than cached in a static.rethrow()uses basewithCallingHandlers(): about 2 µs perdbFetch()instead of about 12 µs withrlang::try_fetch().lc_messagesset to C), and plainerrorhandlers still catching.Backward compatibility
tryCatch(error = ),try()andexpect_error()still catch these errors. What changes:conditionMessage()of a server error drops theERROR:label and libpq'sDETAIL:/HINT:/CONTEXT:/LINElines in favor of the bullets (decided in this question), the class no longer includessimpleError,conditionCall()is a DBI call instead ofNULL, and printing uses rlang's format.Not in this PR
No
NEWS.mdbullet:.github/CONTRIBUTING.mdasks contributors not to edit it, and no PR since the fledge marker was dropped (#628) adds one; entries are written at release.Status
Tests pass locally against PostgreSQL 16 (full suite including DBItest). The clean review of the earlier state (one round, run with valgrind and against
main) found nothing above Low; its Lows are fixed or listed as accepted limitations with a question each. The restructured message is still to be reviewed.Interplay with the deferred warnings of #669, now merged in: an
RPostgres_errorraised from C++ leaves warnings queued by the failing call in the queue, so they are dropped rather than raised; every entry point that raises deferred warnings clears the queue first, so they never surface in a later call.test-deferred-warnings.Rpasses unchanged. CI: see the checks on the head commit.Open questions are posted as separate comments below. Accepted limitations.
Session: https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc
Generated by Claude Code