Skip to content

feat: Bind the rows of an Arrow stream to a statement - #866

Draft
krlmlr wants to merge 13 commits into
claude/arrow-stream-lifetimefrom
claude/arrow-bind-stream
Draft

krlmlr wants to merge 13 commits into
claude/arrow-stream-lifetimefrom
claude/arrow-bind-stream

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Pull request 11 of the Arrow rework plan. It stacks on #865 (Arrow streams outlive dbClearResult() and dbDisconnect()), which stacks on #864, #863, #862, #861, #860, #859, #857, #856, #855, #830 and #850.

What changes

A new internal entry point, bind_arrow_stream(res, stream), binds the rows of a nanoarrow array stream of struct arrays (or of anything nanoarrow converts to one, such as a data frame) to a prepared statement, and runs the statement once per row, as dbBind() does with a data frame. No DBI method calls it yet; the default dbBind() path is unchanged.

Parameter source. The rows come through a new SqliteArrowParamSource, next to #855's list source behind SqliteParamSource. SqliteResultImpl::bind() is split so that both sources share the start of a bind (start_bind()) and the count check (check_param_count()), with the same messages as before. The source reads the stream's arrays as the statement runs, one get_next() whenever the rows of the current array are bound, and skips empty arrays. A null row of the struct array binds NULL to every placeholder. The offset of a sliced struct array applies to its columns, which may have offsets of their own, as Arrow's StructArray.slice() exports them.

Placeholders. Named placeholders take the columns of the same name, anonymous and numbered ones take unnamed columns by position, through #855's is_unnamed_placeholders() and match_placeholders(), which gets the schema's named children. The messages are those of dbBind(): a column without a name counts as an unnamed parameter, as in DBI's default dbBindArrow(), which drops names that are all empty. A stream that isn't of struct arrays fails with "Parameters must be an Arrow stream of struct arrays, with a column per placeholder."

Types. These bind to the storage classes that dbBind() uses for the matching R types:

  • bool and the signed and unsigned integers of 8 to 64 bits as integers; a uint64 value beyond INT64_MAX fails with its value and parameter
  • half float, float and double as reals
  • utf8 and large utf8 as text, binary and large binary as blobs; an empty value stays an empty text or blob, not NULL
  • the null type as NULL
  • date32 as days since the epoch, time32 and time64 as seconds since midnight, timestamp as seconds since the epoch, and duration as seconds, all as reals and in any unit; a timestamp is an instant, whatever its time zone. These include the date32, time64[us] and timestamp[us, UTC] of the read path of feat: Build Arrow date, time and timestamp arrays with extended_types #861, so a chunk read with extended_types binds back as it was stored. A duration binds as dbBind() binds a difftime in seconds, such as an hms; dbBind() binds a difftime in other units as its bare number, while nanoarrow converts it to a duration, which binds as seconds.

Nulls come from the validity bitmaps. Every other type, such as a dictionary (a factor of a data frame), a list, a decimal or date64, fails with "Can't bind parameter 1 of Arrow type …" before any row runs: the source checks the schema in its constructor, before the result drops its previous bind, and takes the stream over only then, so the stream stays with its owner and the previous bind goes on. The result of every sqlite3_bind_*() call is checked. bind_arrow_stream() reads the schema through nanoarrow before it calls the C++ code, so a failing get_schema() reports nanoarrow's message ("array_stream->get_schema(): …") rather than the source's "Can't read the schema of the Arrow parameters: …", which only a stream whose schema fails the second time would reach.

Errors. An error of the stream's get_next() ("Can't read the Arrow parameters: …") or of a value fails like a later parameter set of dbBind() (#830, #855): it becomes a step_error with SQLITE_ERROR, so after a full fetch it is kept for the next one, a statement without rows raises it from the bind after the earlier rows ran, and dbGetRowsAffected() counts those rows. The stream's callbacks may call R, as a stream of RSQLite (#864) does to warn about converted values: they run under cpp11::unwind_protect(), so an R error that leaves one by a jump, such as a warning made an error by options(warn = 2), unwinds the C++ frames and leaves the result unbound, like any other failed bind. A stream of RSQLite protects its own callbacks with cpp11 in turn, and cpp11 protects such nested calls from 0.4.6 on, so LinkingTo now asks for cpp11 (>= 0.4.6). #830's busy guard covers the whole bind, so a handler of such a warning can't clear the result meanwhile. The source releases the stream from its destructor, unprotected, also from a new bind, dbClearResult() or a finalizer: as the Arrow C stream interface expects, a stream's release() must not raise an R error, which a code comment states.

