Skip to content

fix: Never restart a statement after an error in dbFetch() or dbBind() - #830

Draft
krlmlr wants to merge 28 commits into
claude/fetch-row-aheadfrom
claude/fix-error-mid-result
Draft

krlmlr wants to merge 28 commits into
claude/fetch-row-aheadfrom
claude/fix-error-mid-result

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Found while reviewing #795, where the maintainer asked for a separate pull request from main: two pre-existing bugs in how a result behaves after an SQLite error. Both come from the same SQLite behavior: since 3.7.0, sqlite3_step() on a statement that failed resets it and runs it again from the start instead of returning SQLITE_MISUSE, and RSQLite stepped such a statement again on the next fetch. It is stacked on #850, which, as the maintainer asked here, keeps the rows of a fetch when the step past its last row fails and raises that error from the next fetch.

Error in the middle of a result. When sqlite3_step() failed after some rows had been returned, dbFetch() raised the error, but dbHasCompleted() stayed FALSE and the next dbFetch() restarted the query from the first row. It returned a row of NA followed by the first rows again, or raised the same error again, with dbGetRowCount() growing each time. This affected plain queries, any parameter set of a dbBind() with several sets, and a later parameter set that fails to bind. Now an error ends the execution: dbHasCompleted() returns TRUE, a further dbFetch() returns zero rows with the result's columns, and a new dbBind() makes the result usable again. dbGetRowCount() no longer counts the rows read by a fetch that fails, also not when the conversion to a data frame fails, because they are not returned. The same holds for any other error that leaves a fetch: one raised while converting values, for example an unparsable DATE with extended_types = TRUE or the mixed-type warning under options(warn = 2), a handler that leaves the fetch on a warning, or an interrupt. Before, such an error either repeated on every further fetch, so a while (!dbHasCompleted(res)) loop that caught it never ended, or skipped the rows of that fetch while the result went on. dbFetch(n = 0) and dbColumnInfo() read no row, so an error while converting the row they look at leaves the result as it is. Completing the result also ends the statement, so a result that ends with an error releases its read lock, as it does when it reaches its end. An interrupt during a fetch completes the result too: dbHasCompleted() returns TRUE, dbGetRowCount() does not count the rows of the interrupted fetch, and the next fetch returns zero rows, where main went on after the rows that were lost. An allocation failure in R's own functions still leaves a fetch without completing the result. The warning for a fetch from a statement that is not a query now passes its message as an argument rather than as a format, so its condition call is NULL. A handler of a warning raised during a fetch, bind or dbColumnInfo() can no longer clear or use that result: dbClearResult() and further fetches fail with #795's messages instead of reaching freed memory, which on main could crash R.

Failed dbBind(). When the first parameter set of a list dbBind() failed, either in binding or in the statement, its parameters stayed in place. The next dbFetch() ran them once more, raising the error again, or returned rows from a statement whose bindings were partly cleared. Now a failed dbBind() leaves the result unbound, as it was before the first bind: dbFetch() raises "Query needs to be bound before fetching", which is what a failed Arrow bind in #795 already does. dbHasCompleted() returns FALSE and dbGetRowCount() returns 0; dbGetRowsAffected() reports the changes since the failed bind, for example 2 when the third of four inserts fails, and 0 for a failed query (it stays NA only before the first bind).

Why these semantics. DBI's specification does not cover errors during a fetch. Completing the result follows from dbHasCompleted() returning TRUE "if no more rows are available for fetching" and from fetches past the end returning zero rows; #795 does the same when a later Arrow parameter set fails to bind. The rejected alternative was to keep the error and raise it again on every further dbFetch(): that needs extra state, because SQLite's error message is overwritten by later calls, and it turns while (!dbHasCompleted(res)) loops that handled the error into repeated errors. A failed dbBind() is treated differently because the failing call is the bind itself: asking for a new bind is louder than silently returning zero rows that look like an empty result. With #850 underneath, one error is kept after all: the one from the step past the last row a fetch returns, which the next fetch raises once, so that no row is lost; after that, the result completes as described above.

Merging into #795. A trial merge of this stack into #795 (43db19f) conflicts in two hunks of src/SqliteResultImpl.h and nine of src/SqliteResultImpl.cpp, and passes test-arrow.R, test-dbSendQuery.R and test-read-ahead.R with this resolution: in the header, keep #795's nrows_ and executions_ and add bind_started_ before them, and keep both raise_sqlite_exception(int rc) and raise_kept_error(); in the .cpp file, keep #795's includes and Arrow constants and add <stdexcept> with the step_error class, keep both sides of the constructor (this stack's kept-error fields before #795's Arrow fields), keep #795's bind() and bind_row(), take this stack's "%s" warning and the try/catch loop of fetch_rows() (written as nrows_ = nrows_ + n_fetched for #795's counter), keep #795's arrow_row_read_ = false; in step() before this stack's try/catch and add it at the start of read_ahead(), keep #795's raise_sqlite_exception(rc) in step_run(), and keep #795's Arrow functions while adding raise_kept_error(). Beyond the conflicts: raise_sqlite_exception(int rc) throws step_error for both of its messages, so no R function is called on the step path; raise_kept_error() also completes the result; after_set_params() sets bind_started_, drops a kept error, and wraps bind_row() and after_bind() in a try whose catch resets params_, ready_, complete_ and nrows_ before rethrowing; bind_row() turns a std::runtime_error from the parameter source into a step_error, and SqliteListParamSource::bind_parameter() throws instead of calling cpp11::stop(), so that read_ahead() keeps a later set that fails to bind; step_done() no longer completes the result in its catch; fetch_arrow_rows() starts by raising a kept error, counts its rows only once the chunk is built, and should get the same catch as fetch_rows(), so that an interrupt or a conversion error completes an Arrow result too; and ensure_arrow_columns() reads a row only when the result is neither complete nor keeping an error. Two Arrow tests go with it: an error in the middle of an Arrow result completes it, and an error kept by a data-frame fetch comes from the next Arrow chunk. On the merged build, an interposer counted no R call off R's main thread while five error paths ran on a worker thread. The guard that keeps a running fetch from being cleared is a port of #795's, without its thread and Arrow parts, so in src/DbResult.cpp, src/DbResult.h and src/result.cpp the merge keeps #795's side, which gives files identical to #795's.

With main at 3.54.1. The same holds for the out-of-memory error that #890 raises while a fetch converts a text value: on main, the fetch after it returns a row of NA with dbHasCompleted() still FALSE, and the one after that restarts the query; here the error completes the result. #890's test "a fetch after out of memory does not blame an empty blob" therefore runs out of memory in a dbFetch(n = 0), which leaves the result going, and a new test pins that a fetch that runs out of memory completes the result. Three tests that #868 added to tests/testthat/test-dbBind.R expect dbHasCompleted() TRUE and dbGetRowsAffected() NA after a failed bind and fail here, pending the maintainer's answer on the state after a failed dbBind(), since 3.54.1 shipped #868's state.

