Skip to content

fix: dbBind() fails when SQLite refuses to bind a value - #868

Merged
krlmlr merged 3 commits into
mainfrom
claude/bind-return-codes
Nov 13, 2026
Merged

krlmlr merged 3 commits into
mainfrom
claude/bind-return-codes

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Decided in #829 (comment).

On main, the data-frame path of dbBind() ignores the return codes of sqlite3_bind_text(), sqlite3_bind_blob() and the other sqlite3_bind_*() calls in SqliteResultImpl::bind_parameter_pos(). A text or blob value over SQLite's length limit (SQLITE_LIMIT_LENGTH, 2147483647 bytes by default, lower if a connection sets it) is therefore bound as NULL without an error, and the row is written with NULL in its place. With RSQLite's build settings, the default limit (SQLITE_MAX_LENGTH=2147483647) equals R's maximum string length, so a value from R cannot exceed it; the check guards connections that lower the limit, and allocation failures (SQLITE_NOMEM).

This pull request checks the return code of every sqlite3_bind_*() call of that path. A refused value fails with SQLite's message, naming the parameter by position, by name for a named placeholder, and the row of the parameters, for example Can't bind parameter 2 (:x) in row 2: string or blob too big. The message is passed through a fixed format string. dbBind() now treats the result as unbound and completed until its first row is bound, so when the first row fails, a following dbFetch() errors as for an unbound result instead of returning zero rows, and dbGetRowCount() no longer reports the previous binding's count. When a later row of the parameters fails, the result is marked complete, so no fetch reads the reset statement; the rows before it have already been executed, and rows already fetched in the same dbFetch() call are discarded with the error, as for an error from sqlite3_step() in a later row on main. In both cases a following dbBind() with valid values binds afresh, and dbClearResult() works as before.

#866 and #867 do the same on the Arrow path of dbBindArrow(), with similar wording.

For the tests, a new unexported entry point connection_limit_length() sets SQLITE_LIMIT_LENGTH on a connection and returns the previous limit; it has the same signature as the one in the Arrow stack, so the two converge. SQLite does not go below 30 bytes, so the tests use that limit.

Left out: raise_sqlite_exception() still passes sqlite3_errmsg() as the format string of cpp11::stop(); that is fixed separately rather than here, to keep this change to the bind path. The other errors raised by bind_parameter_pos() (an unsupported parameter type) keep their message; in the first row they now leave the same completed, unbound result as a refused value, while in a later row they still do not mark the result complete.