Deliberately left out

  • Dictionary arrays, and with them the factor columns of a data frame, checks and tests of values beyond 32-bit lengths, and binding a result to its own stream (or two results to each other's streams): pull request 12. Dictionaries fail with the type error above; the 64-bit binds of SQLite are used and their result codes checked, but not tested with values beyond 2 GiB. A result bound to a stream of itself fails at the first row, which feat: Read a result as a lazy Arrow array stream #864's check of the execution refuses.
  • Requested types: pull requests 13 and 14.
  • dbBindArrow(), dbAppendTableArrow() and the other DBI methods: pull request 17.
  • Streams read on worker threads: pull request 15. The source calls the stream on R's main thread, inside the bind or fetch that needs the next row.

Tests

tests/testthat/test-arrow-bind.R, through nanoarrow:

  • a round trip of a data frame of integer, real, text, blob, Date, hms and POSIXct columns with nulls into a table with extended_types, read back with dbGetQuery(), and of its chunk from the Arrow read path into a second table, read back both ways
  • every integer width, signed and unsigned, booleans, half floats, floats, doubles and the null type, with their storage classes
  • large utf8 and binary, time32 in milliseconds, a timestamp in seconds with a time zone, a duration in milliseconds, and a null row of the struct array
  • a sliced struct array of integer, text, boolean and binary columns, with and without a validity bitmap of its own, and one whose columns are sliced as well; the boolean values and the validity bitmaps start at a bit offset
  • a stream of several arrays with an empty one in between, fetched in two steps, and a stream without arrays, for a query and a statement
  • named, $, @, anonymous and numbered placeholders
  • the messages of mismatched parameters, compared with those of dbBind(), and a stream that isn't of struct arrays
  • dictionary and list columns, which fail before any row runs, leave the stream readable and the previous bind fetching
  • a uint64 value out of range in the third row: kept after a full fetch of a query, raised by the bind of an INSERT after two rows
  • a stream of RSQLite that fails with an SQLite error in its third chunk, one whose warning handler is refused dbClearResult() by the busy guard, and one whose warning, made an error, leaves get_next() by a jump; the last test fails with unwind_protect() removed

Every test_that() block passes on its own after load_all(). devtools::test() with NOT_CRAN=true passes except the three known errors in test-httpvfs.R (#832, #837). valgrind (--leak-check=full) reports no errors and nothing lost for test-arrow-bind.R.

https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn


Generated by Claude Code

The internal `bind_arrow_stream()` binds the rows of a nanoarrow array stream
of struct arrays to a prepared statement,
through a new `SqliteArrowParamSource` behind the parameter source of #855,
and runs the statement once per row, as `dbBind()` does with a data frame.
Named placeholders take the columns by name,
anonymous and numbered ones take unnamed columns by position,
with the messages of `dbBind()`.

Integers, booleans, floats, utf8 and binary (also large),
the null type, date32, time32, time64 and timestamp bind
as the storage classes that `dbBind()` uses,
with nulls from the validity bitmaps.
Other types fail before any row runs,
and leave the stream and the previous bind as they were.
An error of the stream or of a value fails like a later parameter set
of `dbBind()`, and an R error that leaves a callback of the stream
by a jump unwinds the C++ frames.
The default `dbBind()` path is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
@krlmlr
krlmlr added this pull request to stack #851 November 12, 2026 23:18
krlmlr and others added 2 commits November 12, 2026 23:23
The CI's auto-update regenerated `src/SqliteParamSource.dd` and `src/cpp11.dd` with GCC,
whose dependency output indents continuation lines by one space,
which the filter in `src/Makevars.deps` does not drop,
so the files gained hundreds of absolute and vendored paths (#836).
This restores them as they were at 098aa5e
and keeps the auto-update's formatting of `src/SqliteParamSource.cpp`.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 098aa5e, by a Claude Code reviewer with clean context that read the description of #866 and of #855, the diff against #865 (049716e), the code it touches (SqliteResultImpl bind and fetch paths, run_guarded(), the stream of #864/#865, the vendored nanoarrow 0.9.0 view accessors, cpp11 0.5.5's unwind_protect()), and the tests; built the pull request and its base into separate libraries, plus an AddressSanitizer/UBSan build of the pull request; ran the tests, valgrind and my own reproducers. I posted nothing myself.

What was run

  • test-arrow-bind.R on the pull request (passes) and on the base (fails, as expected: bind_arrow_stream() is new); test-dbBind.R on both (passes).
  • Each of the 9 test_that() blocks of test-arrow-bind.R alone in a fresh process after pkgload::load_all(): all pass.
  • 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).
  • ASan + UBSan (LD_PRELOAD of libasan/libubsan) on test-arrow-bind.R, test-dbBind.R and my reproducers: no report from the new code. valgrind --leak-check=full on test-arrow-bind.R plus my reproducers: no invalid access, nothing definitely or indirectly lost.
  • Reproducers: sliced struct and child arrays, malformed lengths, pre-epoch and fractional timestamps, hms and Date compared with dbBind(), placeholder name mismatches compared with dbBind(), self-binding, two results bound to each other's streams, an R error raised from a warning handler inside get_next() during a bind and during a fetch, a rebind from such a handler, a uint64 overflow mid-stream, a stream error kept for the next fetch, GC and disconnect while bound.

What holds

  • Integer widths and signedness, uint64 above INT64_MAX (message with value and parameter), bool, half float, utf8/binary and their large variants with a non-zero child offset, empty text and blob vs NULL, child validity bitmaps, date32, and time/timestamp units all bind as described; pre-epoch and fractional POSIXct and Date values store exactly what dbBind() stores. Microseconds round-trip with feat: Build Arrow date, time and timestamp arrays with extended_types #861's nearbyint(seconds * 1e6) for every value within 2^52 µs (checked on 10^7 random values).
  • Lengths are validated by ArrowArrayViewSetArray(): a struct longer than its child fails with "Invalid Arrow parameters", no out-of-bounds read under ASan.
  • The schema is checked before the stream is moved and before the previous bind is dropped; arrays are released once (ASan/valgrind clean); empty arrays and streams without arrays work.
  • fix: Never restart a statement after an error in dbFetch() or dbBind() #830's semantics hold: the busy guard refuses dbClearResult() and a rebind from a warning handler; a mid-stream error is kept after a full fetch, raised by the bind of a statement after the earlier rows, and the next bind works; an R error from a handler inside get_next() unwinds cleanly in both the bind and the fetch path.
  • Placeholder messages match dbBind() in every case I tried (empty names, mixed names, duplicates, ?3, unused names).
  • Self-binding fails at the first row with a clear message; mutual binding fails at the schema; nothing crashes.
  • src/SqliteParamSource.dd gains only DbArrow.h, no absolute path. The description matches the code.

High

None.

Medium

  1. The offset of the struct array is ignored for its children, so a sliced struct array binds the wrong rows without an error.
    if (!ArrowArrayViewIsNull(view.get(), i)) {
    for (size_t k = 0; k < indexes.size(); ++k) {
    // sqlite parameters are 1-indexed
    bind_parameter(stmt, static_cast<int>(k) + 1, i);
    and
    const struct ArrowArrayView* values = view->children[indexes[pos - 1]];
    if (type.type == NANOARROW_TYPE_NA || ArrowArrayViewIsNull(values, row)) {
    — In Arrow, a struct's offset applies to its children (nanoarrow's own validation requires child length >= parent offset + length, which I hit), but the row index i is passed unchanged to the child views, whose accessors add only the child's own offset. The struct-level null check, by contrast, does add the parent offset, so validity and values come from different rows. (Confirmed) A struct of x = c(10L, 20L, 30L, 40L) modified to offset = 2, length = 2 binds 10 and 20 instead of 30 and 40. nanoarrow's R constructors and RSQLite's read path emit offset 0, but StructArray.slice() in Arrow C++/pyarrow exports a non-zero struct offset, and this becomes a user path once dbBindArrow() lands (pull request 17). Suggested fix: bind children at view->offset + i (keep ArrowArrayViewIsNull(view.get(), i) for the struct row) and add a test with nanoarrow_array_modify(array, list(offset = ...)), including a struct validity bitmap.

Low

  1. The nested cpp11::unwind_protect() is only correct with cpp11 >= 0.5.0, while DESCRIPTION still links to cpp11 (>= 0.4.0).

    cpp11::unwind_protect([&] {
    code = callback();
    if (code != 0) {
    message = stream->get_last_error(stream);
    }
    });
    — (by reading) In cpp11 0.4.x a nested unwind_protect() runs its code unprotected, so for a stream of RSQLite (feat: Read a result as a lazy Arrow array stream #864) the cpp11::warning() and warn_coercion() calls inside get_next() would longjmp past that stream's C++ frames (skipping fetch_loop()'s cleanup and destructors) straight to this outer protect. With the installed cpp11 0.5.5 both levels unwind correctly, as the warn = 2 test shows. Suggested fix: raise LinkingTo: cpp11 (>= 0.5.0), or note the requirement next to call_stream().

  2. The stream's release() runs unprotected from the source's destructor.

    class SqliteArrowParamSource : public SqliteParamSource {
    nanoarrow::UniqueArrayStream stream;
    — (by reading) The destructor runs from params_.reset() in start_bind() (
    params_.reset(params);
    ), from dbClearResult() and from the result's finalizer. A release() that raised an R error would skip the C++ frames of a bind in progress and leak the new source. No known producer does this (nanoarrow's R streams release through R_ReleaseObject(); RSQLite's own stream does not call R), and the description acknowledges it. Suggested fix: state in the class comment that release() must not call into R in a way that can raise, the same contract refactor: Bind list parameters through a parameter source #855 states for sources.

  3. Data frame columns that dbBind() accepts are refused.

    bool can_bind(enum ArrowType type) {
    switch (type) {
    case NANOARROW_TYPE_NA:
    case NANOARROW_TYPE_BOOL:
    case NANOARROW_TYPE_INT8:
    case NANOARROW_TYPE_UINT8:
    case NANOARROW_TYPE_INT16:
    case NANOARROW_TYPE_UINT16:
    case NANOARROW_TYPE_INT32:
    case NANOARROW_TYPE_UINT32:
    case NANOARROW_TYPE_INT64:
    case NANOARROW_TYPE_UINT64:
    case NANOARROW_TYPE_HALF_FLOAT:
    case NANOARROW_TYPE_FLOAT:
    case NANOARROW_TYPE_DOUBLE:
    case NANOARROW_TYPE_STRING:
    case NANOARROW_TYPE_LARGE_STRING:
    case NANOARROW_TYPE_BINARY:
    case NANOARROW_TYPE_LARGE_BINARY:
    case NANOARROW_TYPE_DATE32:
    case NANOARROW_TYPE_TIME32:
    case NANOARROW_TYPE_TIME64:
    case NANOARROW_TYPE_TIMESTAMP:
    return true;
    default:
    return false;
    }
    }
    — (Confirmed) a difftime column becomes duration('us') and fails with "Can't bind parameter 1 of Arrow type duration('us').", while dbBind() binds its number; factors (dictionaries) fail too. Dictionaries are deferred to pull request 12, but duration is not mentioned. Suggested fix: list duration under "Deliberately left out", or bind it as seconds.

  4. A failing get_schema() never reaches the C++ message.

    RSQLite/R/db_bind.R

    Lines 38 to 39 in 098aa5e

    stream <- nanoarrow::as_nanoarrow_array_stream(stream)
    schema <- nanoarrow::infer_nanoarrow_schema(stream)
    — (Confirmed) infer_nanoarrow_schema() in R calls get_schema() first, so the user sees nanoarrow's "array_stream->get_schema(): [5] …" rather than "Can't read the schema of the Arrow parameters: …". Suggested fix: check the format from the C++ schema read instead, or accept and drop the unreachable wording.

  5. Size. About 737 hand-written lines (776 minus generated cpp11 files, the .dd line and the snapshot) against the ~600 target; ~330 are tests and helpers. The code is cohesive; the only clean split is moving the start_bind()/check_param_count() refactor of SqliteResultImpl::bind() (~30 lines) ahead, or trimming the type matrix to the read-path types and adding the remaining widths in a follow-up. Not worth splitting in my view.

Outside this diff, UBSan reports memcpy(…, NULL, 0) for an empty blob in SqliteColumnDataSource::fetch_blob() (src/SqliteColumnDataSource.cpp line 92), which predates this pull request.


Generated by Claude Code

The offset of the struct array applies to its children,
so the source binds the values of `offset + i`;
the null check of the struct row already counted it.
Durations bind as seconds, as `dbBind()` binds a difftime in seconds.
`LinkingTo` asks for cpp11 0.5.0,
whose nested `unwind_protect()` protects the callbacks of a stream of RSQLite
inside those of the parameter source,
and a comment states that the stream's `release()` must not raise an R error.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Second review round of this pull request, of 8ccd758, on top of c0c6a4b: a review of this pull request at 8ccd758, by a Claude Code reviewer with clean context that read the description of #866, the first review only to know what the commit addresses, git diff c0c6a4bc 8ccd7584, the code around it (bind_next_row(), bind_parameter(), call_stream(), the vendored nanoarrow view accessors) and the headers of cpp11 0.4.3, 0.4.7, 0.5.0 and 0.5.5; built the commit and its base into separate libraries, plus an AddressSanitizer/UBSan build of the commit and builds against older cpp11 releases; ran the tests, R CMD check, valgrind and my own reproducers. I posted nothing myself.

What was run

  • test-arrow-bind.R with NOT_CRAN=true on the commit (all 10 blocks pass) and on the base (the duration block errors, the sliced block fails 3 expectations, as expected). The two changed blocks pass alone in a fresh process after pkgload::load_all().
  • devtools::test() with NOT_CRAN=true: 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 --ignore-vignettes of the built tarball: tests and examples OK, one NOTE about a hidden .git, which is the .git file of my worktree, not the package.
  • Install against cpp11 0.4.7 with the commit's DESCRIPTION; and with the bound lowered, builds and test runs against cpp11 0.4.3, 0.4.7 and 0.5.0.
  • ASan + UBSan (LD_PRELOAD) and valgrind --leak-check=full on test-arrow-bind.R and the reproducers below.
  • Reproducers: a sweep over 28 child types (int8 to uint64, bool, half float, float, double, utf8, large utf8, binary, large binary, null, date32, time32 s/ms, time64 us/ns, timestamp s/ns, duration s/ms/us/ns), each with a child offset (0, 1, 3, 7) and a struct offset (0, 5, 13, 31), with and without a struct validity bitmap, plus a stream mixing sliced, unsliced, empty and sliced arrays, compared with the same rows built unsliced; raw int64 durations in every unit including ±1, ±1500, ±999999999, 2^53 + 1, INT64_MAX and INT64_MIN; difftime in secs to weeks via dbBind(), via this path, and via as.data.frame() of the stream then dbBind() (DBI's default dbBindArrow()); a struct whose child is shorter than offset plus length; a warn = 2 jump out of a stream of RSQLite under cpp11 0.4.3 and 0.5.0 (all under /tmp/claude-0/-home-user-RSQLite/f42b7fc0-2b11-523a-8045-e512d240ea51/scratchpad/r866-r2/).

What holds

  • The Medium finding of the first round is fixed: children are read at view->offset + i, struct nulls through ArrowArrayViewIsNull(view, i), which adds the struct offset itself, and the child accessors add the child's own offset. The sweep finds 0 mismatches on the commit, for every type, including booleans at bit offsets that cross byte boundaries, offsets into the offsets buffer of utf8/binary and their large variants, child validity bitmaps under offsets, the null type, and multi-chunk streams. The base shows mismatches for every type. (Confirmed)
  • A child shorter than the struct's offset plus length fails with "Invalid Arrow parameters: Expected struct child 1 to have length >= 3 …" and no out-of-bounds read under ASan. (Confirmed)
  • Durations bind as value / units_per_second in doubles: exact for the small values, negative values keep their sign, INT64_MAX and INT64_MIN convert without overflow or UBSan reports; above 2^53 units the int64-to-double conversion rounds, as for timestamps, which REAL storage implies anyway. A duration bound into a TIME column reads back as the right hms with extended_types. (Confirmed)
  • The documented difference from dbBind() is accurate: dbBind() binds a difftime in mins, hours, days or weeks as its bare number (1.5 hours binds 1.5), this path binds seconds (5400). Seconds are the right call: they are what extended_types reads from a TIME column, and DBI's default dbBindArrow(), which converts the stream with as.data.frame() and gets difftime in secs, binds the same seconds, so pull request 17 will not change results when it switches to this path. (Confirmed)
  • LinkingTo: cpp11 (>= 0.5.0) is enforced at install time ("package 'cpp11' 0.4.7 was found, but >= 0.5.0 is required"); 0.5.0 compiles and passes; R CMD check has no new note. cpp11 0.5.0 is from 2024, so the bound costs nothing in practice. (Confirmed)
  • ASan/UBSan and valgrind: nothing from the new code, nothing definitely or indirectly lost; the only UBSan report is the pre-existing memcpy(…, NULL, 0) in SqliteColumnDataSource::fetch_blob() noted in round 1. (Confirmed)
  • No src/*.dd file changes. The title and description match the commit.

High

None.

Medium

None.

Low

  1. The comment and description date the nested protection of cpp11 to 0.5.0, but it came with 0.4.6.

    // A stream of RSQLite protects its own callbacks with cpp11 in turn:
    // cpp11 >= 0.5.0 protects nested calls, see LinkingTo in DESCRIPTION.
    — (Confirmed) cpp11 0.4.3's protect.hpp has the should_unwind_protect shortcut that runs a nested unwind_protect() unprotected; 0.4.7 (and 0.4.6 by its NEWS: "Nested calls to cpp11::unwind_protect() are no longer supported or encouraged", with the shortcut removed) and 0.5.0 have none. The warn = 2 test and my reproducer pass and are valgrind-clean even with 0.4.3, so the bound is a defensive one rather than a tested one. >= 0.5.0 is a fine bound to keep. Suggested fix: write "cpp11 >= 0.4.6 protects nested calls; LinkingTo asks for 0.5.0" in the comment and the description, or lower the bound to 0.4.6.

  2. The new slicing test covers only an int32 and a utf8 column.

    test_that("sliced struct arrays and sliced columns bind their own rows", {
    skip_if_not_installed("nanoarrow")
    con <- local_con()
    values <- function(array) {
    res <- dbSendQuery(con, "SELECT :x AS x, :y AS y")
    on.exit(dbClearResult(res))
    bind_arrow_stream(res, nanoarrow::basic_array_stream(list(array)))
    dbFetch(res)
    }
    array <- nanoarrow::as_nanoarrow_array(data.frame(
    x = c(10L, 20L, 30L, 40L, 50L),
    y = c("a", NA, "ccc", "", "e")
    ))
    # The offset of the struct array applies to its columns,
    # also with a validity bitmap of its own
    sliced <- nanoarrow::nanoarrow_array_modify(array, list(offset = 1, length = 3))
    expect_equal(values(sliced), data.frame(x = c(20L, 30L, 40L), y = c(NA, "ccc", "")))
    validity <- nanoarrow::as_nanoarrow_array(c(TRUE, TRUE, FALSE, TRUE, TRUE))
    sliced <- nanoarrow::nanoarrow_array_modify(array, list(
    offset = 1, length = 3, null_count = 1, buffers = list(validity$buffers[[2]])
    ))
    expect_equal(values(sliced), data.frame(x = c(20L, NA, 40L), y = c(NA, NA, "")))
    # Columns with offsets of their own, inside a sliced struct array
    columns <- lapply(array$children, nanoarrow::nanoarrow_array_modify, list(offset = 1, length = 4))
    sliced <- nanoarrow::nanoarrow_array_modify(array, list(
    offset = 2, length = 2, children = columns
    ))
    expect_equal(values(sliced), data.frame(x = c(40L, 50L), y = c("", "e")))
    })
    — (by reading) Booleans at bit offsets and a binary child are where offset arithmetic differs from fixed-width values; they work (my sweep), but no test pins them. Suggested fix: add a boolean column (struct offset not a multiple of 8) and a binary column to the sliced data frame of that test.


Generated by Claude Code

cpp11 protects nested calls of `unwind_protect()` from 0.4.6 on,
not from 0.5.0, so `LinkingTo` and the comment of `call_stream()` say so.
The test of sliced struct arrays gains a boolean column,
whose values and validity start at a bit offset, and a binary column.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this newer copy.

Two clean review rounds: the first of the whole pull request at 098aa5e, the second of 8ccd758. The first found that a sliced struct array bound the wrong rows, fixed in 8ccd758 together with durations, the cpp11 bound and a comment on release(). The second found nothing above Low: 28 column types sliced at every level bind the same rows as unsliced ones, durations bind as seconds without overflow, and AddressSanitizer, UBSan and valgrind report nothing from the new code; its two Lows are fixed in 0f7e793 (cpp11 0.4.6, and sliced boolean and binary columns in the test). devtools::test() and DBItest show only the three known test-httpvfs.R errors, and R CMD check passes. These remain:

  • src/SqliteParamSource.cpp#L360-L361: an Arrow duration binds as seconds in any unit, while dbBind() binds a difftime as its bare number, so a difftime in minutes binds 90 through dbBind() and 5400 through Arrow. Seconds match how TIME columns are read and what DBI's default dbBindArrow() binds; the description says so. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteParamSource.cpp#L215: dictionary arrays (factors), date64 and nested types are refused before any row runs; dictionaries, 64-bit lengths and self-binding come with pull request 12. Binding a result to its own stream or two results to each other's streams fails cleanly today. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteParamSource.h#L59: the stream's release() runs unprotected from the source's destructor, so a stream implemented in R whose release() raises an R error would jump past a bind in progress; the Arrow C interface forbids that, and the comment says so. Relevance: low; reviewer's confidence: high (recorded).
  • R/db_bind.R#L37: a stream whose get_schema() fails reports nanoarrow's message, since the R side reads the schema first. Relevance: low; reviewer's confidence: high.
  • About 740 hand-written lines against the plan's ~600; the reviewer found no split worth making beyond moving the 30-line refactor of bind() ahead. Relevance: low; reviewer's confidence: medium.
  • UBSan reports a pre-existing warning in fetch_blob() for an empty blob, outside this diff. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

…n R < 4.3

Before R 4.3, `as.POSIXct()` on a number needs an `origin`.
`.POSIXct()` gives the same value on every R version.

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

Question: bind an Arrow duration as dbBind() binds a difftime, as its bare number?

An Arrow duration binds as seconds in any unit (src/SqliteParamSource.cpp#L357-L370), while dbBind() binds a difftime as its bare number, whatever its units. nanoarrow converts a difftime to a duration, so a difftime of 90 minutes binds 90 through dbBind() and 5400 through this path. Seconds are what extended_types reads from a TIME column, and what DBI's default dbBindArrow() binds, since it converts the stream to a data frame whose difftime is in seconds; dbBind()'s bare number is a bug of main, now #870. Run on a build of #867's head (d63d63d), the top of the stack, which leaves this path as it is here:

library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:", extended_types = TRUE)
dbExecute(con, "CREATE TABLE t (x TIME)")
#> [1] 0
x <- as.difftime(90, units = "mins")

res <- dbSendStatement(con, "INSERT INTO t VALUES (:x)")
dbBind(res, list(x = x))
RSQLite:::bind_arrow_stream(res, data.frame(x = x))
dbClearResult(res)

# dbBind() stores 90, the Arrow path 5400 seconds
dbGetQuery(con, "SELECT x, CAST(x AS REAL) AS seconds FROM t")
#>          x seconds
#> 1 00:01:30      90
#> 2 01:30:00    5400
dbDisconnect(con)

Created on 2026-11-13 with reprex v2.1.1

If nobody decides, durations bind as seconds, and the two paths differ until #870 is fixed.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: bind Arrow date64, decimal and nested columns, rather than refusing them?

The parameter source binds the Arrow types that map to a storage class of SQLite (src/SqliteParamSource.cpp#L131-L160). Every other type fails with "Can't bind parameter … of Arrow type …" before any row runs, and leaves the stream and the previous bind as they were. Dictionaries, and with them factors, come with #867. date64 would need a choice between days and seconds, and decimals and nested types (lists, structs, maps) have no storage class in SQLite, so binding them would need a choice of text or blob encoding. Run on a build of #867's head (d63d63d), the top of the stack, which leaves this path as it is here:

library(DBI)
library(nanoarrow)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
res <- dbSendQuery(con, "SELECT :x AS x")

date64 <- as_nanoarrow_array(
  data.frame(x = as.Date("2026-11-13")),
  schema = na_struct(list(x = na_date64()))
)
RSQLite:::bind_arrow_stream(res, date64)
#> Error:
#> ! Can't bind parameter 1 of Arrow type date64.

dbClearResult(res)
dbDisconnect(con)

Created on 2026-11-13 with reprex v2.1.1

  • Keep refusing them (recommended): RSQLite's default read path produces none of them, and the error names the type and the parameter
  • Bind date64 as seconds and decimals as text, and keep refusing nested types

If nobody decides, these types keep failing before any row runs.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: protect the parameter stream's release() against R errors?

The parameter source releases its stream from its destructor without cpp11::unwind_protect() (src/SqliteParamSource.h#L59-L62), also when the destructor runs inside a bind in progress, dbClearResult() or a finalizer. A stream implemented in R whose release() raised an R error would jump past those C++ frames. The Arrow C stream interface expects a release callback not to fail, RSQLite's own streams don't raise from release(), and the code comment states the requirement. No reproducer: none of the streams at hand raises from release().

  • Accept it (recommended): a release that raises breaks the Arrow C stream interface for every consumer, not only for RSQLite
  • Call release() under unwind_protect() and keep the error for later, since a destructor can't throw

If nobody decides, the release stays unprotected.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: report a failing get_schema() of the parameter stream with RSQLite's own message?

bind_arrow_stream() reads the schema through nanoarrow before it calls the C++ code (R/db_bind.R#L39). A stream whose get_schema() fails therefore reports nanoarrow's message ("array_stream->get_schema(): …") rather than the parameter source's "Can't read the schema of the Arrow parameters: …", which only a stream whose schema fails the second time reaches. No reproducer: it needs a producer whose get_schema() fails, which nanoarrow doesn't offer from R.

  • Keep nanoarrow's message (recommended): it names the failing callback and carries the producer's error
  • Catch nanoarrow's error and raise it again with RSQLite's prefix

If nobody decides, the message stays nanoarrow's.


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.

Two clean review rounds: the first of the whole pull request at 098aa5e, the second of 8ccd758. The first found that a sliced struct array bound the wrong rows, fixed in 8ccd758 together with durations, the cpp11 bound and a comment on release(). The second found nothing above Low: 28 column types sliced at every level bind the same rows as unsliced ones, durations bind as seconds without overflow, and AddressSanitizer, UBSan and valgrind report nothing from the new code; its two Lows are fixed in 0f7e793 (cpp11 0.4.6, and sliced boolean and binary columns in the test). devtools::test() and DBItest show only the three known test-httpvfs.R errors, and R CMD check passes. The UBSan report for an empty blob in fetch_blob(), outside this diff, is fixed on main by #869, which this branch has merged (9bc6e56). These remain:

Found here, but also on main:


Generated by Claude Code

The Arrow stream parameter source now checks SQLite's result code of every bind
through SqliteParamSource::check_bind(), as the list parameter source does.
A value SQLite refuses, such as one over SQLITE_LIMIT_LENGTH,
fails with a SqliteBindError that names the parameter and the row,
and leaves the result in the same state as for dbBind().
The row counts the parameter sets over all arrays of the stream, in 64 bits,
and check_bind() takes the row as int64_t for both sources.
A test compares each step with dbBind() for text and blobs over the limit,
in the first row, in a later array kept for the next fetch,
and in a statement without rows.

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

Question: what should binding an INSERT to a stream that reads the same table do?

The clean review of 2026-11-29 rated this High, though only internal functions reach it today. The parameter source pulls the stream lazily, one array at a time while the statement runs (src/SqliteParamSource.cpp#L272-L281). If the stream reads a table on the same connection and the statement inserts into that table, the query behind the stream sees the rows the insert has just written, and the bind never ends. This is the "read with Arrow, append with Arrow" pattern that #865 lets a stream outlive its result for. Run in this session with devtools::load_all() at 8e6fe0d, the top of the stack:

con <- dbConnect(RSQLite::SQLite(), tempfile())
dbWriteTable(con, "t", data.frame(a = 1:3))
r <- dbSendQuery(con, "select a from t")
s <- RSQLite:::read_arrow_stream(r, 1L)
dbClearResult(r)
RSQLite:::bind_arrow_stream(dbSendStatement(con, "insert into t values (:a)"), s)
# never returns, and ignores setTimeLimit(); killed after 30 s, `t` held 1020902 rows

The reviewer saw the same with the default chunk size and 70000 rows. The data-frame path, dbAppendTable(con, "t", dbGetQuery(con, "select a from t")), adds three rows and stops, since dbGetQuery() reads everything first; main has no lazy path. #867's arrow_stream_result() already recognizes a stream of RSQLite and the result it reads, so a bind can tell whether the stream reads its own connection.

  • Read a stream of RSQLite on the same connection to its end before the first row runs, so that it binds a snapshot, as the data-frame path does; streams from other connections and other producers stay lazy (recommended: correct by default, and the memory cost only falls where the lazy path is unsafe)
  • Refuse a stream of RSQLite on the same connection that has not ended, with an error that suggests reading it first, which also stops copies between two tables of one connection
  • Document the hazard for pull request 17, which exposes the bind through dbBindArrow() and dbAppendTableArrow(), and leave the code as it is

The detection lives in #867, so the first two options would be written there, or here with a part of #867's check moved down. The fix was not written in this session, whose harness refused to start an agent for fixes. Kirill decides. If nobody decides, nothing changes until pull request 17, which must not expose the bind before this is settled.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Two clean review rounds: the first of the whole pull request at 098aa5e, the second of 8ccd758. The first found that a sliced struct array bound the wrong rows, fixed in 8ccd758 together with durations, the cpp11 bound and a comment on release(). The second found nothing above Low: 28 column types sliced at every level bind the same rows as unsliced ones, durations bind as seconds without overflow, and AddressSanitizer, UBSan and valgrind report nothing from the new code; its two Lows are fixed in 0f7e793 (cpp11 0.4.6, and sliced boolean and binary columns in the test). devtools::test() and DBItest show only the three known test-httpvfs.R errors, and R CMD check passes. The UBSan report for an empty blob in fetch_blob(), outside this diff, is fixed on main by #869, which this branch has merged (9bc6e56).

The clean review of 2026-11-29, after main (3.54.1) was merged up the stack, read this pull request at 2745035 and found one High here, which is not accepted: binding an INSERT to a stream that reads the same table on the same connection never ends and keeps growing the table, a hazard for pull request 17, which exposes the bind (question). The merge also made this source go through the shared check_bind(), with the message and state of dbBind(). 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:

Found here, but also on main:


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Finding: dbBind() and the Arrow bind disagree about all-empty names

The description says the Arrow bind's messages "are those of dbBind()" and that "a column without a name counts as an unnamed parameter". dbBind() doesn't follow that rule. R/db_bind.R:19 on main (:8 at 27450355) reads if (!is.null(names(params)) || any(names(params) != "")). Because of the ||, any non-NULL names count as named, and the second operand never matters. A list whose names are all "" is therefore rejected by dbBind(), while bind_arrow_stream() accepts the equivalent column. DBI's specification doesn't count empty names as names, so && was presumably intended. The bug is on main and in CRAN 3.54.1 as well, so the fix could go from main.

con <- dbConnect(RSQLite::SQLite())   # RSQLite 3.54.1 (CRAN), main fb8effeb, #866 27450355
rs <- dbSendQuery(con, "SELECT ?")
try(dbBind(rs, setNames(list(1), "")))
#> Error : Cannot use named parameters for anonymous/numbered placeholders
# Expected: binds like list(1)

# On #866 (27450355), the Arrow bind accepts the same input:
df <- data.frame(x = 1); names(df) <- ""
RSQLite:::bind_arrow_stream(rs, df); dbFetch(rs)[[1]]
#> [1] 1
  • Change || to && in R/db_bind.R in a separate PR from main, with a test (recommended)
  • Keep dbBind() as it is and reject all-empty names in the Arrow bind too, so the two paths agree

Finding (low): Malformed or unknown parameter schemas get the generic message

The description says every other type gets "Can't bind parameter k of Arrow type …", and that the generic "Can't read the schema of the Arrow parameters: …" is reached only by "a stream whose schema fails the second time". A schema that ArrowSchemaViewInit() can't parse, however, fails earlier, at src/SqliteParamSource.cpp:221 at 8e6fe0de, and gets the generic message. Examples are a format string nanoarrow doesn't know, which could be a future Arrow type, and a dictionary with non-integer indices. Every well-formed type that nanoarrow 0.9.0 parses gets the documented message. The later ArrowArrayViewInitFromSchema() branch (:246) wasn't reachable with any input tried.

library(nanoarrow)
con <- dbConnect(RSQLite::SQLite())   # #866 27450355 and #867 8e6fe0de give the same
bind1 <- function(child) {
  sch <- nanoarrow_schema_modify(na_struct(list(x = na_int32())), list(children = list(x = child)), validate = FALSE)
  rs <- dbSendQuery(con, "SELECT :x"); on.exit(dbClearResult(rs))
  tryCatch({RSQLite:::bind_arrow_stream(rs, basic_array_stream(list(), schema = sch, validate = FALSE)); "bound"}, error = conditionMessage)
}
bind1(na_decimal128(10, 2))
#> [1] "Can't bind parameter 1 of Arrow type decimal128(10, 2)."
bind1(nanoarrow_schema_modify(na_int32(), list(format = "zzz"), validate = FALSE))
#> [1] "Can't read the schema of the Arrow parameters: Error parsing schema->format 'zzz': parsed 1/3 characters"
bind1(nanoarrow_schema_modify(na_string(), list(dictionary = na_string()), validate = FALSE))
#> [1] "Can't read the schema of the Arrow parameters: Expected dictionary schema index type to be an integral type but found 'u'"
# Expected per the description: "Can't bind parameter 1 of Arrow type ..." for each
  • Correct the description, since the generic message is fine for schemas nanoarrow can't parse (recommended)
  • Report parse failures per parameter, with the parameter's position and its format string

Both findings came from mapping this stack onto RMariaDB (r-dbi/RMariaDB#596) and were checked by building the heads named above.


Generated by Claude Code

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