Skip to content

feat: Raise SQLite errors as classed rlang conditions with SQLite's result codes - #943

Draft
krlmlr wants to merge 7 commits into
claude/rb-connection-tagfrom
claude/rb-rlang-conditions
Draft

krlmlr wants to merge 7 commits into
claude/rb-connection-tagfrom
claude/rb-rlang-conditions

Conversation

@krlmlr

@krlmlr krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Errors that SQLite reports in dbSendQuery(), dbBind() and dbFetch(), when opening the database in dbConnect(), in sqliteCopyDatabase() and when loading extensions are now rlang conditions of class c("RSQLite_error_<name>", "RSQLite_error", "rlang_error", "error", "condition"), where <name> is SQLite's primary result code in lowercase, such as RSQLite_error_constraint, RSQLite_error_busy or RSQLite_error_cantopen. The condition carries the fields code (primary result code), extended_code (such as 2067 for SQLITE_CONSTRAINT_UNIQUE), code_name (such as "SQLITE_CONSTRAINT") and extended_code_name (such as "SQLITE_CONSTRAINT_UNIQUE", NA for a code RSQLite doesn't know), and its call is the DBI method or the RSQLite function (dbConnect(), sqliteCopyDatabase(), initExtension()), as in RPostgres. Messages are unchanged, so existing expectations keep passing. The only other visible change is that these errors print with the call instead of a bare Error:. Documented in the new ?"RSQLite-conditions" page, NEWS bullet under Features.

