Skip to content

refactor: Bind list parameters through a parameter source - #855

Draft
krlmlr wants to merge 9 commits into
claude/fix-error-mid-resultfrom
claude/arrow-param-source
Draft

krlmlr wants to merge 9 commits into
claude/fix-error-mid-resultfrom
claude/arrow-param-source

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

This is the first pull request of the reworked Arrow stack, as planned in #829 (comment). It moves the binding of list parameters out of the result into a parameter source, so that a later pull request can add an Arrow parameter source next to it. No behavior and no message changes.

What changes

SqliteResultImpl bound list parameters itself: bind_row() reset the statement and bound one parameter set through bind_parameter_pos(), while group_ and groups_ counted the sets. That code moves, unchanged apart from names and the type of exception it throws, into SqliteListParamSource, behind a small abstract SqliteParamSource whose one method, bind_next_row(), resets the statement, binds the next set, and returns whether there was one. The result keeps the source of its latest bind in a boost::scoped_ptr and calls it from bind_row(), which is all that is left of the binding in SqliteResultImpl. The comment of the interface says that a source must not leave by the longjmp of an R error, which would leave the result ready on a statement that was reset and only partly bound; the list source reads its vectors with R's API directly, as the result did before, which fails only for an ALTREP vector whose data pointer can't be taken.

On the R side, db_bind() gets is_unnamed_placeholders() and match_placeholders() from #795, for the Arrow bind to share later. Unlike #795's version, match_placeholders() takes the parameters rather than their names, and counts the unused ones with seq_along(params) as db_bind() did. #795 counted them with seq_along(param_names), which turned "Named parameters not used in query: " into "Query does not require parameters." for an unnamed list bound to a query without placeholders. So match_placeholders() takes any object whose names are matched, and the Arrow bind of pull request 11 will pass, for example, the schema's named children rather than a vector of column names.

What a reviewer may want to check

  • Lifetime of the R vectors. The source holds the cpp11::list, which protects the vectors across the fetches that bind the later sets, as the params_ member of the result did. A new bind, or a first set that fails, destroys the source and releases the list, as before. Values are bound with SQLITE_TRANSIENT, so the statement never points into R memory. A new test binds vectors that only the result refers to and calls gc() between fetches; the same bind also passed under gctorture().
  • Errors of later sets. The source throws a std::runtime_error for a value it can't bind, and bind_row() turns it into a step_error with SQLITE_ERROR, which is what fix: A fetch returns its rows when the step past its last row fails #850's bind_parameter_pos() threw. So read_ahead() still keeps the error of a later set for the next fetch, and the fetch returns its rows. feat: Implement the DBI Arrow interface natively #795's list source called cpp11::stop() there, which bypassed read_ahead(). step_error stays private to SqliteResultImpl.cpp, and the interface does not depend on it.
  • The busy guard. Only bind() replaces the source, and only bind() and the fetches use it, all under fix: Never restart a statement after an error in dbFetch() or dbBind() #830's guard, so a handler can't replace the source while a fetch or a bind uses it. A new test pins that a dbBind() from a warning handler of a fetch is refused.
  • Speed of the default path. The virtual call happens once per parameter set, not once per value. Binding 100k rows of five columns (integer, double, character, logical and integer64) takes the same time before and after, within a millisecond, through an INSERT (40 ms), an UPDATE that changes no row (30 ms) and a SELECT per set that returns the rows (70 ms); 1M rows through the UPDATE take 0.29 to 0.30 s at best on both builds.

Left out

The Arrow parameter source and its R entry point (pull request 11 of the plan), executions(), the holds_r_objects() method that #795's interface has for reading streams on other threads (pull request 15), and everything else Arrow.

Tests

