Skip to content

feat: expose PostgreSQL SQLSTATE and diagnostic fields on errors - #581

Closed
schochastics wants to merge 4 commits into
r-dbi:mainfrom
schochastics:feature/sqlstate-conditions
Closed

schochastics wants to merge 4 commits into
r-dbi:mainfrom
schochastics:feature/sqlstate-conditions

Conversation

@schochastics

Copy link
Copy Markdown
Contributor

fix #579

When a server-side error occurs, RPostgres currently surfaces only libpq's error message string and discards the SQLSTATE code and the other diagnostic fields, which forces users to regex-match localized message text to classify errors.

This PR captures those fields from the failing PGresult and raises a classed R condition that carries them: the condition gains the class vector c("RPostgres_error_<SQLSTATE>", "RPostgres_error", "error", "condition") and fields sqlstate, hint, detail, context, table, column, datatype, constraint, and schema (each NULL when libpq doesn't supply it).

Users can now dispatch on a specific code (tryCatch(..., RPostgres_error_FS002 = ...)) or read cnd$sqlstate directly, including for custom codes set via RAISE EXCEPTION ... USING ERRCODE. The original error message is preserved unchanged, and all errors—including connection-level ones with no result—gain the RPostgres_error parent class for uniform handling.

The condition is built in a small internal R helper invoked from C++; error sites that have a PGresult (step_run, prepare, and the COPY completion check) now route through it, while result-less paths keep their existing behavior aside from the new parent class. Includes tests covering undefined-table (42P01), syntax (42601), custom ERRCODE (FS002), and unique-violation (23505) cases.

schochastics and others added 3 commits June 9, 2026 21:42
…stic fields

Errors raised by libpq now signal structured R conditions (class `pq_error`) carrying the SQLSTATE code and other diagnostic fields (hint, detail, constraint, schema, etc.), enabling programmatic error handling via `tryCatch`/`withCallingHandlers`.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

@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.

Thanks.

  • Could we also throw rlang errors with this approach?
  • I'd like to include snapshot tests, needs local_edition(3) perhaps
  • The approach differs from what duckdb is doing. I don't remember how I landed on the duckdb approach, perhaps just because I wanted rlang errors everywhere. I'm curious how and why this even works: R -> C++ -> R -> throwing and the resulting object survives. What does the captured call stack look like?

@krlmlr

krlmlr commented Jun 10, 2026

Copy link
Copy Markdown
Member

@schochastics

Copy link
Copy Markdown
Contributor Author

Ah sorry, missed the part about the rlang errors. I have another look

…ntext

Server/result errors are now raised with rlang::abort() (via signal_pq_error),
so they are nicely formatted rlang conditions while keeping the
RPostgres_error_<SQLSTATE> / RPostgres_error classes and the libpq diagnostic
fields.

Because cpp11 evaluates the R error helper in the global environment, the
condition is created detached from the R call stack and its call is empty. A
small rethrow() layer (R/rethrow.R) wraps the four cpp11 entry points that can
raise these errors (result_create, result_fetch, result_bind,
connection_copy_data) and re-attaches the user-facing call, skipping the S4
.local dispatch wrapper. This mirrors duckdb-r's rethrow approach.

- Move rlang from Suggests to Imports.
- Index RPostgres-conditions in _pkgdown.yml so the docs build.
- Add snapshot tests (edition 3) plus rlang-class and calling-context checks.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@krlmlr

krlmlr commented Jun 10, 2026

Copy link
Copy Markdown
Member

Red CI/CD.

@schochastics

Copy link
Copy Markdown
Contributor Author

Claude says:
The remaining red checks are pre-existing CI issues, not from this PR — everything this PR touches is green

The two failing job types are unrelated to these changes:

  1. All windows-latest jobs die in after-install:

    ankane/setup-postgres@v1/index.js:136
        throw `Postgres version not supported on Windows: ${postgresVersion}`;
    Postgres version not supported on Windows: 17
    

    after-install/action.yml defaults to pg-version 17, which ankane/setup-postgres@v1 can't install on Windows, so Postgres never starts and the job aborts before the build/tests.

  2. ubuntu-24.04 (devel) errors on NOTEs (devel uses error-on: "note"), and there are two long-standing ones: Non-standard file/directory found at top level: 'configure.log' (left by the package's own configure script) and checking compilation flags in Makevars.

@krlmlr

krlmlr commented Jun 10, 2026

Copy link
Copy Markdown
Member

Yes, of course. Apologies, thanks for checking.

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member

Thanks, now in #666.

@krlmlr krlmlr closed this Nov 29, 2026
krlmlr added a commit that referenced this pull request Nov 29, 2026
…666)

* feat: Expose the PostgreSQL SQLSTATE and diagnostic fields on errors

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

* fix: Carry the SQLSTATE when a COPY fails to start

`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

* fix: Name the DBI verb in errors from `dbAppendTable()` and `dbWriteTable()`

`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

* docs: Describe which errors carry the SQLSTATE

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

* test: Cover the COPY, bind, fetch and lost-connection paths

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

* test: Wait for the terminated backend before using its connection

`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

* fix: Release the failing result before allocating the R condition

`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

* fix: Keep libpq's own messages in the native encoding

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

* perf: Rethrow with base `withCallingHandlers()`

`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

* docs: Name the internal DBI calls and the errors without the class

`?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

* feat: Print the server's primary message with the diagnostic fields as 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

---------

Co-authored-by: David Schoch <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

Expose SQLSTATE (and other diagnostic fields) on error conditions

2 participants