Tested with the new tests/testthat/test-dbBind.R: text and blob values one byte over the limit fail, values at the limit bind and round-trip, a named parameter in a later row is named in the message, the result is complete after the failure and can be re-bound, a query bound and fetched before errors on dbFetch() after a failed re-bind, reports a row count of 0, dbHasCompleted() TRUE and dbGetRowsAffected() NA, a statement reports dbGetRowsAffected() NA after a failed re-bind, an unsupported parameter type leaves a completed, unbound result, dbClearResult() succeeds after a failed bind, and dbExecute() with an over-long value fails and inserts nothing. devtools::test() with NOT_CRAN=true, DBItest included, passes except the three known test-httpvfs.R errors (#832, #837); the busy-handler test in test-dbConnect.R runs against an installed build.

https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn


Generated by Claude Code

The data-frame path of `dbBind()` ignored the return codes
of `sqlite3_bind_text()`, `sqlite3_bind_blob()` and the other `sqlite3_bind_*()` calls,
so a text or blob value over SQLite's length limit was bound as NULL without an error.
Every return code is now checked,
and a refused value fails with SQLite's message,
naming the parameter and the row of the parameters.
The failure marks the result complete,
so that no fetch reads the reset statement and a following `dbBind()` starts afresh.

The internal `connection_limit_length()` lowers `SQLITE_LIMIT_LENGTH` for the tests.

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

Review of this pull request at ddd58b0, by a Claude Code reviewer with clean context that read the description, the full diff against main at 3b7bea3, the surrounding code of SqliteResultImpl (bind(), bind_row(), fetch_rows(), step_done()) and the R side (db_bind(), dbAppendTable()), built the pull request and its base into separate libraries, ran the new tests on both, the full test suite, its own reproducers and valgrind, and posted nothing on GitHub itself.

What was run

  • R CMD INSTALL of the head and of the base, each into its own library.
  • tests/testthat/test-dbBind.R, each of its five test_that() blocks on its own after pkgload::load_all(): all pass on the head. On main, with only the connection_limit_length() hook added so that the tests can run, all five fail.
  • devtools::test() with NOT_CRAN=true (DBItest included): only the three known test-httpvfs.R errors (test: Run the HTTP VFS tests for real, and make their errors fail the check #832, testthat hides a test's error when the test records another result after it #837). The busy-handler test passes when the head's library is on R_LIBS.
  • Reproducers for every risk named in the brief, on both builds. The new tests and the reproducers also ran under valgrind: 0 errors.
  • cpp11::cpp_register(): it leaves R/cpp11.R and src/cpp11.cpp unchanged.
  • A benchmark of dbAppendTable() with 1e6 rows and three columns: 0.37 to 0.39 s on both builds, no measurable difference.

What holds

  • Every sqlite3_bind_*() call in bind_parameter_pos() now assigns rc, and one check after the branches covers them all; there are no other bind calls in the data-frame path.
  • The message goes through a fixed format string. A Tcl-style placeholder $a(%s%n%x) comes out literally as Can't bind parameter 1 ($a(%s%n%x)) in row 1: …, without a crash and with no valgrind error. Numbered placeholders get their names too (parameter 2 (?2)).
  • SQLite sets the connection's error for SQLITE_TOOBIG, SQLITE_RANGE, SQLITE_MISUSE and SQLITE_NOMEM alike, so sqlite3_errmsg() gives the right text for each. SQLITE_RANGE cannot occur here because bind() checks the parameter count, and SQLITE_MISUSE cannot occur because bind_row() resets the statement first (by reading).
  • If the first row of a fresh result fails, dbFetch() errors with "needs to be bound". A later row that fails marks the result complete, dbGetRowsAffected() counts the rows already executed, and a re-bind works. dbClearResult() works after a failure.
  • dbAppendTable() and dbWriteTable(append = TRUE) fail and leave the table unchanged, both outside and inside a transaction (the savepoint rolls back, and the outer transaction stays open). dbExecute() with several rows outside a transaction keeps the rows before the failing one, as the description states.
  • connection_limit_length() is unexported and needs :::. A negative value or NA reads the limit without changing it, and a disconnected connection errors cleanly. No src/*.dd file changes.

High

None.

Medium

  1. A result that was bound before keeps ready_ when the first row of a new dbBind() fails, so a later dbFetch() silently returns zero rows instead of erroring.
    void SqliteResultImpl::bind(const cpp11::list& params) {
    if (cache.nparams_ == 0) {
    cpp11::stop("Query does not require parameters.");
    }
    if (params.size() != cache.nparams_) {
    cpp11::stop(
    "Query requires %i params; %i supplied.",
    cache.nparams_,
    params.size()
    );
    }
    set_params(params);
    SEXP first_col = cpp11::as_sexp(params[0]);
    groups_ = Rf_length(first_col);
    group_ = 0;
    total_changes_start_ = sqlite3_total_changes(conn);
    bool has_params = bind_row();
    after_bind(has_params);
    (Confirmed) With the limit at 30 bytes: dbBind(res, list("ok")); dbFetch(res), then dbBind(res, list(strrep("a", 31))) errors. After that, dbFetch(res) returns a 0-row data frame, dbHasCompleted() is TRUE and dbGetRowCount() still reports 1 from the earlier binding. A fresh result in the same situation errors with "Query needs to be bound before fetching". Code that catches the bind error and goes on to fetch gets a plausible empty answer for a query that never ran. This comes from the new complete_ = true, because bind() never clears ready_. On main, a dbBind() with the wrong number of parameters already leaves the old binding's remaining rows fetchable, so the state handling was loose before this change, but this pull request adds a new case. Suggested fix: set ready_ = false (and nrows_ = 0) in bind() after the argument checks and before bind_row(). after_bind() sets it again on success, so failures in later rows keep their current behaviour. Add a test that binds, fetches, re-binds with an over-long value and expects dbFetch() to error.

Low

  1. Rows already fetched in the same dbFetch() call are discarded when a later parameter row fails.

    cpp11::list SqliteResultImpl::fetch_rows(const int n_max, int& n) {
    n = (n_max < 0) ? 100 : n_max;
    SqliteDataFrame data(stmt, cache.names_, n_max, types_, with_alt_types_);
    if (complete_ && data.get_ncols() == 0) {
    Rf_warning(
    "`dbGetQuery()`, `dbSendQuery()` and `dbFetch()` should only be used "
    "with `SELECT` queries. Did you mean `dbExecute()`, `dbSendStatement()` "
    "or `dbGetRowsAffected()`?"
    );
    }
    while (!complete_) {
    data.set_col_values();
    step();
    nrows_++;
    if (!data.advance()) {
    break;
    }
    }
    return data.get_data(types_);
    (Confirmed) dbBind(res, list(c("a", "b", strrep("a", 31)))); dbFetch(res) errors, and the rows for "a" and "b" are not returned. An error from sqlite3_step() in a later row behaves the same way on main, so this is consistent, but the description only says that the earlier rows "have already been executed". Suggested fix: say in the description, and possibly in NEWS, that the rows fetched so far are discarded. No code change is needed.

  2. With RSQLite's build settings, a text value can never exceed the default length limit, so the fix is defensive unless a connection lowers the limit.

    if (value == NA_STRING) {
    rc = sqlite3_bind_null(stmt, j);
    } else {
    rc = sqlite3_bind_text(stmt, j, CHAR(value), -1, SQLITE_TRANSIENT);
    }
    } else if (TYPEOF(value_) == VECSXP) {
    SEXP value = VECTOR_ELT(value_, group_);
    if (TYPEOF(value) == NILSXP) {
    rc = sqlite3_bind_null(stmt, j);
    } else if (TYPEOF(value) == RAWSXP) {
    rc = sqlite3_bind_blob(
    stmt,
    j,
    RAW(value),
    Rf_length(value),
    SQLITE_TRANSIENT
    );
    } else {
    cpp11::stop("Can only bind lists of raw vectors (or NULL)");
    }
    } else {
    cpp11::stop(
    "Don't know how to handle parameter of type %s.",
    (by reading) SQLITE_MAX_LENGTH=2147483647 in src/Makevars equals R's maximum string length, SQLite only refuses lengths above the limit, and Rf_length() on a raw vector longer than that errors before the bind. Users have no public API to lower the limit, so the motivating "bound as NULL" case comes mainly from the test hook (or from SQLITE_NOMEM). The change is still right. Suggested fix: reword the description to say that the default limit is effectively unreachable from R, and that the check guards lowered limits and allocation failures.

  3. Pre-existing and out of scope: the other errors in bind_parameter_pos() still leave a reset statement that the next fetch runs with NULL parameters.

    );
    } else {
    cpp11::stop("Can only bind lists of raw vectors (or NULL)");
    }
    } else {
    cpp11::stop(
    "Don't know how to handle parameter of type %s.",
    Rf_type2char(TYPEOF(value_))
    );
    }
    (Confirmed, same output on main and on the head) dbBind(res, list(list(as.raw(1), "a", as.raw(3)))): the first dbFetch() errors with "Can only bind lists of raw vectors", dbHasCompleted() is FALSE, and the second dbFetch() returns three rows NA, NA, blob, which is a wrong result. The description acknowledges that this case is not covered. Suggested fix, as a follow-up: make these cpp11::stop() calls set complete_ = true too, for example through a variant of raise_bind_exception() that takes a message.


Generated by Claude Code

`bind()` now clears `ready_` and the row count before binding the first row,
so a refused value no longer leaves a result bound and fetched before
reporting zero rows and the old row count.
A fetch after such a failure errors as for an unbound result.

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

Second review round of this pull request, of af501a0, by a Claude Code reviewer with clean context that read the description, git diff ddd58b09 af501a02, the surrounding SqliteResultImpl.cpp (bind(), init(), step_done(), fetch_rows(), raise_bind_exception()), built the commit into a separate library, and ran the tests and reproducers below. It posted nothing on GitHub and changed no branch.

What was run

  • test-dbBind.R after pkgload::load_all(): 19 pass, including the new block.
  • devtools::test() with NOT_CRAN=true (DBItest included): the three known test-httpvfs.R errors, plus the busy-handler test in test-dbConnect.R, which needs an installed build (as the description says); it passes with R_LIBS pointing at the installed build.
  • A reproducer script covering every bind path in the brief: /tmp/claude-0/-home-user-RSQLite/f42b7fc0-2b11-523a-8045-e512d240ea51/scratchpad/r2-repro.R.
  • valgrind on the new test's scenario (bind, fetch, failed bind, fetch error, dbGetRowCount(), dbColumnInfo(), re-bind, fetch, clear): no errors.

What holds

  • First row fails after a fetched result: dbFetch() errors "needs to be bound", dbGetRowCount() is 0, dbGetRowsAffected() is NA, dbHasCompleted() is TRUE, dbColumnInfo() still works, and a re-bind then fetches correctly.
  • A failure on the first bind of a fresh result behaves the same. For a statement from dbSendStatement(), a failed first row reports NA affected rows, and a re-bind then reports the right count (1) and inserts the right rows.
  • A failure in a later row surfaces in dbFetch(), where ready_ is already true and complete_ is set by raise_bind_exception(). Row count and affected rows were as expected. A fetch after it errors, and a re-bind recovers. A failed bind after a partial fetch resets the count to 0.
  • dbBind() with zero rows, after a success or after a failed bind, gives ready_ true, count 0, completed, and an empty frame.
  • The early errors in bind() (wrong parameter count, no parameters) come before the new lines, so they keep the previous state: after a rejected dbBind() with 2 parameters, the count of the earlier fetch stays 1.
  • dbClearResult() works after every case. Nothing else reads nrows_ except n_rows_fetched() and fetch_rows(), and init() already zeroed it on success, so only the failure path sees a changed value.
  • No interrupt check exists inside bind_row(), so an interrupt cannot land between the new lines and init().
  • The diff touches no src/*.dd file, DESCRIPTION, NAMESPACE or docs, so no R CMD check was needed. The description matches the code.

High

None.

Medium

None.

Low

  1. An unsupported parameter type in the first row leaves dbHasCompleted() at its old value on an unbound result. SqliteResultImpl.cpp#L144-L153. cpp11::stop() in bind_parameter_pos() does not go through raise_bind_exception(), so complete_ keeps its previous value. After dbBind(res, list("a","b")), dbFetch(res, 1) and dbBind(res, list(list(1))), I saw dbHasCompleted() FALSE with ready_ false; dbFetch() errors "needs to be bound", and dbColumnInfo() runs peek_first_row() on the reset, cleared statement (no crash under valgrind in the equivalent scenario; it returned the right columns). (Confirmed) The description already lists this as left out, and the commit improves on the old behaviour, which kept ready_ true. Suggested fix: set complete_ = true next to ready_ = false in bind(), so every first-row failure leaves the same state. init() resets it on success.

  2. The test covers only the first-row failure. test-dbBind.R#L83-L101. It does not check dbGetRowsAffected() (NA) or dbHasCompleted() (TRUE) after the failed re-bind, nor the statement variant, where a stale affected-row count would have been the old symptom. (Confirmed by running both; both behave as intended.) Suggested fix: add expect_true(dbHasCompleted(res)) to the block, and one dbSendStatement() case with expect_true(is.na(dbGetRowsAffected(s))).


Generated by Claude Code

`bind()` now also marks the result complete before binding the first row,
so every failure there, including an unsupported parameter type,
leaves the same completed, unbound state;
a successful bind resets it in `init()`.
The tests also check `dbHasCompleted()` and `dbGetRowsAffected()`
after a failed re-bind, for a query and for a statement.

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

Superseded: Accepted limitations

Superseded by the current copy.

Two clean review rounds: the first of ddd58b0 found that a result bound and fetched before kept its state when the first row of a new dbBind() failed, so a fetch silently returned no rows (fixed in af501a0); the second found nothing above Low, and its two Lows are fixed in 9897482 (every failure in the first row leaves a completed, unbound result; the tests cover dbHasCompleted(), dbGetRowsAffected() and dbSendStatement()). Every sqlite3_bind_*() call of the data-frame path is checked, the message uses a fixed format, dbAppendTable() and dbWriteTable() leave the table unchanged on failure, DBItest passes, valgrind is clean, and appending a million rows takes the same time. These remain:

  • src/SqliteResultImpl.cpp: when a later parameter row fails during dbFetch(), the rows already fetched in that call are discarded with the error, as for a step error on main; the description says so. Relevance: low; reviewer's confidence: high.
  • With RSQLite's build settings, the default length limit equals R's maximum string length, so the check matters for connections that lower the limit and for allocation failures. Relevance: low; reviewer's confidence: high.
  • An unsupported parameter type or a non-raw list element in a later row still leaves a reset statement that is not marked complete, as on main; the description lists it as left out. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Two clean review rounds: the first of ddd58b0 found that a result bound and fetched before kept its state when the first row of a new dbBind() failed, so a fetch silently returned no rows (fixed in af501a0); the second found nothing above Low, and its two Lows are fixed in 9897482 (every failure in the first row leaves a completed, unbound result; the tests cover dbHasCompleted(), dbGetRowsAffected() and dbSendStatement()). Every sqlite3_bind_*() call of the data-frame path is checked, the message uses a fixed format, dbAppendTable() and dbWriteTable() leave the table unchanged on failure, DBItest passes, valgrind is clean, and appending a million rows takes the same time. No limitation introduced by this pull request remains; these are older:


Generated by Claude Code

@krlmlr
krlmlr merged commit 53f2693 into main Nov 13, 2026
8 checks passed
@krlmlr
krlmlr deleted the claude/bind-return-codes branch November 13, 2026 15:27
krlmlr pushed a commit that referenced this pull request Nov 13, 2026
`raise_bind_exception()` from #868 throws a `step_error` with SQLite's result code
instead of calling `cpp11::stop()`,
so that `read_ahead()` keeps a value SQLite refuses to bind
like any other error of the step past the last row of a fetch.
The completion it sets is held back until the next fetch raises the kept error,
so that `dbHasCompleted()` stays `FALSE` until then.
A new `dbBind()` resets both the state #868 resets and the kept error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
krlmlr pushed a commit that referenced this pull request Nov 13, 2026
A value SQLite refuses to bind carries SQLite's own code since the merge of #868,
such as `SQLITE_TOOBIG`;
only a parameter of a type that cannot be bound carries `SQLITE_ERROR`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7mthffYErGmWTGDfQ
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
…urce

The checks of the bind return codes from #868 move into the parameter source:
SqliteListParamSource checks each code through SqliteParamSource::check_bind(),
which names the parameter and the row and throws a SqliteBindError with SQLite's code.
The result's bind_row() turns it into a step_error with that code
and marks the result complete, as raise_bind_exception() did,
which goes away with the result's own row counter.
The tests of both branches are kept in test-dbBind.R.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd8MVXyvU7qoMeruD1R
krlmlr pushed a commit that referenced this pull request Nov 30, 2026
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
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