Skip to content

feat: Build Arrow arrays from the integer, real and NULL columns of a result - #859

Draft
krlmlr wants to merge 14 commits into
claude/arrow-vendor-nanoarrowfrom
claude/arrow-numeric-columns
Draft

krlmlr wants to merge 14 commits into
claude/arrow-vendor-nanoarrowfrom
claude/arrow-numeric-columns

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Fourth step of the Arrow rework (plan: #829 (comment)), and the first piece of the internal Arrow engine: fetch up to n rows of a result into a nanoarrow struct array, for columns whose values are integers, reals or NULL. The entry point is internal; no DBI method calls it until pull request 16 of the plan, so nothing changes for users.

What changes:

  • result_fetch_arrow_chunk(res, n), registered through cpp11 and not exported, returns a nanoarrow_array of a struct type, with its schema in the tag of the external pointer as the nanoarrow package expects. It holds at most n rows, or all remaining rows for n = -1. Other values are refused: a chunk of no rows would have to fix the column types without seeing a value. The fetch runs under the busy guard of fix: Never restart a statement after an error in dbFetch() or dbBind() #830, like dbFetch(), and fails like it for an inactive or unbound result.
  • The first commit is a refactor without change of behavior: the loop of fetch_rows() moves into the member template fetch_loop(), which takes the rows to fill and a function that completes them. Data-frame fetches and Arrow fetches both run through it, so the Arrow fetch has fix: A fetch returns its rows when the step past its last row fails #850's one-row read-ahead (the row stepped past the last row of a full chunk is the first row of the next chunk, and a chunk that returns the last row completes the result and releases its read lock), fix: Never restart a statement after an error in dbFetch() or dbBind() #830's error semantics (an error of that step is kept and raised by the next fetch, and any error that leaves the fetch, including one from building the arrays, completes the result), and dbGetRowCount() counting rows once they are returned.
  • SqliteArrowColumn builds the child array of one column. The type comes from the first value that is not NULL: int64 for an integer, double for a real. An int64 column widens to double when a real arrives later in the same chunk, as the default path widens integers. A column whose values in the first chunk are all NULL takes the type of its declared affinity: int64 for INTEGER, double for REAL and NUMERIC (which includes unknown declared types), and the null type without a declared type, as for an expression. The first chunk of an execution fixes the types for its later chunks: there, a real in an int64 column is truncated toward zero, or NULL beyond the range of int64 where SQLite would saturate, and a value in a column of the null type is NULL. A new dbBind() starts a new execution, whose first chunk decides again.
  • DbArrow.h holds check_arrow(), which turns a nanoarrow error code into a C++ exception, so that the arrays under construction are released on every error. SqliteResultImpl.h only declares the Arrow types, so that the nanoarrow headers are compiled only where arrays are built (SqliteArrowColumn.cpp, SqliteResultImpl.cpp, result.cpp).
  • DESCRIPTION adds nanoarrow (>= 0.4.0) to LinkingTo, for the header-only helpers of nanoarrow/r.h that create the external pointers with the class and the finalizer the nanoarrow package expects, and to Suggests, for the tests. 0.4.0 is the first version that ships r.h; 0.3.0.1 has only r_nanoarrow.h. Nothing more is needed from it: looking into the returned array from R needs the nanoarrow package loaded, which the tests do through nanoarrow::. Through LinkingTo, nanoarrow is now needed to build the package.

DbArrow.h and SqliteArrowColumn.* come from #795 at 43db19f with its refinements up to 3436358, cut down to int64, double and the null type. The data-frame mode, ArrowTarget, CoercionLog, the byte limits, ProgressValue and the SqliteColumnDataSource member are left out, and so is the split of read_row() from append_row() that only the byte limits need. The truncation of a real in a fixed int64 column follows integer_value() of 3436358. The struct array is assembled in the shared fetch loop instead of a loop of its own.

Mixing data-frame and Arrow fetches on one result stays undecided (#829 (comment)), and the entry point neither refuses nor supports it on purpose. What happens today: each fetch continues at the next row of the result, whichever kind came before, so no row is lost or read twice, and dbHasCompleted() and dbGetRowCount() follow both. Each path types its columns on its own: the first Arrow chunk of an execution fixes the Arrow types, dbFetch() keeps its types as before, and neither sees the other's. Nothing is handed from one path to the other, because nothing reads ahead by more than the one row that both share; the question becomes concrete with the byte cut (pull request 8) and the schema read-ahead of streams (pull request 9).

Where the values differ from dbFetch(): integers are int64, which nanoarrow converts to double unless asked for integer64; a column without declared type and only NULL values is of the null type rather than logical; later chunks keep the types of the first one, where dbFetch() widens integers again in a later fetch; and an int64 column that holds a value beyond 2^31 widens to double when a real arrives, where dbFetch() keeps integer64 and truncates the real with a warning. The tests pin each of these.

Deliberately left out:

  • Text and blobs come in pull request 5. Until then, a text or blob value fails the fetch with "Column x: Arrow arrays of text and blobs are not supported yet.", which completes the result like any other error. So does a column of NULL values declared as TEXT or BLOB, which would otherwise need a type that pull request 5 changes.
  • extended_types is not consulted until pull request 6: a DATE, TIME or TIMESTAMP column comes through as the numbers it stores, as double if it holds only NULL (by its NUMERIC affinity), and text dates fail as text.
  • The conversions in later chunks are silent until pull request 7 reports them once per chunk with their rows.
  • Byte limits (pull request 8), streams (pull request 9), requested types (pull requests 13 and 14) and the DBI methods (pull request 16) come later. The row count stays 32-bit, as on main; counting in 64 bits is a separate pull request.

Tested:

  • New tests/testthat/test-arrow-columns.R with fixtures in tests/testthat/helper-arrow.R: integer, real and NULL columns; the first-value rule; widening within a chunk, also from beyond 2^53; the types fixed by the first chunk; the affinity of all-NULL columns (INTEGER, REAL, NUMERIC, none, and an expression); int64 values beyond 2^53 and up to 2^63 - 1 kept exactly; chunks of 1, k and all rows up to past the end, and a chunk ending on the last row releasing the read lock for a writer on another connection; an empty result and a statement without columns; a step error (json() on invalid JSON, as in fix: A fetch returns its rows when the step past its last row fails #850's tests) after the rows of a chunk and among them; a busy handler that runs during the step past the last row of a chunk and can neither clear the result nor fetch from it; text and blob values and declared types failing the fetch and completing the result; a new execution deciding its types again; an unbound query and invalid n. Where the rules agree, a helper fetches the same query with dbFetch() in the same chunk sizes and compares the values, dbHasCompleted() and dbGetRowCount() after each chunk.
  • Each test_that() block passes on its own in a fresh session right after pkgload::load_all().
  • devtools::test() with NOT_CRAN=true: no failures beyond the three errors in test-httpvfs.R that also happen on main (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 refactor commit alone passes test-read-ahead.R, test-dbSendQuery.R, test-dbClearResult.R, test-error.R, test-dbBind.R and test-basic-types.R.
  • Under AddressSanitizer (gcc, -O1), the new tests and test-read-ahead.R, test-dbSendQuery.R, test-dbClearResult.R, test-error.R and test-dbBind.R pass without a report, and so does a script with chunks of several sizes, widening, a text error, rebinding, and arrays converted after their result was cleared and the connection closed, also under gctorture(TRUE).
  • The code compiles against the r.h of nanoarrow 0.4.0, and the Arrow tests pass with nanoarrow 0.4.0 installed as well as with 0.9.0.
  • arrow 26.0.1's ValidateFull() accepts chunks with int64, double and null columns (checked by hand; arrow is not a test dependency here).
  • R CMD check --no-manual: Status OK.

Sits on #857, which is on #856, #855, #830 and #850.

Size

About 530 hand-written lines of C++ and 405 lines of tests, above the plan's target of 600 in all; splitting off the 16-line fetch_loop() refactor or the later-chunk rules would save little, so the pull request is kept whole, and its commits can be read one at a time.

Review

The clean review found nothing above Low; two points are fixed in 9251a64 and d912dbc, and the rest are listed in the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

`fetch_rows()` keeps building the data frame,
and hands the loop over the rows to the new member template `fetch_loop()`,
which takes the rows to fill and a function that completes them.
The loop is the one of a data-frame fetch:
the one-row read-ahead, the kept error of the step past the last row,
the completion of the result by any error that leaves the fetch,
and the count of fetched rows once they are returned.
The next commit fills Arrow arrays through it.

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

The internal `result_fetch_arrow_chunk()` fetches at most `n` rows of a result,
all of them for -1, into a nanoarrow struct array with its schema.
It runs under the busy guard of `dbFetch()`,
and reads the rows through the same loop as a data-frame fetch,
so the one-row read-ahead, the kept step error,
the completion of the result by any error and `dbGetRowCount()` apply as they do there.
No DBI method calls it yet.

`SqliteArrowColumn` types a column from its first value that is not NULL,
int64 for an integer and double for a real,
and widens int64 to double when a real comes later in the same chunk.
A column of NULL values takes the type of its declared affinity,
or the null type without one.
The first chunk of an execution fixes the types for the later chunks,
where a real in an int64 column is truncated, or NULL beyond the range of int64,
and a value in a column of the null type is NULL.
A text or blob value, or a column of NULL values declared as text or blob,
fails the fetch until text and blob arrays are built.

The arrays are returned with the helpers of `nanoarrow/r.h`,
so nanoarrow joins `LinkingTo`, and `Suggests` for the tests.

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 90753dc, by a Claude Code reviewer with clean context that read the description, the two commits against #857 (40678e2..90753dc), the fetch loop and busy guard around them, the new tests and helpers, and the old SqliteArrowColumn code with integer_value() at 3436358; built the head, the base and the refactor commit on its own; and ran the tests, an AddressSanitizer build, valgrind, arrow's ValidateFull() and reproducers of its own that compare with dbFetch(). I posted nothing myself.

What was run

  • R CMD INSTALL of 90753dc and 40678e2 into separate libraries, with nanoarrow 0.9.0 and arrow 26.0.1.
  • test-arrow-columns.R on the head (107 expectations pass) and on the base (all 15 blocks fail, the entry point is missing); each of the 15 test_that() blocks alone in a fresh session right after pkgload::load_all(): all pass.
  • devtools::test() with NOT_CRAN=true: only the three test-httpvfs.R errors. 45cf73b alone: test-read-ahead.R, test-dbSendQuery.R, test-dbClearResult.R, test-error.R, test-dbBind.R, test-basic-types.R, test-dbFetch.R and DBItest without failure.
  • R CMD check --no-manual: Status OK; with NOT_CRAN=true, only the httpvfs errors and the 1 GB blob test, which ran out of disk here.
  • A gcc AddressSanitizer build (-O1): the full suite, and scripts with chunks of 1, k and all rows, widening after 3000 rows, text errors in the middle of a chunk and in finish_chunk(), step and kept errors, rebinding, an R error from check_user_interrupt() in the middle of a chunk (through setTimeLimit()), and arrays converted after dbClearResult() and dbDisconnect(), also under gctorture(TRUE): no report. valgrind on the same paths: 0 bytes definitely lost.
  • dbGetQuery() of 1e6 rows, dbFetch(n = 1000) over them and 30000 calls of dbFetch(n = 1), base against head, interleaved: medians within noise (0.37 to 0.39 s for the first on both).

What holds

  • arrow's Table$ValidateFull() accepts every chunk I built: lengths, null counts, validity bitmaps, the null type (no buffers, null count equal to length), int64 exact at INT64_MIN, INT64_MAX and beyond 2^53, doubles at ±1e308 and ±Inf. NaN cannot reach a row, SQLite stores it as NULL.
  • Widening int64 to double within a chunk gives exactly the values of dbFetch(), also after 5000 rows with NULLs. In a fixed int64 column a real is truncated toward zero, -2^63 is kept, and 2^63, values below -2^63 and ±Inf become NULL, as described and as integer_value() of 3436358 does.
  • The first commit is mechanical: the read-ahead row, the kept error, the completion of the result on any error, the row count and the release of the read lock behave as before, without a change in speed.
  • For Arrow chunks, the read-ahead row, kept errors, dbHasCompleted(), dbGetRowCount(), rebinding and the busy guard (also against a call from a warning handler of dbFetch()) behave as described; an aborted chunk completes the result and releases its read lock.
  • Mixing dbFetch() and Arrow chunks on one result loses and repeats no row, a kept error is raised by the other path, and each path keeps its own types, as the description says.
  • n of 0, -2, NA and Inf are refused, non-integers by cpp11; a cleared, replaced or disconnected result gives "Invalid result set".
  • The vendored nanoarrow wins over the LinkingTo path (-Ivendor comes first, and the package ships only r.h), its symbols carry the RSQLite prefix, there are no new compiler warnings, and no src/*.dd gains absolute paths.

High

None.

Medium

None.

Low

  1. LinkingTo: nanoarrow has no minimum version, and nanoarrow before 0.4.0 has no nanoarrow/r.h.

    RSQLite/DESCRIPTION

    Lines 65 to 67 in 90753dc

    LinkingTo:
    cpp11 (>= 0.4.0),
    nanoarrow
    With nanoarrow 0.3.0.1 installed, which ships only r_nanoarrow.h, building this head fails with result.cpp:5:10: fatal error: nanoarrow/r.h: No such file or directory (Confirmed); the four helpers used are in r.h with the same signatures from 0.4.0 on (by reading the 0.4.0 and 0.7.0 sources). Suggested fix: nanoarrow (>= 0.4.0) in LinkingTo, so that R reports the version instead of a compiler error; or drop the build dependency by creating the two external pointers in RSQLite, which takes about 30 lines.

  2. Arrays outlive their result and connection, but not RSQLite's DLL.

    RSQLite/src/result.cpp

    Lines 53 to 63 in 90753dc

    }
    // Allocated before the fetch, so that a failed allocation loses no rows
    cpp11::sexp array_xptr(cpp11::safe[nanoarrow_array_owning_xptr]());
    cpp11::sexp schema_xptr(cpp11::safe[nanoarrow_schema_owning_xptr]());
    res->fetch_arrow_chunk(
    nanoarrow_output_array_from_xptr(array_xptr),
    nanoarrow_output_schema_from_xptr(schema_xptr),
    n
    );
    // The schema of a nanoarrow_array lives in the tag of the external pointer
    R_SetExternalPtrTag(array_xptr, schema_xptr);
    and

    RSQLite/R/zzz.R

    Lines 5 to 8 in 90753dc

    .onUnload <- function(libpath) {
    gc() # Force garbage collection of connections
    library.dynam.unload("RSQLite", libpath)
    }
    The finalizer of the external pointer (a static function of r.h) and the release callback of the array both live in RSQLite.so, which .onUnload() unloads, and its gc() cannot collect a chunk that is still referenced. A chunk kept across detach("package:RSQLite", unload = TRUE) segfaults at the next gc() (Confirmed); so would, by reading, a reload by pkgload::load_all() and an array imported into arrow. A connection kept across the unload crashes the same way, so the mechanism is not new, but arrays are made to be kept and handed on. Suggested fix: decide before the stream and DBI pull requests of the plan whether .onUnload() keeps unloading the DLL, or note the limit there.

  3. SqliteResultImpl.h pulls nanoarrow.h and nanoarrow.hpp into DbResult.cpp and SqliteResult.cpp, which use none of it.

    #include <boost/ptr_container/ptr_vector.hpp>
    #include <boost/scoped_ptr.hpp>
    #include <boost/shared_ptr.hpp>
    #include "sqlite3-cpp.h"
    #include "DbColumnDataType.h"
    #include "SqliteArrowColumn.h"
    It causes no conflict and no warning (Confirmed by the build). Because the destructor of SqliteResultImpl is out of line, replacing the include with class SqliteArrowColumn; and including the header in SqliteResultImpl.cpp instead compiles for all four affected files (Confirmed with -fsyntax-only). Suggested fix: forward-declare, so that the nanoarrow headers stay in the two files that use them.

  4. A column without declared type whose first chunk holds only NULL becomes the null type, and every later value of it is dropped without a word.

    ARROW_KIND SqliteArrowColumn::kind_from_decltype() const {
    const char* decl_type = sqlite3_column_decltype(stmt, j);
    if (decl_type == NULL) {
    return AK_NA;
    }
    and
    case AK_NA:
    append_null();
    break;
    With a first chunk of one row whose value is NULL, the values 2, 3.5, 9007199254740993 and -1 of the later chunks all come back NULL (Confirmed). This is the documented rule and a test pins it, but expressions, the common case without a declared type, lose whole columns this way, where dbFetch() types each fetch anew. Suggested fix: nothing to change for this internal step; the plan's reports of conversions (pull request 7) and schema read-ahead (pull request 9) should cover it, or the chunk could fail instead of dropping values until they land.

  5. The internal entry point, like result_fetch(), takes any external pointer for a result.

    template <typename T>
    enable_if_dbres_ptr<T> as_cpp(SEXP x) {
    DbResultPtr* result = (DbResultPtr*)(R_ExternalPtrAddr(x));
    if (!result || !result->get()) {
    cpp11::stop("Invalid result set");
    }
    return result->get();
    result_fetch_arrow_chunk(con@ptr, 1L) gives an AddressSanitizer heap-buffer-overflow in scoped_ptr<SqliteResultImpl>::operator->, exactly as result_fetch(con@ptr, 1L) does (Confirmed); NULL and other objects that are not external pointers are refused by R_ExternalPtrAddr(). It is inherited and internal. Suggested fix: in a separate pull request, check the class or tag of the pointer in as_cpp<DbResult*>().


Generated by Claude Code

nanoarrow 0.3.0.1 ships only `r_nanoarrow.h`, so building against it fails in the compiler.
From 0.4.0 on, `r.h` has the four helpers that `result_fetch_arrow_chunk()` uses,
and the Arrow tests pass with nanoarrow 0.4.0 installed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The header declares `SqliteArrowColumn`, `ArrowArray` and `ArrowSchema` instead of including them,
so that `DbResult.cpp` and `SqliteResult.cpp` no longer compile the nanoarrow headers.
`SqliteResultImpl.cpp` includes `SqliteArrowColumn.h` itself,
and the dependency lists of the two other objects are back to those of the base.

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: arrow's ValidateFull() accepted every chunk (int64 at its limits and beyond 2^53, ±Inf, the null type, widening within a chunk), AddressSanitizer and gctorture() were clean, the data-frame path is unchanged in results and speed, and mixing data-frame and Arrow fetches loses or repeats no row. Two Lows are fixed: nanoarrow (>= 0.4.0) in LinkingTo and Suggests (9251a64, the first version with nanoarrow/r.h, tested with 0.4.0), and SqliteResultImpl.h only declares the Arrow types (d912dbc). #857's head 62e252d is merged in. These remain:

  • src/SqliteArrowColumn.h#L16-L21: a column without a declared type whose first chunk holds only NULL becomes the null type, and values in later chunks of that column are dropped without notice; other values that do not fit the types of the first chunk are converted silently too. The rule is documented and pinned by a test; pull request 7 reports such conversions, and pull request 9 reads ahead for a stream's schema. Relevance: medium (internal entry point only until pull request 16); reviewer's confidence: high.
  • src/result.cpp#L50: an Arrow chunk kept after detach("package:RSQLite", unload = TRUE) crashes R at the next garbage collection, because its release callback lives in RSQLite's library; a connection kept across the unload crashes the same way already. Relevance: low; reviewer's confidence: high.
  • src/result.cpp#L50: the internal entry point, like result_fetch(), accepts any external pointer as a result; a connection's pointer reads out of bounds. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: keep values that arrive after the first chunk has typed their column as null?

The first chunk of an execution fixes the Arrow types for its later chunks (src/SqliteArrowColumn.h#L16-L21). A column without a declared type whose first chunk holds only NULL becomes the null type, and values in its later chunks are dropped without notice. Other values that don't fit the type of the first chunk are converted silently too, such as a real in an int64 column, which is truncated. The rule is documented there and pinned by a test. Against this pull request's head:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
# A column without a declared type, NULL in the first chunk
res <- dbSendQuery(con, "
  WITH t(i) AS (VALUES (1), (2), (3), (4))
  SELECT CASE WHEN i > 2 THEN i END AS x FROM t
")
chunk <- RSQLite:::result_fetch_arrow_chunk(res@ptr, 2L)
nanoarrow::infer_nanoarrow_schema(chunk)$children$x$format
#> [1] "n"
# The later chunk keeps the null type: 3 and 4 become NULL without notice
# (expected: the values 3 and 4, or a warning)
nanoarrow::convert_array(RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L))
#>    x
#> 1 NA
#> 2 NA
dbClearResult(res)
dbDisconnect(con)

Kirill decides. If nobody decides, the rule stays as it is until #862, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: keep Arrow chunks valid after RSQLite is unloaded?

An Arrow chunk kept after detach("package:RSQLite", unload = TRUE) crashes R at the next garbage collection, because its release callback lives in RSQLite's shared library, which .onUnload() unloads (src/result.cpp#L50). A connection kept across the unload crashes the same way already. Against this pull request's head:

# Run in a separate R process because it crashes
res <- try(callr::r(function() {
  library(RSQLite)
  con <- DBI::dbConnect(RSQLite::SQLite())
  rs <- DBI::dbSendQuery(con, "SELECT 1 AS x")
  chunk <- RSQLite:::result_fetch_arrow_chunk(rs@ptr, -1L)
  DBI::dbClearResult(rs)
  DBI::dbDisconnect(con)
  detach("package:RSQLite", unload = TRUE)
  # Expected: the chunk is released without a crash
  rm(chunk)
  gc()
  "survived"
}, libpath = .libPaths()), silent = TRUE)
cat(attr(res, "condition")$stderr)
#> 
#>  *** caught segfault ***
#> address 0x7ff09a075d10, cause 'memory not mapped'
#> An irrecoverable exception occurred. R is aborting now ...
  • Accept it, as for connections: unloading a package with live objects is rare (recommended)
  • Keep RSQLite's shared library loaded while a chunk exists, for example by skipping library.dynam.unload() in .onUnload() then

Kirill decides. If nobody decides, the behavior stays, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review found nothing above Low: arrow's ValidateFull() accepted every chunk (int64 at its limits and beyond 2^53, ±Inf, the null type, widening within a chunk), AddressSanitizer and gctorture() were clean, the data-frame path is unchanged in results and speed, and mixing data-frame and Arrow fetches loses or repeats no row. Two Lows are fixed: nanoarrow (>= 0.4.0) in LinkingTo and Suggests (9251a64, the first version with nanoarrow/r.h, tested with 0.4.0), and SqliteResultImpl.h only declares the Arrow types (d912dbc). These remain:

  • src/SqliteArrowColumn.h#L16-L21: a column typed as null by its first chunk drops the values of later chunks, and other values that don't fit the types of the first chunk are converted silently (question). Relevance: medium (internal entry point only until pull request 16); reviewer's confidence: high. (recorded)
  • src/result.cpp#L50: an Arrow chunk kept after RSQLite is unloaded crashes R at the next garbage collection (question). Relevance: low; reviewer's confidence: high.

A finding that main already shows:


Generated by Claude Code

The first data frame fetch or Arrow fetch of a result claims it,
and a fetch of the other kind then fails with an error of class `RSQLite_error_fetch_kind`.
The claim holds across `dbBind()`.
`dbFetch(n = 0)`, `dbColumnInfo()` and the state of the result read no rows and stay allowed.

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

krlmlr commented Nov 30, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: should the fetch loop take its rows through a virtual row sink, as RPostgres does since r-dbi/RPostgres#638?

Outcome: the maintainer asked to rebuild the chain from main with bug fixes first, then refactorings such as a virtual row consumer, then the features; this pull request moves to draft, and the rebuilt chain is coordinated on #880.

The stack does not build on virtual methods for consuming rows. This pull request introduces SqliteResultImpl::fetch_loop() as a template over a duck-typed Rows (src/SqliteResultImpl.cpp#L436-L442, declared in src/SqliteResultImpl.h#L100-L101): takes_row(), set_col_values() and advance(), plus a finish lambda. Its two consumers share no base class: SqliteDataFrame gets a non-virtual takes_row() that always says yes, and ArrowChunk (#L34-L111) refuses a row whose text or blobs would pass the 2^31 − 1 byte limit of a utf8 or binary column, so that the row starts the next chunk. main has no such seam either; its only virtuals read values (DbColumnDataSource). RPostgres merged a virtual PqRowSink in r-dbi/RPostgres#638 (begin() with the column cache, append(const PGresult*), remaining()), with the data frame as its first sink.

A virtual SqliteRowSink would make the seam match RPostgres's, so that an Arrow chunk, a data frame, and later the sinks of #881 plug in the same way across the backends, and fetch_loop() stops being a template in the header. RSQLite's sink needs one hook more than PqRowSink: a way to refuse a row without an error (takes_row()), for the byte limit. The cost is one virtual call per row and value, small next to sqlite3_step(), and a reshuffle of #859 to #864 while they are in review. Doing it in a layer of its own below #859, which routes the data-frame fetch through the sink first, as r-dbi/RPostgres#638 did, keeps #859's diff to the Arrow sink.

If nobody decides, the template stays. Nothing starts before the current simplification of #859 to #864 (no mixed data-frame and Arrow fetches) is pushed, since both touch the same lines.


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