Skip to content

feat: Expose the PostgreSQL SQLSTATE and diagnostic fields on errors - #666

Merged
krlmlr merged 13 commits into
mainfrom
claude/sqlstate-conditions
Nov 29, 2026
Merged

krlmlr merged 13 commits into
mainfrom
claude/sqlstate-conditions

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Picks up #581 by David Schoch (schochastics) as a PR we own, ported onto the current main. 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 fields sqlstate, detail, hint, position, context, schema, table, column, datatype and constraint (each NULL when libpq has no value). Handlers can dispatch on a code, tryCatch(..., RPostgres_error_23505 = ...), or read cnd$sqlstate, including custom codes from RAISE EXCEPTION ... USING ERRCODE. ?RPostgres-conditions documents this.

The printed message is the failing step and the server's primary text, followed by one i bullet per field that is set. These bullets replace libpq's DETAIL:, HINT: and CONTEXT: lines, so nothing is printed twice; the LINE 1: ... ^ pointer becomes the Position bullet. 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.

> dbExecute(con, "INSERT INTO t VALUES (1, 1)")
Error in `dbSendQuery()`:
! Failed to fetch row : duplicate key value violates unique constraint "t_pkey"
ℹ SQLSTATE: 23505
ℹ Detail: Key (id)=(1) already exists.
ℹ Schema: public
ℹ Table: t
ℹ Constraint: t_pkey

conditionMessage() returns all of these lines. Errors that libpq produces itself, such as a lost connection, have no SQLSTATE: they carry RPostgres_error without a code and keep libpq's text, without bullets.

Covered paths: prepare(), step_run() (send, fetch and bind), and both COPY results in dbAppendTable() / dbWriteTable(), the start of the COPY included. The error names the DBI method that ran the statement; for dbGetQuery() and dbExecute() that is dbSendQuery() or dbBind(), as in duckdb-r. dbConnect() failures, large object import and export, and argument checks stay plain errors.