Covered: errors when a statement is prepared, when a parameter fails to bind (including a parameter of a type that can't be bound, raised with SQLITE_ERROR as today), when a step fails, the error kept from reading ahead that the next fetch raises, opening a database, each step of the backup in sqliteCopyDatabase(), and sqlite3_load_extension() in initExtension() (also called by dbConnect(default.extensions = TRUE)). Errors from invalid or busy results, value conversion and argument checks stay ordinary errors; the help page lists them. sqliteSetBusyHandler() has no SQLite error to class: sqlite3_busy_handler() and sqlite3_busy_timeout() only fail for a misused handle, which the connection check already rules out.

How: the C++ exception step_error becomes SqliteError (new src/SqliteError.h), which also carries the extended result code; the prepare error and the connection-level errors are thrown as one too. with_sqlite_errors() wraps the bodies of the entry points result_create(), result_bind(), result_fetch(), connection_connect(), connection_copy_database() and extension_load(), catches a SqliteError after the body's C++ frames have unwound and the busy flag is reset, and only then calls the R function signal_sqlite_error() through cpp11::package("RSQLite"). That R error unwinds the remaining frame through cpp11 like any R error from R code, so no longjmp crosses live C++ objects. signal_sqlite_error() raises the condition with stop(rlang::error_cnd(...)) rather than rlang::abort(), so that no backtrace is captured: it would be detached from the user's frames anyway, and capturing it cost about 1.3 ms per error. rethrow() and dbi_call() are taken from RPostgres's R/rethrow.R and set the call; dbi_call() searches the frames from the top of the stack. The deprecated dbGetPreparedQuery() and dbSendPreparedQuery() capture their call before the tryCatch() whose handler binds a second time, so that they name themselves. SQLite has no API for the symbolic name of an extended result code, so R/conditions.R holds a table of the extended codes from the vendored sqlite3.h.

Performance of a caught error, 2000 × tryCatch(dbExecute(con, "INSERT …duplicate…"), error = function(e) NULL): 40 µs per error on the base branch, 3.4 ms with rlang::abort(), 0.2 ms now (0.3 ms instead of 7.9 ms at a call depth of 100). The remaining overhead over the base is mostly conditionMessage() of an rlang_error, which stop() evaluates when the condition is signaled and again when rethrow() signals it with the call. The path without an error is unchanged.

The fix for sqliteCopyDatabase(con, con), which crashed R because sqlite3_backup_init() returned NULL, and for releasing the locks after a failed backup step moved to #942; this PR raises those errors as classed conditions (RSQLite_error_error for the same connection). sqlite3_load_extension(), sqlite3_backup_step() and sqlite3_backup_finish() don't set the error code on the connection, so these errors take their code from the call's return value rather than from sqlite3_extended_errcode(), which could report an earlier error.

Tests: new test-conditions.R checks class and fields for a unique constraint error, a busy database, a syntax error at prepare, a value over the length limit at bind, a parameter of an unbindable type, and the kept read-ahead error, plus conditionCall(), tryCatch(RSQLite_error_constraint = ), and that RSQLite's own argument checks aren't classed. Further tests cover extended_code_name and unknown codes, the call of the deprecated prepared-query functions, dbConnect() on a missing file with SQLITE_RO and on a directory (RSQLite_error_cantopen), sqliteCopyDatabase() into a read-only destination (RSQLite_error_readonly), the class of the same-connection error in #942's test, initExtension() with a library that can't be loaded, and a failed extension load after an unrelated error, which reported that error's extended code (SQLITE_ERROR_MISSING_COLLSEQ) before. Full suite with NOT_CRAN=true: FAIL 0, WARN 3 (locale), SKIP 63, PASS 11138. R CMD check --no-manual on the built tarball: Status OK.

Layer R0 of the rebuilt chain, planned in #880 (asked for in #880 (comment)); based on #942. It is the base for B2 (#872), which will attach the rows read before an error to this condition. New in the rebuilt chain, not ported from an old PR.

Coordinating session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4


Generated by Claude Code

…esult codes

Errors from SQLite in dbSendQuery(), dbBind() and dbFetch()
are raised by the new signal_sqlite_error() with rlang::abort(),
with the classes "RSQLite_error" and "RSQLite_error_<name>" for the primary result code,
and the fields code, extended_code and code_name.
The messages are unchanged.

The C++ exception step_error becomes SqliteError in SqliteError.h,
which also carries the extended result code,
and the prepare error is thrown as one too.
with_sqlite_errors() at the entry points result_create(), result_bind() and result_fetch()
catches it after the C++ frames of the body have unwound
and calls signal_sqlite_error() through cpp11,
so that no R error jumps over live C++ objects.
rethrow(), as in RPostgres, sets the call of the condition to the DBI method.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
@krlmlr
krlmlr added this pull request to stack #928 December 1, 2026 01:29

krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member Author

Question: should SQLite's extended result codes get condition subclasses too?

This pull request classes an SQLite error by its primary result code, RSQLite_error_<code> such as RSQLite_error_constraint, and puts the extended code in the field extended_code (2067 for a UNIQUE violation) next to code and code_name ("SQLITE_CONSTRAINT"). A handler that only wants UNIQUE violations compares cnd$extended_code == 2067L. RPostgres subclasses by SQLSTATE, which is already as fine-grained as SQLite's extended codes.

  • Keep the primary-code subclass and add a field extended_code_name ("SQLITE_CONSTRAINT_UNIQUE"), so that handlers can compare names instead of numbers (recommended: a few lines, no change to the class vector)
  • Also add the extended subclass to the class vector, e.g. c("RSQLite_error_constraint_unique", "RSQLite_error_constraint", "RSQLite_error", …)
  • Keep it as it is

Implemented on 2026-12-01: the recommended option is in 2f8f761; no box is ticked, and ticking another option changes it.

If nobody decides, the recommended option goes in with the fixes of this pull request's review.


Generated by Claude Code

krlmlr commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

Question: which call should an SQLite error report, the method that hit it or the verb the user called?

conditionCall() of an RSQLite_error is the DBI method that hit the error: dbSendQuery(), dbBind() or dbFetch(). Through dbExecute() or dbGetQuery(), users therefore see dbSendQuery(), or dbBind() when params are given, rather than the call they wrote. RPostgres does the same; reporting the outermost verb needs a rethrow() in each of the convenience methods and a way to tell nested DBI calls apart.

  • Keep the method that hit the error, as RPostgres does (recommended: consistent across r-dbi backends, and the call names the step that failed)
  • Report the verb the user called, e.g. dbGetQuery(), in RSQLite (and later in RPostgres for consistency)

If nobody decides, it stays as it is.


Generated by Claude Code

krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member Author

Question: should connection-level SQLite errors be classed as well?

This pull request classes the errors of statements: prepare, bind, step and the error kept from reading ahead. Errors that SQLite reports outside a statement stay ordinary errors: opening a database in dbConnect(), the backup in sqliteCopyDatabase(), and loading extensions. A handler for RSQLite_error_cantopen therefore never sees a file that can't be opened.

  • Class them in this pull request too, with the same fields, so that every error that comes from SQLite is an RSQLite_error (recommended: one consistent rule, a few more call sites)
  • Class them in a later layer
  • Leave them as ordinary errors

Implemented on 2026-12-01: the recommended option is in 2f8f761; no box is ticked, and ticking another option changes it.

If nobody decides, the recommended option goes in with the fixes of this pull request's review.


Generated by Claude Code

claude and others added 2 commits December 1, 2026 01:48
SQLite errors are now raised with `stop()` on a condition from `rlang::error_cnd()`
instead of `rlang::abort()`, which captured a useless backtrace on every error;
a caught constraint error takes about 0.2 ms instead of 3.4 ms.
`dbi_call()` searches the frames from the top of the stack.

The conditions gain the field `extended_code_name`, such as `"SQLITE_CONSTRAINT_UNIQUE"`,
from a table of the extended result codes in sqlite3.h.

Opening the database in `dbConnect()`, `sqliteCopyDatabase()` and loading extensions
raise `RSQLite_error` conditions with unchanged messages
and name `dbConnect()`, `sqliteCopyDatabase()` or `initExtension()` as their call.
`sqliteCopyDatabase()` fails with SQLite's error instead of crashing R when the copy can't start,
and releases the copy when it fails.

The deprecated `dbGetPreparedQuery()` and `dbSendPreparedQuery()` name themselves
in SQLite errors from their second bind, which runs in a handler.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
…value

`sqlite3_load_extension()`, `sqlite3_backup_step()` and `sqlite3_backup_finish()`
don't set the error code on the connection the error was built from,
whose extended code could be left over from an earlier error,
such as `SQLITE_ERROR_MISSING_COLLSEQ` for a failed load.
The conditions now carry the code these calls return.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4

This branch has not been deployed

No deployments
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.

2 participants