The tests are in tests/testthat/test-dbSendQuery.R, with their fixtures in helper files so that every block runs on its own after load_all(); the tests this pull request adds fail on main, among them one for the read lock after an error while converting values a callr test that interrupts a fetch and skips unless its session loads the RSQLite under test, and tests that a warning handler cannot clear the result of a running fetch. Four clean reviews, first, second, third and one of the stack with #850, found no High issue; their Medium and Low findings are fixed up to aa07034, and what remains is listed under Accepted limitations.

Closes #838, which shows both bugs with a reprex against the current CRAN release.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE (merge of 3.54.1: https://claude.ai/code/session_01Hr1rd8MVXyvU7qoMeruD1R)


Generated by Claude Code

…dle of its result

When `sqlite3_step()` failed in the middle of a result, `dbHasCompleted()` stayed `FALSE`.
The next `dbFetch()` stepped the statement again, and SQLite answers that by resetting it and running it from the first row.
After such an error the result is now complete.
`dbHasCompleted()` returns `TRUE`, and a further `dbFetch()` returns zero rows with the result's columns.
This holds for an error in a later parameter set of `dbBind()` as well, including one that fails to bind.
A new `dbBind()` makes the result usable again.
`dbGetRowCount()` no longer counts the rows read by a fetch that fails, because they are not returned.

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

When the first parameter set of a `dbBind()` failed, in binding or in the statement, its parameters stayed in place.
The next `dbFetch()` ran them once more, or went on from a statement whose bindings were partly cleared.
A failed `dbBind()` now leaves the result unbound, as it was before the first bind, and drops the parameters.
`dbFetch()` then raises "Query needs to be bound before fetching", as after a failed Arrow bind in #795.
`dbHasCompleted()` returns `FALSE`, `dbGetRowCount()` returns zero, and `dbGetRowsAffected()` returns `NA`.
`NA` is returned even when earlier parameter sets of a statement changed rows before the failure.
A new `dbBind()` makes the result usable again.

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

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review of this PR at 527c277, by a Claude Code reviewer with clean context that read the description, the diff, src/SqliteResultImpl.cpp in full with its callers (src/DbResult.cpp, R/db_bind.R and the result wrappers), DBI 1.3.0's specification of dbBind(), dbFetch(), dbHasCompleted(), dbGetRowCount(), dbGetRowsAffected() and dbColumnInfo(), and the DBItest 1.8.3 specs that involve failing binds and fetches; ran the four new tests against builds of main and of this PR, devtools::test() (including test-DBItest.R), R CMD check --no-manual, scripted probes on both builds (statements and queries with several parameter sets, dbFetch(n = 0), dbColumnInfo(), dbClearResult() and re-binding after each kind of failure, options(warn = 2), an interrupt during a fetch, SQLITE_BUSY from a second connection, the busy-handler tests), and the merge with #795 as the description proposes in a scratch worktree; and posted nothing itself. Line numbers refer to 527c277. "Confirmed" means reproduced by running code.

Summary. Every claim of the description holds. On main, an error in the middle of a result left dbHasCompleted() FALSE, and the next dbFetch() restarted the query: a loop of while (!dbHasCompleted(res)) try(dbFetch(res, n = 1)) cycled through an NA row, row 1 and the error until I stopped it. A failed dbBind() re-raised its error on the next dbFetch(). With this PR, the error completes the result, later fetches return zero rows with the result's columns, dbGetRowCount() counts only returned rows, a new dbBind() makes the result usable, and a failed first parameter set leaves the result unbound. All four new tests fail on main and pass here. devtools::test() finished with 0 failures and 10398 passing expectations, DBItest included. The only errors were three test-httpvfs.R tests that can't reach their local HTTP server in this sandbox (the same on main), and "interrupt in busy handler", which needs the package installed in the default library and passes once it is. R CMD check --no-manual gives Status: OK.

Checked without a finding:

  • Default path. Without an error nothing changes: fetch_rows() counts the same rows, and the try blocks don't alter control flow.
  • catch (...) and cpp11. Every error raised under step() today goes through cpp11's unwind protection: cpp11::stop() for SQLite and bind errors, and cpp11::function for an R busy handler. It arrives as cpp11::unwind_exception, and throw; rethrows the same object to END_CPP11, which calls R_ContinueUnwind(). The handlers only assign members. params_ = cpp11::list() only releases a cell of the preserve list and allocates nothing, so it can't raise a nested R error. A raw R longjmp would bypass the handler and leave the state as on main, but there is none in that call tree. "error in busy handler" and "interrupt in busy handler" pass against this build.
  • Read-only calls after an error. dbFetch(n = 0) and dbColumnInfo() after an error mid-result return zero rows with the types seen so far. dbClearResult() and a new dbBind() work after every kind of failure. An error at the first step of a query without parameters still makes dbSendQuery() fail, as before. A query whose first parameter set is empty and whose second fails raises the error from dbBind() and is then unbound, consistent with the description.
  • DBI and DBItest. DBI doesn't specify completion after an error. The unbound state after a failed bind matches its description of a result before the first bind: dbFetch() errors, dbGetRowCount() is 0, dbGetRowsAffected() is NA and dbHasCompleted() is FALSE. DBItest only expects the failing dbBind() call itself to raise an error.

High

None.

Medium

None.