The first commit adds test-dbBind.R, which pins the messages for named, unnamed and missing parameters, including an unnamed list bound to a query without placeholders, the messages for values that can't be bound, parameter sets that return several rows, none, or that are empty, a later set that fails to bind after earlier sets wrote to the database, rebinding, bound vectors across fetches, and the refused bind from a handler. A later set that fails to bind in a fetch, which returns the earlier rows and raises from the next fetch, was already pinned in test-read-ahead.R and test-dbSendQuery.R. The new tests pass on #830's head (aa07034) as well as on this branch, and each test_that() block passes on its own after pkgload::load_all(). devtools::test() passes except for the three errors in test-httpvfs.R that main has as well (#832, #837). R CMD check --no-manual passes its tests, with one NOTE for the .git file that a git worktree puts in the built tarball.

Stack

Based on #830 (claude/fix-error-mid-result), which is based on #850. Next in the new stack: owning results through a shared pointer, and vendoring nanoarrow.

Review

The clean review found nothing above Low; its two points are answered by comments in c352631. See the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

These tests pin what binding a list of parameters does, before its implementation moves into a parameter source.
They cover the messages for parameters that don't match the placeholders,
including an unnamed list bound to a query without placeholders,
values that can't be bound,
parameter sets that return any number of rows or are empty,
a later set that fails to bind after earlier sets changed the database,
a new bind that replaces the sets left,
bound vectors that only the result refers to across fetches,
and a handler that tries to bind while a fetch runs.
A later set that fails to bind in a fetch is pinned in `test-read-ahead.R`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The result bound list parameters itself, with `bind_row()`, `bind_parameter_pos()` and the `group_` bookkeeping.
`SqliteListParamSource` now holds the list and binds its sets one at a time,
behind `SqliteParamSource`, whose one method `bind_next_row()` resets the statement and binds the next set.
A later pull request adds an Arrow parameter source next to it.
The source owns the list, which protects the vectors across the fetches that bind the later sets,
and a new bind or a failed first set releases it, as before.
A value that can't be bound throws a `std::runtime_error`, which `bind_row()` turns into a `step_error` with `SQLITE_ERROR`,
so that `read_ahead()` still keeps the error of a later set for the next fetch.

`db_bind()` gets `is_unnamed_placeholders()` and `match_placeholders()`, for the Arrow bind to share.
`match_placeholders()` takes the parameters, not their names, and counts the unmatched ones with `seq_along(params)`,
so that an unnamed list bound to a query without placeholders still fails with "Named parameters not used in query: ".
No message changes.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 7387832, by a Claude Code reviewer with clean context that read the description, the plan, the diff against #830's head aa07034, the code around it (SqliteResultImpl.cpp, DbResult.cpp's guard, R/db_bind.R) and #795's src/SqliteParamSource.* and R/db_bind.R at 43db19f, built the pull request and its base into separate libraries, plain and with AddressSanitizer, and ran the tests and its own reproducers against both builds. It posted nothing on GitHub itself.

What was run

  • test-dbBind.R on both builds, and each of its 10 test_that() blocks alone after pkgload::load_all() of each worktree: all pass on both.
  • devtools::test() with NOT_CRAN=true on the pull request: 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).
  • R CMD check --no-manual of a tarball built from git archive 7387832e: Status OK.
  • A comparison script of 1461 cases on both builds, recording values, condition class, message and call, warnings, row counts and completion: queries with ?, ?NNN (also gaps and repeats), :name, @name, $name, mixed and no placeholders against 19 parameter shapes (named, unnamed, partially named, missing, extra, duplicated, empty names, NA name, data frame, empty list) through dbGetQuery(), dbBind() and db_bind(allow_named_superset = TRUE); 18 kinds of values (unbindable in the first set, in a later set, in the second column, of length zero, factors, dates, integer64, blobs) through dbGetQuery(), dbExecute(), dbSendStatement() and fetches with n of 1, 2, 3, 4 and -1, peeks, dbColumnInfo() and rebinding; dbGetPreparedQuery(); handlers that bind, clear or fetch during a fetch.
  • A memory script (vectors that only the result holds, fetched row by row; rebinding with sets left; a failed first set; a failed later set; a handler's rebind; dbClearResult() with sets left; a result finalized by GC; the statement path; disconnecting with a result open) under gctorture(TRUE), and under AddressSanitizer with and without gctorture().
  • A busy handler that binds, clears or fetches the result while its bind steps; R errors raised from inside the source by R's internal mmap ALTREP class, at the first and a later set; test-dbBind.R, test-read-ahead.R, test-dbSendQuery.R, test-error.R and test-dbClearResult.R under AddressSanitizer.
  • Benchmarks alternating the builds: 200k sets of five columns (integer, double, character, logical, integer64) through an INSERT, an UPDATE of an empty table and a SELECT per set; 20k one-row dbBind() calls; 1M sets through the INSERT and the UPDATE.

What holds

  • The moved binding code is identical to the base's bind_parameter_pos() apart from names and the exception type, as the description says.
  • All 1461 cases give identical results on both builds, also under AddressSanitizer, including "Named parameters not used in query: " for an unnamed list bound to a query without placeholders, and fix: A fetch returns its rows when the step past its last row fails #850's kept error of a later set (the fetch returns the earlier rows, the next fetch raises a simpleError with call NULL, the result is then complete).
  • cpp11::unwind_exception derives from std::exception (cpp11 0.5.5), so the new catch (const std::runtime_error&) in bind_row() lets it through; R errors raised inside the source are not swallowed and keep the base's message, call and resulting state.
  • The 24 memory checks pass under gctorture() and AddressSanitizer, which reports nothing in any run; the guard refuses dbBind(), dbClearResult() and dbFetch() from warning and busy handlers on both builds alike.
  • Speed is unchanged within the noise of a shared machine (best times, base vs pull request): INSERT 0.164 vs 0.167 s, UPDATE 0.068 vs 0.068 s, SELECT 0.138 vs 0.136 s, 20k binds 0.390 vs 0.385 s; 1M sets 0.847 vs 0.846 s and 0.334 vs 0.341 s.
  • The interface is one pure virtual bind_next_row() and a virtual destructor, the method feat: Implement the DBI Arrow interface natively #795's Arrow source implements; step_error stays private, and holds_r_objects() is left out as the plan puts it in pull request 15.
  • The description matches the code and the scope matches the title; the .dd files hold relative paths only and match what the build regenerates; the build has the same 49 warnings as the base, all in vendored or unchanged code.

High

None.

Medium

None.

Low

  1. An R error that longjmps out of the source leaves the result ready on a reset, half-bound statement (pre-existing, identical on the base).

    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()
    );
    }
    params_.reset(new SqliteListParamSource(params));
    total_changes_start_ = sqlite3_total_changes(conn);
    bind_started_ = true;
    // A new execution starts: the error kept from the previous one is dropped
    error_kept_ = false;
    kept_error_.clear();
    kept_error_code_ = SQLITE_OK;
    try {
    bool has_params = bind_row();
    after_bind(has_params);
    } catch (...) {
    // 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
    params_.reset();
    ready_ = false;
    complete_ = false;
    nrows_ = 0;
    throw;
    }
    }
    and
    void SqliteListParamSource::bind_parameter(
    sqlite3_stmt* stmt,
    int pos,
    SEXP value_
    ) const {
    if (TYPEOF(value_) == LGLSXP) {
    int value = LOGICAL(value_)[i];
    if (value == NA_LOGICAL) {
    sqlite3_bind_null(stmt, pos);
    } else {
    sqlite3_bind_int(stmt, pos, value);
    }
    } else if (TYPEOF(value_) == INT64SXP && Rf_inherits(value_, "integer64")) {
    int64_t value = INTEGER64(value_)[i];
    if (value == NA_INTEGER64) {
    sqlite3_bind_null(stmt, pos);
    } else {
    sqlite3_bind_int64(stmt, pos, value);
    }
    } else if (TYPEOF(value_) == INTSXP) {
    int value = INTEGER(value_)[i];
    if (value == NA_INTEGER) {
    sqlite3_bind_null(stmt, pos);
    } else {
    sqlite3_bind_int(stmt, pos, value);
    }
    } else if (TYPEOF(value_) == REALSXP) {
    double value = REAL(value_)[i];
    if (value == NA_REAL) {
    sqlite3_bind_null(stmt, pos);
    } else {
    sqlite3_bind_double(stmt, pos, value);
    }
    } else if (TYPEOF(value_) == STRSXP) {
    SEXP value = STRING_ELT(value_, i);
    if (value == NA_STRING) {
    sqlite3_bind_null(stmt, pos);
    } else {
    sqlite3_bind_text(stmt, pos, CHAR(value), -1, SQLITE_TRANSIENT);
    }
    } else if (TYPEOF(value_) == VECSXP) {
    SEXP value = VECTOR_ELT(value_, i);
    if (TYPEOF(value) == NILSXP) {
    sqlite3_bind_null(stmt, pos);
    } else if (TYPEOF(value) == RAWSXP) {
    sqlite3_bind_blob(
    stmt,
    pos,
    RAW(value),
    Rf_length(value),
    SQLITE_TRANSIENT
    );
    } else {
    throw std::runtime_error("Can only bind lists of raw vectors (or NULL)");
    }
    } else {
    throw std::runtime_error(
    std::string("Don't know how to handle parameter of type ") +
    Rf_type2char(TYPEOF(value_)) + "."
    );
    }
    }
    . (Confirmed) An integer vector of R's mmap ALTREP class made with ptrOK = FALSE makes INTEGER() raise "cannot access data pointer for this mmaped vector" inside bind_parameter(). dbBind() raises it with call result_bind(res@ptr, params), but the result keeps the ready state of its previous bind with dbHasCompleted() FALSE; the next dbFetch() reads the reset statement, steps it with the bindings cleared, and raises the same error when it reaches the bind again. Unmapping a bound vector between fetches does the same for a later set, and the row of the failing fetch is lost. Base and pull request print the same lines, AddressSanitizer reports nothing, and fix: Never restart a statement after an error in dbFetch() or dbBind() #830's comment in fetch_rows() already describes this kind of longjmp, so the pull request's claim of no behavior change holds. It is noted because the brief asks about R errors in the source, which is now the one place where they arise. Suggested fix: nothing in this pull request; in a follow-up, clear ready_ at the start of bind() so that a longjmp leaves the result asking for a new bind, or state in the interface comment that a source must not longjmp, for example by reading R memory under cpp11::unwind_protect(), whose unwind_exception the new catch already lets through, after measuring its cost per set.

  2. match_placeholders() needs a named object, so feat: Implement the DBI Arrow interface natively #795's Arrow call with a plain vector of column names would no longer work.

    RSQLite/R/db_bind.R

    Lines 42 to 73 in 7387832

    # The position of each placeholder among the elements of `params`, by name.
    # An element that no placeholder uses, such as any element of an unnamed list,
    # is an error, or a warning with `allow_named_superset`.
    match_placeholders <- function(
    placeholder_names,
    params,
    allow_named_superset
    ) {
    param_names <- names(params)
    param_indexes <- match(placeholder_names, param_names)
    if (any(is.na(param_indexes))) {
    stopc(
    "No value given for placeholder ",
    paste0(placeholder_names[is.na(param_indexes)], collapse = ", ")
    )
    }
    unmatched_param_indexes <- setdiff(seq_along(params), param_indexes)
    if (length(unmatched_param_indexes) > 0L) {
    if (allow_named_superset) {
    errorc <- warningc
    } else {
    errorc <- stopc
    }
    errorc(
    "Named parameters not used in query: ",
    paste0(param_names[unmatched_param_indexes], collapse = ", ")
    )
    }
    param_indexes
    }
    . (by reading) The change from param_names to params keeps the base's message for an unnamed list, as the description explains. feat: Implement the DBI Arrow interface natively #795's db_bind_arrow() passes column_names, an unnamed character vector; with this signature names(params) is NULL, and every placeholder would fail with "No value given for placeholder ...". The Arrow bind of pull request 11 can pass the schema's named children list instead. Suggested fix: say in the comment above match_placeholders() that params is any vector or list named by the parameters, or adapt the call when pull request 11 adds it.