How the review on #581 is addressed

  • rlang errors: signal_pq_error() raises with rlang::abort(); rlang moves from Suggests to Imports (>= 1.0.0, which abort(body = ) needs). It is no new install: hms already imports it.
  • Snapshot tests: tests/testthat/_snaps/sqlstate.md shows 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 custom RAISE with code, detail and hint, a context over several lines from a function, and an error at fetch time. A separate test pins what conditionMessage() returns. local_edition(3) is not needed, since DESCRIPTION sets edition 3. The tests set lc_messages to C (skipping where the role may not), so the snapshots do not depend on the server's locale.
  • Comparison with duckdb: same shape as duckdb-r. C++ calls an R function from the package namespace that raises a classed condition with the fields, and an R wrapper around the C++ entry point (rethrow(), cf. duckdb's generated rethrow_rapi_*()) puts the DBI call into call. Two differences: duckdb wraps every rapi_* entry point by a generated file and catches every error, rebuilding it with a fresh rlang::abort(); here four entry points are wrapped by hand, only RPostgres_error is caught, and the original condition is re-signalled with its call set, so its fields and backtrace stay as captured. Whether to go all the way to duckdb's scheme is a question below.
  • Why the condition survives R → C++ → R: R looks up handlers when the condition is signalled, while the C++ frames are still on the stack. The calling handler from rethrow() runs first, sets call, and re-signals the same object with stop(), 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 with R_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:
     9. ├─global f()
    10. │ ├─DBI::dbGetQuery(con, "SELECT * FROM nope")
    ...
    15. │       └─RPostgres (local) .local(conn, statement, ...)
    19. │         ├─RPostgres:::rethrow(result_create(conn@ptr, statement, immediate))
    22. │         └─RPostgres:::result_create(conn@ptr, statement, immediate)
    23. └─RPostgres (local) `<fn>`(...)
    
  • pkgdown reference: RPostgres-conditions is listed in _pkgdown.yml; pkgdown::check_pkgdown() finds no problems.

Changes beyond #581

  • The port resolves the conflict with fix: Never pass column names or server messages as a printf format #665: the fallback cpp11::stop() passes the message as a "%s" argument.
  • A failing start of a COPY (unknown column, missing table) now carries its SQLSTATE too.
  • dbAppendTable() and dbWriteTable() errors name the DBI verb instead of the internal db_append_table(); rethrow() finds the call from its caller's frame and skips S4's .local().
  • result_stop() copies the fields and frees the PGresult before 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 base withCallingHandlers(): about 2 µs per dbFetch() instead of about 12 µs with rlang::try_fetch().
  • Tests for COPY, bind, fetch, a terminated backend (class without code), every diagnostic field (with lc_messages set to C), and plain error handlers still catching.

Backward compatibility

tryCatch(error = ), try() and expect_error() still catch these errors. What changes: conditionMessage() of a server error drops the ERROR: label and libpq's DETAIL:/HINT:/CONTEXT:/LINE lines in favor of the bullets (decided in this question), the class no longer includes simpleError, conditionCall() is a DBI call instead of NULL, and printing uses rlang's format.

Not in this PR

No NEWS.md bullet: .github/CONTRIBUTING.md asks 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_error raised 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.R passes 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

schochastics and others added 7 commits November 29, 2026 16:11
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
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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: How far should this PR follow duckdb's rethrow scheme?

rethrow() (R/rethrow.R L22-L30) wraps four C++ entry points by hand (result_create(), result_fetch(), result_bind(), connection_copy_data()) and catches only RPostgres_error, re-signalling the same object with its call set. duckdb-r generates a rethrow_*() wrapper for every rapi_*() entry point and turns every error into a fresh rlang::abort() against the caller, which gives rlang formatting and a DBI call to the remaining plain errors as well ("Query needs to be bound before fetching", "Disconnected", "Lost connection to database" from quoting, and so on).

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 simpleError with no call for now. Kirill decides; if nobody does, the PR stays as it is.

  • Keep this PR to RPostgres_error on the four entry points, and do the duckdb-style wrappers for all entry points in a follow-up PR (recommended)
  • Extend this PR to generated wrappers for all entry points that rethrow every error as an rlang error
  • Keep the current scope and do not plan the follow-up

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: Accept that server errors are no longer simpleError?

Server errors used to be c("simpleError", "error", "condition") with call = NULL. They are now c("RPostgres_error_<SQLSTATE>", "RPostgres_error", "rlang_error", "error", "condition") with the DBI verb as call (R/signal_pq_error.R L68-L92). tryCatch(error = ), try(), expect_error() and conditionMessage() behave as before, and a test checks this. Code that tests inherits(e, "simpleError"), matches the printed output, or relies on conditionCall(e) being NULL would change behavior. I found no such use in the package's own tests; a revdep check would show it in the wild.

Adding "simpleError" to the class vector would keep such code working, but an rlang error that claims to be a simpleError is unusual, and duckdb-r did not do it. Kirill decides; if nobody does, the change stands and goes into the "Accepted limitations" list.

  • Accept the change, and let the release's revdep check show whether anything depends on simpleError (recommended)
  • Add "simpleError" to the class vector for compatibility

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Should dbConnect() failures also raise RPostgres_error?

A failed connection still raises a plain error from the DbConnection constructor (src/DbConnection.cpp L36, pinned). libpq gives no PGresult there, so there would be no SQLSTATE either way; the gain would be a uniform RPostgres_error class and an rlang message naming dbConnect(). The cost is a changed class for an error that many scripts and packages catch, and the message would need a prefix such as "Failed to connect : ...", or result_stop() would need a variant without one. ?RPostgres-conditions says today that these stay ordinary errors.

Kirill decides; if nobody does, connection failures stay plain errors.

  • Leave dbConnect() errors plain in this PR, and fold them into the follow-up for all entry points if that one happens (recommended)
  • Raise RPostgres_error (without sqlstate) for connection failures in this PR, keeping the message text unchanged

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: Accept the <fn> branch in backtraces?

cpp11 calls signal_pq_error() as a function object evaluated in the global environment (src/DbConnection.cpp L352-L354). An rlang backtrace therefore ends with a separate top-level branch RPostgres (local) <fn>(...) instead of a frame under result_create() (example in the PR body). duckdb-r shows the same. The fix would build the call with the symbol signal_pq_error and evaluate it in the namespace through cpp11::safe[Rf_eval], which names the frame RPostgres:::signal_pq_error(); it would still be a separate branch, because .Call() creates no R frame to hang it under.

Kirill decides; if nobody does, the backtrace stays as it is and goes into the "Accepted limitations" list.

  • Accept the <fn> branch; it is cosmetic and matches duckdb-r (recommended)
  • Evaluate the helper by name in the namespace so the branch reads RPostgres:::signal_pq_error()

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the new Accepted limitations comment.

  • R/signal_pq_error.R#L73: server errors are no longer simpleError and carry the DBI verb as call; see the question. Relevance: low to medium, only code that tests for simpleError or a NULL call is affected. Confidence: high.
  • src/DbConnection.cpp#L346: rlang backtraces show the helper as a separate RPostgres (local) <fn>(...) branch; see the question. Relevance: low, cosmetic. Confidence: high.

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Should the error name the verb the user called, or the DBI method that ran the statement?

rethrow() takes the call of the RPostgres method that reached C++ (R/rethrow.R L22-L46). For dbGetQuery() and dbExecute(), DBI's default methods call dbSendQuery() (and dbBind() with params), so the error reads "Error in dbSendQuery()" although the user wrote dbGetQuery(). duckdb-r shows the same. ?RPostgres-conditions now says so, and the snapshot pins dbSendQuery() for dbGetQuery(), so it would need an update if DBI changed its default methods.

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 dbGetQuery() on the user's behalf, which would then name dbplyr's call. Kirill decides; if nobody does, the inner method stays.

  • Keep naming the method that ran the statement, as duckdb-r does (recommended)
  • Walk up to the outermost DBI generic in this PR

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: Accept the handler cost on every dbFetch()?

dbFetch() now wraps result_fetch() in rethrow() (R/dbFetch_PqResult.R L20), which establishes a calling handler on every call. With rlang::try_fetch() the review measured about 9 µs per call (20k fetches of one row: 1.07 s instead of 0.89 s). The handler is now base withCallingHandlers(), about 2 µs per call here, which is small next to a round trip to the server.

Removing the cost entirely would mean signalling without a wrapper and finding the call from inside signal_pq_error(), which runs detached from the caller's frames, so it would have to search sys.calls() for the RPostgres method. Kirill decides; if nobody does, the 2 µs stay.

  • Accept the remaining ~2 µs per dbFetch() (recommended)
  • Drop the wrapper on dbFetch() and find the call by searching the frames from signal_pq_error()

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by #666 (comment).

  • R/signal_pq_error.R#L79: server errors are no longer simpleError and carry a DBI call as call; see the question. Relevance: low to medium, only code that tests for simpleError or a NULL call is affected. Confidence: high.
  • R/rethrow.R#L35: dbGetQuery() and dbExecute() errors name the DBI method that ran the statement, dbSendQuery() or dbBind(), not the verb the user called; see the question. Relevance: low, documented in ?RPostgres-conditions. Confidence: high. (recorded)
  • R/dbFetch_PqResult.R#L20: about 2 µs of handler setup on every dbFetch(); see the question. Relevance: low. Confidence: high (measured).
  • src/DbConnection.cpp#L352: rlang backtraces show the helper as a separate RPostgres (local) <fn>(...) branch; see the question. Relevance: low, cosmetic. Confidence: high.

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 17:20
Comment thread tests/testthat/_snaps/sqlstate.md Outdated
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Is there an easy way to show the sqlstate and other fields in this output by default?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

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. ! Failed to prepare query : ERROR: relation "no_such_table_579" does not exist; the SQLSTATE and the fields are only reachable as cnd$sqlstate, cnd$table and so on (snapshot). rlang makes this easy: signal_pq_error() can pass a body of i bullets to rlang::abort() (or the package can define a cnd_body() method for RPostgres_error), which prints, for example, ℹ SQLSTATE: 42P01 and ℹ Table: no_such_table_579 under the message. The catch is that rlang's conditionMessage() includes the body, so code that matches the full message text would see the extra lines; the first line stays the same. libpq's message already contains DETAIL:, HINT: and CONTEXT: lines where the server sends them, so showing those again as bullets would duplicate them unless the message is cut down to the primary text.

  • Add bullets for the SQLSTATE and the fields libpq does not already print (schema, table, column, datatype, constraint), only where they are set; leave the libpq message as it is (recommended). Small change in R/signal_pq_error.R, snapshots updated.
  • Restructure: message is the server's primary text only, with SQLSTATE, detail, hint, context and the object names all as bullets. Cleaner output, but conditionMessage() changes more for users who match on it.
  • Keep the output as it is; the fields stay available on the condition object.

Kirill decided (#666 (comment)): "Restructure, with tests that show where it matters."


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

  • R/signal_pq_error.R#L79: server errors are no longer simpleError and carry a DBI call as call; see the question. Relevance: low to medium, only code that tests for simpleError or a NULL call is affected. Confidence: high.
  • R/rethrow.R#L35: dbGetQuery() and dbExecute() errors name the DBI method that ran the statement, dbSendQuery() or dbBind(), not the verb the user called; see the question. Relevance: low, documented in ?RPostgres-conditions. Confidence: high. (recorded)
  • R/dbFetch_PqResult.R#L20: about 2 µs of handler setup on every dbFetch(); see the question. Relevance: low. Confidence: high (measured).
  • src/DbConnection.cpp#L352: rlang backtraces show the helper as a separate RPostgres (local) <fn>(...) branch; see the question. Relevance: low, cosmetic. Confidence: high.

https://claude.ai/code/session_01Hr1rd6e5NcxC9GSrNJDokc


Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

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
@krlmlr
krlmlr merged commit d34e76a into main Nov 29, 2026
6 of 7 checks passed
@krlmlr
krlmlr deleted the claude/sqlstate-conditions branch November 29, 2026 18:03
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
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
krlmlr added a commit that referenced this pull request Nov 29, 2026
…#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]>
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

3 participants