Low

  1. dbGetRowsAffected() no longer reports rows that a failed multi-set statement did write. src/SqliteResultImpl.cpp#L147-L159, #L119-L124. Example: table u (x INTEGER UNIQUE), then res <- dbSendStatement(con, "INSERT INTO u VALUES (?)") and dbBind(res, list(c(1L, 2L, 2L, 3L))), which fails on the third set. Rows 1 and 2 are inserted and committed, since autocommit is on. main returns dbGetRowsAffected(res) as 2, and this PR returns NA. Confirmed. The description says so, and DBI allows NA "if the number of rows affected is not known", but here the number is known, and no test pins either behavior. Suggested fix: accept it explicitly and add a test, or keep a flag that a bind has started, separate from ready_, and have n_rows_affected() return sqlite3_total_changes(conn) - total_changes_start_ once it is set.

  2. Only failures inside the try leave the result unbound. src/SqliteResultImpl.cpp#L126-L145, src/DbResult.cpp#L42-L45, R/db_bind.R#L10-L41. Example: on SELECT id FROM t1 WHERE id >= ?, run dbBind(res, list(1L)) and dbFetch(res, n = 1). Then dbBind(res, list(1L, 2L)) fails with "Query requires 1 params; 2 supplied.", and on a query with two placeholders dbBind(res, list(1:2, 4L)) fails with "Parameter 2 does not have length 2.". In both cases the next dbFetch() returns the remaining rows of the old binding instead of asking for a bind. Confirmed, and the same on main. The description limits its claim to a failing first parameter set, so the claim holds; the new comment "A failed bind leaves the result unbound", however, reads as covering every failure. Suggested fix: reword the comment to "Parameters that fail to bind or to execute leave the result unbound", or also reset at the start of DbResult::bind().

  3. Rows from a fetch that fails after the loop still count. src/SqliteResultImpl.cpp#L342-L344. nrows_ += n_fetched runs before data.get_data(types_), which raises the "mixed type" warning. Example: with options(warn = 2) and a column holding 1, 2, 'a', 4, 5, run dbFetch(res, n = 2) and then dbFetch(res, n = 2). The second call errors. dbGetRowCount(res) is then 4, although only two rows were returned, and rows 3 and 4 are lost without the result being complete. Confirmed; the count is the same on main. This contradicts the new comment "Rows count as fetched once they are returned, not if the fetch fails". Suggested fix: cpp11::list out = data.get_data(types_); nrows_ += n_fetched; return out;.

  4. Errors that don't come from step() still repeat in a dbHasCompleted() loop. src/SqliteResultImpl.cpp#L334-L341, src/SqliteColumnDataSource.cpp#L110-L113. Example: extended_types = TRUE, a DATE column whose third value is 'garbage', and options(warn = 2). Then while (!dbHasCompleted(res)) try(dbFetch(res, n = 1)) raises "Unknown string format" on every iteration and never ends. The conversion fails in set_col_values() before the statement advances. Confirmed, and the same on main. The description's argument against loops that repeat their error only covers SQLite errors. An interrupt during a long fetch also leaves the result incomplete and skips the rows read so far, which is reasonable for an interrupt. Suggested fix: out of scope for this PR; say in the description that the change covers errors from SQLite, or open a follow-up.

  5. A SQLITE_BUSY at a parameter-set boundary now ends the result. src/SqliteResultImpl.cpp#L347-L356. Example with two connections to one file, each with a 100 ms busy timeout: con1 binds list(c(1L, 2L)) to SELECT id FROM t WHERE id = ?; con2 runs BEGIN IMMEDIATE and an insert, and its COMMIT fails busy and keeps the pending lock; con1's dbFetch() fails with "database is locked" when it steps into the second set. After con2 commits, retrying dbFetch() on main returned NA and 2; here the result is complete and returns zero rows, so the rows of both sets are lost unless the caller binds again. Confirmed. SQLite documents SQLITE_BUSY as retryable, but main's retry gave a wrong result too, so this isn't a regression. A dbBind() that fails with SQLITE_BUSY can be retried by binding again, and that works. Suggested fix: accept this and document it.

  6. The look-ahead step permanently drops a valid row. src/SqliteResultImpl.cpp#L334-L341, tests/testthat/test-dbSendQuery.R#L203-L207. The new test shows it: row 2 ([2]) is valid but is never returned. dbFetch(res, n = 1) returns row 1 and steps to row 2; the next dbFetch() stores row 2, steps to row 3 and fails. In a dbFetch(res, n = 1) loop, the fetch meant for row 2 raises row 3's error. Confirmed. The look-ahead is old (on main the next fetch restarted instead), but completing the result makes the loss permanent. Suggested fix: accept it, and extend the test comment to say the lost rows include the one read before the failing step.

  7. The tests don't cover statements or the read-only calls after an error. tests/testthat/test-dbSendQuery.R#L189-L279. None of the four tests uses dbSendStatement() or dbExecute() with several sets, checks dbGetRowsAffected() after a failed bind, or calls dbFetch(n = 0) or dbColumnInfo() after an error mid-result. By reading. Suggested fix: add a statement case, such as the UNIQUE example in item 1, and a dbColumnInfo() call after the error in the first test.

Merge with #795