Generated by Claude Code

…laceholders()` takes

The comment of `SqliteParamSource` now says that a source must not leave by the longjmp of an R error,
what happens to the result if it does,
and how a source avoids it: through cpp11's safe wrappers, or with R API calls made before binding starts.
`SqliteListParamSource` reads its vectors with R's API directly, as the result did before,
which fails only for an ALTREP vector whose data pointer can't be taken.

The comment of `match_placeholders()` now says that it takes an object whose names are matched,
such as a list of parameters or the named `children` of an Arrow schema,
not a vector of the names themselves.

No code changes.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

The clean review found nothing above Low: in 1461 cases compared with #830's head, values, conditions, row counts and completion were identical, also under AddressSanitizer and gctorture(), and the speed is unchanged. Its two Lows are answered by comments in c352631: what match_placeholders() takes (a named object, so that the Arrow bind of pull request 11 passes, for example, the schema's named children), and the rule below. These remain, both as on main and #830:

  • src/SqliteParamSource.h#L10-L21: an R error that leaves the list source by longjmp, which only an ALTREP vector whose data pointer can't be taken triggers, leaves the result ready on a statement that was reset and only partly bound, so the next fetch steps it with the bindings cleared. Behavior is unchanged from the base; the interface comment now says a source must not longjmp and what happens if it does. Relevance: low; reviewer's confidence: high. (recorded)
  • src/SqliteResultImpl.cpp#L174-L176: rebinding a result with zero-length parameters after a partial fetch completes the result without resetting the statement, so it keeps its read lock until the next bind or dbClearResult(); a second connection gets "database is locked". Found while writing this pull request; a fix changes behavior, so it belongs in a pull request of its own. Relevance: low; reviewer's confidence: high (reproduced on fix: Never restart a statement after an error in dbFetch() or dbBind() #830's head).

Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review found nothing above Low: in 1461 cases compared with #830's head, values, conditions, row counts and completion were identical, also under AddressSanitizer and gctorture(), and the speed is unchanged. Its two Lows are answered by comments in c352631: what match_placeholders() takes (a named object, so that the Arrow bind of pull request 11 passes, for example, the schema's named children), and the rule that a parameter source must not longjmp. This pull request introduces no limitation of its own. Two findings that main and #830 already show are issues now:


Generated by Claude Code

…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

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