The proposed resolution works. Merging 527c277 into claude/elegant-tesla-mja103 (1449720) conflicts only in src/SqliteResultImpl.cpp, in bind() and step(). Resolved as proposed (kept #795's bind(); in step(), kept arrow_row_read_ = false; before the new try; moved the failure handling into after_set_params() and removed it from bind_arrow(); in fetch_arrow_rows(), replaced ++nrows_ in the loop with nrows_ += n; after it), the tree builds and the whole suite passes (9337 expectations), including test-arrow.R and the four new tests. On the merged build, when dbFetchArrow() fails mid-result, dbHasCompleted() is then TRUE and the next stream has zero rows with the columns; when the first set of a dbBindArrow() fails, dbFetchArrow() asks for a new bind; binding again works after both failures. Confirmed.

The description doesn't say what the catch in after_set_params() must reset. It needs both existing handlers combined: #795's params_.reset(); ready_ = false; is not enough. With only those two lines, "a failed dbBind() asks for a new bind" fails at L264 (dbHasCompleted() is TRUE) and at L273 (dbGetRowCount() is 1). Confirmed. The catch that works resets params_, ready_, complete_ and nrows_ and rethrows.

Outside this PR

raise_sqlite_exception() passes sqlite3_errmsg() to cpp11::stop() as the format string (src/SqliteResultImpl.cpp#L397-L399). So dbGetQuery(con, 'SELECT * FROM "x%d%d%x"') fails with "no such table: x15669257920d8293280", here and on main. Confirmed. #795 already throws std::runtime_error there, so the merge removes this; until then, cpp11::stop("%s", sqlite3_errmsg(conn)) fixes it.


Generated by Claude Code

krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this comment.

The clean review of 527c2775 found no High or Medium issue and seven Low ones. Four are being fixed: dbGetRowsAffected() after a multi-set statement that fails partway, the comment on which bind failures leave the result unbound, rows counted for a fetch that fails on a coercion warning, and tests for statements and for dbFetch(n = 0) and dbColumnInfo() after an error. The format string in raise_sqlite_exception() that it found outside this pull request belongs to the open question on #829. This list will be posted again once the fixes are pushed. These remain:

  • src/SqliteResultImpl.cpp#L334-L341: only errors from sqlite3_step() complete the result; a conversion error in set_col_values(), such as an unparsable DATE under options(warn = 2) with extended_types = TRUE, happens before the statement advances and repeats on every fetch, as on main, so a while (!dbHasCompleted(res)) loop that catches it never ends. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L347-L356: an SQLITE_BUSY from sqlite3_step() now ends the result like any other error, although SQLite documents it as retryable, so the rows of the remaining parameter sets are lost unless the caller binds again; on main the retry returned wrong rows instead. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L334-L341: the fetch loop reads one row ahead, so the error of row k is raised by the fetch that holds row k - 1, and with the result now complete that row is lost for good. Returning it would mean keeping the error for the next fetch, which this pull request rejects. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

…at fails partway

A `dbBind()` whose parameters fail to bind or to execute leaves the result unbound, so that `dbFetch()` asks for a new bind.
`dbGetRowsAffected()` returned `NA` in that state, even when earlier parameter sets of a statement had changed rows.
A flag now records that a bind has started, separately from the readiness to fetch.
`dbGetRowsAffected()` reports the changes since the latest bind, also when it failed partway, and zero for a failed query.
It is still `NA` before the first bind.
The comment on the failure handling now says which failures leave the result unbound.

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

`dbFetch()` added the rows it read to the row count before converting them to a data frame.
When the conversion failed, for example on a "mixed type" warning under `options(warn = 2)`, the rows were counted but not returned.
The count is now updated once the conversion has succeeded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
After an error in the middle of a result, `dbFetch(n = 0)` and `dbColumnInfo()` still return the result's columns, with the types seen so far.
The comment on the lost rows now says that they include the row read before the failing step.

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

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review of the fixes at 88cc2af (the three commits after 527c277), by a Claude Code reviewer with clean context that read the description, the first review, the Accepted limitations, the diff 527c2775..88cc2af9, src/SqliteResultImpl.cpp and src/SqliteResultImpl.h in full with their callers (src/DbResult.cpp, R/db_bind.R), the data frame conversion in src/DbDataFrame.cpp and src/DbColumn.cpp, and DBI 1.3.0's specification of dbBind() and dbGetRowsAffected(); built main (cd1fed9), 527c277 and 88cc2af side by side and ran the new tests and scripted probes against each build (statements and queries whose first, third or later parameter set fails to bind or to execute, binding again, binds that fail before they start, dbClearResult(), statements and queries without parameters, INSERT ... RETURNING, and the "mixed type" warning under options(warn = 2), tryCatch(warning = ) and a calling handler); ran devtools::test() (DBItest included) and R CMD check --no-manual on 88cc2af; merged 88cc2af into #795's claude/elegant-tesla-mja103 at b85c0e7 in a scratch worktree with the resolution from the description, ran the whole suite and Arrow probes there, and rebuilt the merge twice, each time with one step of the resolution reverted; and posted nothing itself. Line numbers refer to 88cc2af. "Confirmed" means reproduced by running code.

Summary. The addressed findings are fixed. In every statement case tried, dbGetRowsAffected() after a failed bind now returns what main returned; a failed query bind gives 0 instead of NA; dbGetRowCount() no longer counts the rows of a fetch whose conversion fails; the reworded comments and the new tests are in place. All six new tests fail on main, and the three expectations these commits add fail on 527c277. No High or Medium issue; four Low findings.

Checked without a finding:

  • bind_started_ on every path (L120-L126, L147-L148), with table u (x INTEGER UNIQUE) and INSERT INTO u VALUES (?): when the third of four sets fails, the count is 2; a first set that fails in the statement or fails to bind gives 0; a later set that fails to bind gives 1; an UPDATE that changes two rows per set and fails on its second set gives 2; a new dbBind() after any of these counts only its own changes. All equal main, except that on a result never bound before, a failed first set gave NA on main and now gives 0, as the description says. Binds that fail before they start ("Query requires 1 params; 2 supplied.", the checks in R/db_bind.R or validate_params()) change nothing. After dbClearResult(), dbGetRowsAffected() raises "Invalid result set"; statements and queries without parameters are unchanged. For queries, NA remains only before the first bind, and any bind, failed or not, gives 0 (or 2 for an INSERT ... RETURNING that wrote two rows), so a query result never returns NA after a bind, as DBI requires.
  • Moving nrows_ += after get_data() (L348-L350). When the "mixed type" warning stays a warning, the count is unchanged; when it becomes an error, through options(warn = 2) or tryCatch(warning = ), the rows are not counted. The only other observable difference: a calling handler that reads dbGetRowCount() while the warning is signaled sees the count before the chunk.
  • The tests fail without the fixes. All six new tests fail on main; on 527c277 exactly the three new expectations fail (L276, L301, L332).
  • devtools::test() passes 10425 expectations; the only failures are three test-httpvfs.R tests that can't reach their local HTTP server in this sandbox. R CMD check --no-manual gives Status: 1 NOTE (a hidden .git from building in a git worktree).

High

None.

Medium

None.

Low

  1. A fetch whose conversion fails still drops its rows from the middle of the result, and the accepted limitations don't mention it. src/SqliteResultImpl.cpp#L336-L350, test at tests/testthat/test-dbSendQuery.R#L316-L333. The first review's Low 3 said that the rows of such a fetch "are lost without the result being complete"; 6436e9a fixes the count, but the rows are still lost. With a table m (x) holding 1, 2, 'a', 4, 5: dbFetch(res, n = 2) returns 1 and 2; under options(warn = 2) the next dbFetch(res, n = 2) fails with "mixed type"; dbHasCompleted(res) is then FALSE, and the next dbFetch(res) returns only 5. Rows 3 and 4 are never returned, and dbGetRowCount() ends at 3 for a five-row result. Confirmed, and main behaves the same. Suggested fix: widen the first accepted limitation to all errors that don't come from sqlite3_step() (they repeat when set_col_values() fails and skip rows when the conversion in get_data() fails), and pin the behavior at the end of the new test with expect_false(dbHasCompleted(res)) and expect_equal(dbFetch(res)$x, 5L). The alternative, setting complete_ = true when get_data() fails, would also end the result for callers that catch the warning with tryCatch().

  2. The description says "all four fail on main", but there are now six tests. All six fail on main. Confirmed. Suggested fix: write "all six fail on main".

  3. The comment on a failed bind still says "as before the first bind". src/SqliteResultImpl.cpp#L154-L156. Since d928047, dbGetRowsAffected() differs: on a new INSERT INTO u VALUES (?) result the count is NA, and after dbBind(res, list(list("a", as.raw(1)))) fails it is 0. Confirmed. Suggested fix: "Parameters that fail to bind or to execute leave the result unbound: fetching asks for a new bind instead of running them again, while dbGetRowsAffected() counts from this bind".

  4. The resolution for merging into feat: Implement the DBI Arrow interface natively #795 is right, but no test covers its fetch_arrow_rows() step. The "Merging into feat: Implement the DBI Arrow interface natively #795" paragraph, and feat: Implement the DBI Arrow interface natively #795's src/SqliteResultImpl.cpp#L513 and #L553. With only that step reverted (++nrows_ kept in the loop, no nrows_ += n;), test-arrow.R and test-dbSendQuery.R still pass, but after SELECT id, json(v) AS j FROM t1 over [1], [2], [3], oops, [5], [6], a failing dbFetchArrowChunk(res, chunk_size = 5) leaves dbGetRowCount(res) at 2 instead of 0. Confirmed. Suggested fix: add an Arrow counterpart of "an error in the middle of a result completes it" to test-arrow.R with the merge (a dbFetchArrowChunk() whose chunk fails, then checks of dbGetRowCount(), dbHasCompleted() and an empty next chunk), mention it in the paragraph, and carry feat: Implement the DBI Arrow interface natively #795's comment on why the stream is not kept (#L317-L319) along when the catch moves to after_set_params().

Merge with #795

The paragraph is accurate. Merging 88cc2af into b85c0e7 conflicts exactly where the description says (bind() and step() of src/SqliteResultImpl.cpp, the state block of src/SqliteResultImpl.h); the constructor, n_rows_affected() and fetch_rows() merge cleanly. With the resolution as written, the tree builds and devtools::test() passes 9374 expectations, including test-arrow.R and the six new tests. On the merged build, a dbFetchArrowChunk() or dbFetchArrow() that fails mid-result completes the result and counts only the chunks returned, the next chunk has zero rows and keeps the columns, a dbBindArrow() whose first set fails asks for a new bind with dbGetRowsAffected() at 0 (2 when the third of four inserts fails), and a list dbBind() that fails after an Arrow chunk leaves the result unbound with a row count of 0. With only #795's params_.reset(); ready_ = false; in the catch, "a failed dbBind() asks for a new bind" fails at L274 and L284, as the description says. All confirmed.


Generated by Claude Code

krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this comment.

The first clean review found seven Low issues; four are fixed up to 88cc2af, which the second clean review confirmed without High or Medium findings. Its comment wording and a test pinning the skipped rows are added in 7ab048b and 24bfbed, and the Arrow test it asks for belongs to the merge into #795, as the description says. The format string in raise_sqlite_exception() belongs to the open question on #829. These remain:

  • src/SqliteResultImpl.cpp#L336-L350: only errors from sqlite3_step() complete the result. An error raised while converting values does not, as on main: when set_col_values() fails before the statement advances (an unparsable DATE under options(warn = 2) with extended_types = TRUE), every further fetch raises it again, so a while (!dbHasCompleted(res)) loop that catches it never ends; when the conversion in get_data() fails after the statement advanced (the "mixed type" warning under options(warn = 2)), the rows of that fetch are skipped and the result continues, so such a loop gets a gap (rows 3 and 4 of 1, 2, 'a', 4, 5 are never returned). Completing the result there would also end it for callers that catch the warning with tryCatch(). Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L347-L356: an SQLITE_BUSY from sqlite3_step() now ends the result like any other error, although SQLite documents it as retryable, so the rows of the remaining parameter sets are lost unless the caller binds again; on main the retry returned wrong rows instead. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L334-L341: the fetch loop reads one row ahead, so the error of row k is raised by the fetch that holds row k - 1, and with the result now complete that row is lost for good. Returning it would mean keeping the error for the next fetch, which this pull request rejects. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

A fetch that fails on its conversion to a data frame, such as a "mixed type" warning under `options(warn = 2)`, leaves the result incomplete.
The next fetch goes on after the rows of the failed fetch, which are skipped.
The test now states this accepted limitation, so that a change to it shows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The comment on a failed bind said that it leaves the result unbound as before the first bind.
Since `dbGetRowsAffected()` now counts the changes from that bind, the comment says so instead.

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

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

File an issue that describes the underlying problem with a reprex.

Comment thread tests/testthat/test-dbSendQuery.R Resolved
@krlmlr

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Re SQLITE_BUSY : Create another issue with a reprex to show relevance.

Re row k - 1 : Accuracy is important. Do we still need to fetch one row ahead? If yes, perhaps implement a transparent one-row cache in a fresh PR against main and stack this PR on top?

Fix first limitation here.

`load_all()` sources `tests/testthat/helper*.R` but not the top level of a test file.
`json_error_setup()` moves to `helper-json-error.R`, and `bind_select_setup()`, which predates this branch, to `helper-bind-select.R`.
Every `test_that()` block of `test-dbSendQuery.R` now runs on its own after `load_all()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
Stacks this branch on the one-row cache of `claude/fetch-row-ahead`, which is based on `main` 3b7bea3:
a fetch returns its rows when the step past its last row fails, and the next fetch raises the error.
Raising that kept error now completes the result, as an error of any other step does, so the row before the failing one is no longer lost.
`bind()` drops the kept error before its `try`, and `step()` completes the result when it raises the `step_error` that a failed step now throws.
The tests of the cache also check that the result is complete once the error is raised.
The tests of `test-dbSendQuery.R` see no change, because each of their errors comes from a step among the rows the failing fetch asks for.

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

Only an error of a step completed the result.
An error raised while converting values, for example a warning made an error by `options(warn = 2)` or a handler that leaves `dbFetch()` on a warning, left the result going on.
When the conversion failed before the statement moved on, as for a value of a `DATE` column that is not a date with `extended_types = TRUE`, every further fetch raised the same error, so a `while (!dbHasCompleted(res))` loop that handled it never ended.
When it failed after the statement moved on, as for the warning on mixed types, the rows of that fetch were skipped and the result went on after them.
Now any error that leaves `dbFetch()` completes the result, as an error of a step does, an interrupt included.
`dbHasCompleted()` then returns `TRUE`, further fetches return zero rows, and `dbGetRowCount()` doesn't count the rows the failing fetch read.
An error kept from the step past those rows is dropped with them.
`dbFetch(n = 0)` and `dbColumnInfo()` read no row, so an error while converting the row they look at leaves the result as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
@krlmlr
krlmlr changed the base branch from main to claude/fetch-row-ahead November 11, 2026 16:01
@krlmlr
krlmlr added this pull request to stack #851 November 11, 2026 16:01

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Thanks; all three are done, as of 1b77244.

SQLITE_BUSY: filed as #848, with a reprex against the CRAN release. It is relevant with RSQLite's defaults: in autocommit mode each parameter set of a dbBind() is its own transaction, so when another process waits to commit with a busy timeout, the step that starts the next set fails with "database is locked". A retry on CRAN and main returns NA in place of the row read ahead, and with this pull request the result ends and the remaining sets are lost. In a stress loop, 231 of 1,145 "database is locked" errors came at a later parameter set rather than the first step. #848 proposes treating it as retryable.

Row k - 1: yes, the fetch loop still needs to read one row ahead, though DBI does not require it: a version that steps lazily passes DBItest unchanged. Reading ahead keeps dbHasCompleted() TRUE right after the fetch that returns the last row, and, more importantly, the step that reaches the end finishes the statement and releases its read lock; without it, a reader that fetched exactly all its rows blocks writers from other connections until the next fetch or dbClearResult(). So #850, a fresh pull request against main, keeps the read-ahead and caches its outcome: when the step past the last row of a fetch fails, that fetch returns all its rows, and the next fetch raises the error. This pull request is now stacked on #850, and once that error is raised, the result completes. An error among the rows a fetch asks for is still raised by that fetch, since dbGetQuery() fetches everything at once and holding that error back would silently return a result cut short.

First limitation: any error that leaves a fetch now completes the result, also one raised while converting values (the unparsable DATE and the mixed-type warning under options(warn = 2)), by a handler that leaves the fetch, or by an interrupt (src/SqliteResultImpl.cpp#L379-L388). A while (!dbHasCompleted(res)) loop that catches the error now ends, and no fetch skips rows while the result goes on. The rows that the failing fetch read are not counted. I looked at keeping them for the next fetch instead, but for the DATE case the next fetch would raise the same warning again unless it turned the value into NA silently, hiding the warning the user chose to make an error.

A clean review of #850 and of these new commits is running. CI note: the smoke test on e19e30f failed before any R code ran, because the runners could not resolve the Ubuntu package mirrors (see #832); the jobs will be re-run once they resolve again.


Generated by Claude Code

krlmlr commented Nov 11, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this comment.

The first clean review and the second found no High or Medium issue. Of the limitations accepted after them, the first, an error while converting values, is fixed in 1b77244, and the row k - 1 that a failing read-ahead lost is returned since this pull request is stacked on #850. A third clean review, of #850 and of the commits since 7ab048b, is running; this list follows its findings. These remain:

  • src/SqliteResultImpl.cpp#L395-L404: an SQLITE_BUSY from sqlite3_step() ends the result like any other error, although SQLite documents it as retryable, so the rows of the remaining parameter sets are lost unless the caller binds again; on main the retry returned NA in place of the row read ahead. Tracked with a reprex in A fetch that hits SQLITE_BUSY between parameter sets loses or corrupts rows on retry #848. Relevance: medium; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L412-L418: only the error of the step past the last row a fetch returns is kept for the next fetch; an error among the rows a fetch asks for is raised by that fetch, which then returns none of the rows it read before it. Holding that error back would let dbGetQuery(), which fetches everything at once, return a result cut short without a word. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L379-L388: an error while converting the values of a fetch ends the result and drops the rows of that fetch, also for a caller who catches the warning with tryCatch() and wants to go on. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Review of the changes since 7ab048b, at 1b77244 (the fixture move e19e30f, the merge 5d80c75 with #850 and main, and the fix 1b77244), by a Claude Code reviewer with clean context that read the description, the two earlier reviews, the "Accepted limitations" comment, the maintainer's comment asking to fix the first limitation, issues #838 and #848, the diffs 7ab048b8..1b772443 and 12b103a4..1b772443, src/SqliteResultImpl.cpp in full with the conversion code (DbDataFrame.cpp, DbColumn.cpp, SqliteColumnDataSource.cpp), and #795's head 43db19f where it touches the same code; built this pull request, the merge without the fix, main, #795's head, and an AddressSanitizer and UBSan build; ran the new tests against all of them, the full suite, R CMD check and reproducers; tried a trial merge into #795; and posted nothing itself. Line numbers refer to 1b77244. "Confirmed" means reproduced by running code.

What was run

What holds

  • In the grid, all 126 loops end after exactly one error, as intended, each returning rows in order and each row once: all k - 1 rows when a fetch boundary falls just before row k, otherwise the complete chunks before the failing one; dbGetRowCount() equals the rows returned. On main, 108 of the 126 loops never end (Confirmed).
  • A kept error is raised once, with the original message, and that completes the result; dbFetch(n = 0) and dbColumnInfo() are unaffected; dbBind() and dbClearResult() drop the error; a first parameter set that fails leaves the result unbound. A result restarts its statement from the first row after an SQLite error #838's reprex gives the expected output throughout.
  • The four tests that 1b77244 adds or changes fail on 5d80c75 and pass here, and all nine new tests in test-dbSendQuery.R fail on main (one of them, "a statement that fails partway reports the rows it changed", only through an error that is not its last result, so testthat's summary shows it as passing there). Every block passes on its own after load_all(), and the helpers e19e30f adds define each fixture once.
  • The catch (...) in fetch_rows() only assigns members, clears a string and rethrows, so cpp11's unwind token survives; interrupts from cpp11::check_user_interrupt() and warnings raised through cpp11::warning() arrive there as C++ exceptions, and the conversion cases under options(warn = 2) and with an exiting tryCatch(warning = ) complete the result as the tests say.
  • AddressSanitizer and UBSan are clean on both test files, the grid and the probes, except for the case in Low 3. Default-path timings are unchanged within noise.

High

None.

Medium

1. The merge steps for #795 no longer complete the result on the Arrow path, and the "Merging into #795" paragraph is stale. src/SqliteResultImpl.cpp#L395-L405, #L379-L389. At 7ab048b, step() completed the result for every caller, which is why the paragraph's "in step(), keep arrow_row_read_ = false; and then this PR's try/catch" also fixed the Arrow path, as the second review confirmed on the merged build. Since 1b77244, step() only turns the error into an R error, and only fetch_rows() completes the result. #795's fetch_arrow_rows() calls step() with no catch (#L524); on 43db19f, dbFetchArrowChunk(res, chunk_size = 3) over the six-row fixture returns 1 to 3, then fails with "malformed JSON" and leaves dbHasCompleted() FALSE, and the next chunk restarts the statement and returns NA, 1, 2 (Confirmed); a merge that follows the paragraph keeps this (by reading). The paragraph is also out of date because a trial merge of 1b77244 into 43db19f now conflicts in nine hunks of src/SqliteResultImpl.cpp and two of the header (three and one for 7ab048b), and because the merged step() must not keep the stack's cpp11::stop(), since fetch_arrow_rows() runs on arrow's worker threads (see the review of #850). Suggested fix: set complete_ = true in step() again before raising, as 5d80c75 did, in addition to the catch in fetch_rows(), or give fetch_arrow_rows() the same catch in the merge; rewrite the paragraph against #795's current head, and have the merge add the Arrow test the paragraph already asks for.

Low

1. A result completed by an interrupt or a conversion error keeps its read lock. src/SqliteResultImpl.cpp#L379-L389. Only a failed step ends the statement; the catch just sets complete_. With a file database and a table m (x) holding 1, 2, 'a', 4, 5, after dbFetch(res, n = 2) and another dbFetch(res, n = 2) that fails with "mixed type" under options(warn = 2), dbHasCompleted() is TRUE, yet an INSERT from a second connection with a busy timeout of 0 fails with "database is locked" until dbClearResult(); after a JSON error in the middle of a result, the same insert succeeds (Confirmed). #850's test "a fetch that returns the last row completes the result" makes a point of a complete result holding no lock. Suggested fix: call sqlite3_reset(stmt) in the catch (a later bind resets anyway, and complete_ keeps fetches off the statement), or say in the comment that the lock lasts until dbClearResult().

2. An interrupt now ends the result; the description does not say so and no test covers it. src/SqliteResultImpl.cpp#L379-L389, src/DbDataFrame.cpp#L40. Interrupting dbFetch(res, n = -1) on a 50-million-row query in a callr session: on main, dbHasCompleted() stayed FALSE, dbGetRowCount() was 1460224, and the next fetch went on at 1460225, a silent gap; here, dbHasCompleted() is TRUE, dbGetRowCount() is 0, and the next fetch returns zero rows (Confirmed). Ending the result seems the better of the two, but dbHasCompleted() now reports a result as exhausted when it was not. Suggested fix: state it in the description, and add a callr test like "interrupt in busy handler" in test-dbConnect.R.

3. A calling handler that clears the result during a fetch now reaches freed memory in more cases. src/SqliteResultImpl.cpp#L385, #L391. On the mixed-type table, withCallingHandlers(dbFetch(res, n = 2), warning = function(w) { dbClearResult(res); ... }) under AddressSanitizer: a handler that then calls stop() writes freed memory at L385 (complete_ = true), and one that muffles the warning reads freed memory at L391 (nrows_ += n_fetched) (Confirmed). Neither fails on #850 or main, where nothing touches the result after get_data(); the same handler on a warning from set_col_values() (an unparsable DATE) already reads freed memory in step_run() on #850, which runs the same code as main. #795 refuses dbClearResult() while a fetch runs ("Can't clear a result while one of its fetches or binds is running"), so the merge fixes this. Suggested fix: accept it until #795 lands, or take #795's guard in result_release() now.

4. Two kinds of R error still leave dbFetch() without reaching the catch. src/SqliteResultImpl.cpp#L348, src/SqliteColumnDataSource.cpp#L84-L91, src/DbColumnStorage.cpp#L41. The raw Rf_warning() at L348, made an error by options(warn = 2), longjmps over the C++ frames of fetch_rows(); the result is already complete there, so only the destructors of the data frame are skipped (by reading). An allocation failure in Rf_allocVector() or Rf_mkCharCE() while values are read does the same in the middle of a result: with ulimit -v 1200000 and a query of 20 MB blobs, dbFetch(res, n = 100) fails with "cannot allocate vector of size 19.1 Mb", dbHasCompleted() stays FALSE, and the next fetch goes on after the lost rows (Confirmed). Both are pre-existing, but the new comment "Any error that leaves a fetch ends the execution" overstates what the catch does. Suggested fix: use cpp11::warning() at L348, as #795 does, and wrap the allocations in cpp11::safe[], or narrow the comment to errors raised through cpp11.

5. The description and the "Accepted limitations" comment lag behind the stack and 1b77244. The description does not say that this pull request is stacked on #850, which now returns the row before a failing step when a fetch boundary falls there, with raising a kept error completing the result; "Now an error ends the execution" describes errors of sqlite3_step() only, while since 1b77244 conversion errors, warnings made errors, handlers that leave dbFetch() and interrupts also end the result; "all six fail on main" should be nine, plus the completion checks this pull request adds to #850's test-read-ahead.R; and "Accepted limitations" still lists the first limitation (fixed by 1b77244), the third (fixed by #850) and SQLITE_BUSY (now #848). #848's note that #830 gives zero rows should add that the stack returns row 2 before the error: 1, 2, the error, then zero rows (confirmed with #848's reprex). Suggested fix: update the description and the "Accepted limitations" comment.


Generated by Claude Code

Brings in the fix of `claude/fetch-row-ahead`: a failed step, a kept error and a failed prepare throw a C++ exception that reaches R at cpp11's entry point, the exception keeps SQLite's result code, and an SQLite message with a `%` reaches R intact.
The merge has no conflicts.
As before it, only the catch in `fetch_rows()` completes the result on a failed step; the next commit has `step()` complete it again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`step()` sets the result complete again before its error leaves it, as it did before the merge with `claude/fetch-row-ahead`, in addition to the catch in `fetch_rows()`.
On this branch, the other callers of `step()` are the first step of a result, which destroys it, and `dbBind()`, which leaves the result unbound, so no behavior changes here.
It matters for a caller without such a catch, such as the Arrow fetch of #795, which this keeps from stepping a failed statement again and restarting it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The catch in `fetch_rows()` now resets the statement, so that a result completed by an interrupt, by an error while converting values or by a warning made an error releases its read lock at once, as a result completed by a failed step already did.
Before, a write from another connection failed with "database is locked" until `dbClearResult()`.
The warning that `dbFetch()` gives for a statement that is not a `SELECT` is now raised through `cpp11::warning()`, with its text passed as an argument rather than as the format, so that an error made of it unwinds the C++ frames.
Its condition call is now `NULL` instead of the internal `result_fetch(res@ptr, n = n)`.
The comment of the catch now names the errors that reach it, and says that an R error that longjmps past it, such as a failed allocation in R's API, leaves the result incomplete.

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

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: keep the rows of a fetch that a conversion error or an interrupt ends?

Outcome: superseded by the maintainer's answer on #872 (decision): the fetch still ends with the error, and layer B2 of the rebuilt chain attaches the rows read before it to the condition. Until then, #935 drops them, as recommended here.

An error while converting the values of a fetch, such as the warning about an unparsable DATE with extended_types = TRUE or the mixed-type warning turned into an error by options(warn = 2), or an interrupt, now ends the result and drops the rows of that fetch (src/SqliteResultImpl.cpp#L405-L421). That also holds for a caller who catches the warning with tryCatch() and wants to go on. Keeping the rows for the next fetch would make that fetch raise the same warning again, or turn the value into NA silently and hide the warning the user chose to make an error. An R error that longjmps past these frames, such as a failed allocation in R's API, still leaves the result incomplete, as the code comment there says.

con <- dbConnect(RSQLite::SQLite(), extended_types = TRUE)
dbExecute(con, "CREATE TABLE t (d DATE)")
dbExecute(con, "INSERT INTO t VALUES ('2020-01-01'), ('2020-01-02'), ('oops')")
res <- dbSendQuery(con, "SELECT d FROM t")
options(warn = 2)
try(dbFetch(res))
#> Error : (converted from warning) Unknown string format, NA is returned.
dbHasCompleted(res)
#> [1] TRUE
dbFetch(res)
#> [1] d
#> <0 rows> (or 0-length row.names)
# The two valid dates are not returned; the CRAN release gives FALSE and raises the same error again
  • Accept it: the result ends and the rows of that fetch are dropped, as recorded in the code comment (recommended)
  • Keep the rows of the failed fetch for the next one and convert the failing value to NA there, at the cost of extra state and a warning that does not repeat

If nobody decides, the recommended option holds.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: let a warning handler clear the result that raised the warning?

Outcome: the recommended option is in #934, the busy guard of the rebuilt chain: a handler gets a clear error, and the result can be cleared once the fetch returns.

A handler of a warning raised during a fetch, bind or dbColumnInfo() can no longer clear or use that result (src/result.cpp#L28-L32), and so it can't send a new query on the same connection either, since that clears the open result first. It gets the error "Can't clear a result while one of its fetches or binds is running" instead of the crash that freeing the statement under the running fetch could cause before, also on main. The guard is a port of #795's.

con <- dbConnect(RSQLite::SQLite())
dbExecute(con, "CREATE TABLE u (x)")
dbExecute(con, "INSERT INTO u VALUES (1), ('a')")
res <- dbSendQuery(con, "SELECT x FROM u")
try(withCallingHandlers(
  dbFetch(res),
  warning = function(w) dbClearResult(res)
))
#> Error : Can't clear a result while one of its fetches or binds is running, as from a handler of a warning that it raised.
dbClearResult(res)
  • Accept it: a handler gets a clear error and can clear the result after the fetch returns (recommended)
  • Defer the clearing until the fetch has unwound, so that the handler's call succeeds, at the cost of more state in every result

If nobody decides, the recommended option holds.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the copy of 2026-11-29.

The first clean review and the second found no High or Medium issue. The third found one Medium (the merge steps for #795 no longer completed an Arrow result) and five Low issues, and the review of the stack with #850 one Medium (a handler that clears the result during a fetch crashed R) and four Low ones. All are fixed up to aa07034: dbClearResult() and any other use of a result now refuse while one of its fetches or binds runs, as on #795, so that crash and the one main already had are gone; a result that ends with an error releases its read lock; the callr tests skip unless they load the RSQLite under test. d7d5dcd merges #850 with main. These remain:

  • src/SqliteResultImpl.cpp#L405-L421: an error while converting the values of a fetch, or an interrupt, ends the result and drops the rows of that fetch; see the question. Relevance: low; reviewer's confidence: high. (recorded)
  • src/result.cpp#L28-L32: a handler of a warning raised during a fetch, bind or dbColumnInfo() can't clear or use that result; see the question. Relevance: low; reviewer's confidence: high.

Older behavior that the base branch already shows:


Generated by Claude Code

The local counter of `fetch_rows()` was an `int`,
which a single fetch with `n = -1` could overflow
before `nrows_`, an `int64_t` since #858, takes its value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
The session may now take up to 60 s to start and to stop after the interrupt,
instead of 3 s and 5 s;
both waits still end as soon as the session is ready.
The interrupt is sent only once the session has begun the fetch,
which it signals with a file,
so a slow start no longer lets the interrupt land before the fetch.

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

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

CI is red on 7cceaea because of the five expectations in tests/testthat/test-dbBind.R that came from #868 with the merge of main (8e907fd): #868 expects dbHasCompleted() to be TRUE and dbGetRowsAffected() to be NA after a failed dbBind(), while this pull request deliberately keeps FALSE and a count, as RSQLite on CRAN does. The other three errors, in test-httpvfs.R, happen on main as well (#832, #837). Which state to keep is the question on #880; the fix follows once it is answered, or with the recommended option if nobody decides.


Generated by Claude Code

@krlmlr krlmlr mentioned this pull request Nov 14, 2026
16 of 22 tasks
…mory

The test for an empty blob read again after out of memory, from #890,
ran out of memory in a fetch and fetched the same row again.
A fetch whose conversion fails now completes the result,
so that row is never read again, and the test lost its point.

A fetch of zero rows looks at the next row without reading it,
and running out of memory there leaves the result going on,
so the test now runs out of memory there
and reads the row again in the next fetch, as before.

A new test pins what a fetch that runs out of memory does now:
it raises the error once, completes the result,
and further fetches return zero rows without stepping the statement again.

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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: drop kept_error_completes_, which no longer changes anything here?

Outcome: the recommended option is in #935, the error-ends-fetch layer of the rebuilt chain (573bf59): kept_error_completes_ is gone, since the catch completes the result on every exception.

The clean review of 2026-11-29 rated this Low. #850 keeps the error of the step past a fetch's last row in error_kept_, and kept_error_completes_ records whether raising it should complete the result (src/SqliteResultImpl.cpp#L479, #L526-L530). With this pull request, raise_kept_error() is only called inside the try of fetch_rows(), whose catch (...) completes the result on every exception (#L423-L441), so the flag decides nothing. That catch also clears error_kept_ but not kept_error_completes_, which can stay true after an interrupt or a failed conversion in the fetch that read ahead; bind() resets it (#L196-L197), so nothing observable follows. The reviewer found no behavior that depends on it.

Dropping the flag here removes about six lines and one member that #850 added, with no test change; no layer above this one touches it, so the removal merges up the stack without conflicts in its lines. Resetting it in the catch keeps the state consistent for whoever reads it later.

  • Drop kept_error_completes_ in this pull request and carry the removal up the stack (recommended: dead state invites wrong assumptions)
  • Keep it, and reset it in the catch of fetch_rows() next to error_kept_
  • Accept it as it is

The change was not written in this session, whose harness refused to start an agent for fixes. If nobody decides, it is accepted as is.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: reword the busy guard's error for a handler that sends a new query?

Outcome: the recommended option is in #934, the busy guard of the rebuilt chain (4a46fa6): both refusals name the new query and busy handlers, e.g. "Can't clear a result, or send a query on its connection, while one of its fetches or binds is running, as from a warning or busy handler."

The clean review of 2026-11-29 rated this Low, as a refinement of the question on a handler that clears its result. A warning handler that calls dbGetQuery() or dbExecute() on the same connection during a fetch, for example withCallingHandlers(dbFetch(res), warning = function(w) dbGetQuery(con, "SELECT 1")) on an extended_types DATE column with an unparsable value, now fails with "Can't clear a result while one of its fetches or binds is running, as from a handler of a warning that it raised." (src/result.cpp#L28-L32), because dbSendQuery() first clears the connection's open result. The user never called dbClearResult(), so the message points at the wrong call. On main the same code crashes R, so the behavior itself is the improvement; only the wording is in question.

Naming both causes, for example "Can't clear a result, or send a query on its connection, while one of its fetches or binds is running, as from a handler of a warning that it raised.", is a one-line change and one test expectation. A separate message from dbSendQuery() needs the connection to know that its open result is busy, a few more lines.

  • Name both causes in the one message (recommended: one line, and the user recognizes their call)
  • Give dbSendQuery() on a connection with a busy result its own message
  • Keep the message as it is

The change was not written in this session, whose harness refused to start an agent for fixes. If nobody decides, the message stays as it is.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The first clean review and the second found no High or Medium issue. The third found one Medium (the merge steps for #795 no longer completed an Arrow result) and five Low issues, and the review of the stack with #850 one Medium (a handler that clears the result during a fetch crashed R) and four Low ones. All are fixed up to aa07034: dbClearResult() and any other use of a result now refuse while one of its fetches or binds runs, as on #795, so that crash and the one main already had are gone; a result that ends with an error releases its read lock; the callr tests skip unless they load the RSQLite under test. d7d5dcd merges #850 with main.

The clean review of 2026-11-29, after main (3.54.1) was merged up the stack, read this pull request at dc3ac22 and found nothing above Low here. Two new Lows have their own questions, listed below; the third, a chunked loop that catches an interrupt or a conversion error and then stops because the result is complete, is the case of the first item below. From #830 up, five expectations in test-dbBind.R from #868 fail until the question on the state after a failed dbBind() is answered. This copy replaces the copy of 2026-11-13. These remain:

Older behavior that the base branch already shows:


Generated by Claude Code

The tests from #868 pinned `dbHasCompleted()` as `TRUE`
and `dbGetRowsAffected()` as `NA` after a failed `dbBind()`.
This branch gives one state for every failed bind,
as for an error from the statement:
`dbHasCompleted()` returns `FALSE`,
and `dbGetRowsAffected()` counts the rows changed since that bind,
which is 0 when the first row fails to bind.
`dbFetch()` still asks for a new bind.

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.

A result restarts its statement from the first row after an SQLite error

2 participants