Skip to content

feat: implement dbSendQueryArrow(), dbFetchArrow() and dbFetchArrowChunk() natively - #981

Draft
krlmlr wants to merge 8 commits into
claude/rb-arrow-requested-temporalfrom
claude/rb-dbi-arrow-fetch
Draft

krlmlr wants to merge 8 commits into
claude/rb-arrow-requested-temporalfrom
claude/rb-dbi-arrow-fetch

Conversation

@krlmlr

@krlmlr krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

For users: this is the first Arrow feature of the rebuilt chain that users see. dbSendQueryArrow(), dbFetchArrow(), dbFetchArrowChunk(), dbGetQueryArrow() and dbBindArrow() now have RSQLite's own methods, so DBI's defaults, which fetched data frames and converted them with nanoarrow, are no longer used. Rows go from SQLite into Arrow arrays directly through the chunk fetch of #954–#963 and the stream of #964–#966 and #978: integer columns are int32 or int64 as described below, reals double, text utf8, blobs binary, and with extended_types = TRUE dates, times and timestamps are date32, time64[us] and timestamp[us, UTC]. Values that a column's type changes raise the warnings of #961. dbReadTableArrow() goes through these methods via DBI's default. NEWS bullet; the user documentation is the new ?"SQLiteResultArrow-class".

Methods. dbSendQueryArrow() returns an SQLiteResultArrow, a DBIResultArrow with a result slot holding the SQLiteResult (the slot name that DBI's methods for DBIResultArrow use, so dbClearResult(), dbHasCompleted(), dbGetRowCount(), dbBind(), dbFetch() and friends work through them). It claims the result for Arrow fetches right away, also before a bind (new internal result_claim_arrow()), so a data-frame fetch of res@result fails with RSQLite_error_fetch_kind. dbFetch() on the Arrow result is DBI's method, which converts the whole stream for n = -1. dbFetchArrowChunk() returns the next chunk of at most 65536 rows (fetch_arrow_chunk_warn()), and a zero-row chunk of the same types once complete; its SQLite errors are RSQLite_errors with the call dbFetchArrowChunk(). dbFetchArrow() returns the lazy nanoarrow_array_stream of read_arrow_stream() over the remaining rows, 65536 rows per chunk; it can be read on another thread (#978). The schema argument stays internal (plan item 18); DBI's generics have no such argument.

Integer columns. The Arrow fetches of a dbSendQueryArrow() result type a column of integers as dbFetch() does, so that DBI's default path and DBItest's roundtrips keep their R integers: int32 when every integer of the first chunk fits into 32 bits (needs_64_bit()'s range, so -2^31 is int32 and NA in R as for dbFetch()), and otherwise by the connection's bigint, as dbFetch() plus convert_bigint() do: int64 for "integer64" (the default), int32 with NULL plus an out-of-range warning for "integer", double for "numeric" (promote_to_double()), and utf8 digits for "character". An all-NULL column declared INTEGER is int32, as for dbFetch(). A real in the first chunk still widens to double. The rule is SqliteArrowColumn::settle_integers(), applied in finish() of the first chunk; the mode comes from bigint through result_claim_arrow(). The cost of int32 by default, and a change from DBI's default methods, which converted the data frames of dbFetch() in chunks of 256 rows and kept such values: the first chunk fixes the type (#955), so an integer beyond 32 bits in a later chunk is NULL with the existing out-of-range warning (#961), and a real there is truncated with a warning; documented in NEWS and ?"SQLiteResultArrow-class" with CAST(x AS REAL) as the way out, and pinned by a test. DBItest has no tweak that lets its Arrow roundtrip tests accept int64 for integer columns: tweaks() has no such option, and test_arrow_roundtrip_one() compares with expect_identical() after a plain convert_array_stream(). With bigint = "character", text read as an integer warns as "converted to int64", and integers in later chunks of a utf8 column aren't counted as converted. Requested types (#979, #980) are unaffected, and the internal fetches (read_arrow_stream() and fetch_arrow_chunk_warn() on a dbSendQuery() result) keep int64, so the tests of the earlier layers are unchanged.

Lifetime of dbGetQueryArrow(). DBI's default clears the result on exit, which would end the lazy stream before it is read, per the implemented rule of #966 that clearing ends a stream (#966 (comment)). RSQLite's method instead hands the result over to the stream: the new internal result_drop_r_share() drops R's share of the result as its finalizer does, without clearing it, and the connection forgets it (conn@ref$result). The stream then holds the only share: the statement is finalized once the stream has been read to its end, has failed, or has been released, by its consumer or by R's garbage collector. Until then the statement keeps its read lock. Other queries on the connection don't close the result and don't warn, dbDisconnect() doesn't warn about it and leaves the database open for the stream (#966), and a stream read on a worker drops its share through #978's deferred list.

Warnings of a stream read on another thread. The warnings of chunks read on a worker are kept with the result and raised before R's next call on it (#978). After dbGetQueryArrow() hands the result over, no R call on it can come, so they were lost (found in review). Now, once R no longer holds a result (DbResult::drop_r_share(), also through its finalizer), its queued warnings and later ones go to a queue that its connection and every stream of the connection share (ArrowWarningQueue, under a mutex, as is the result's own queue now). They are raised once on R's main thread: before R's next query on the connection (send_query()), at R's next call on any result of the connection (flush_thread_warnings()), after dbDisconnect() has closed the connection (so a warning made an error leaves it closed), with the stream's next chunk read on the main thread, or when R's main thread releases any stream of the connection. The release takes them from the queue that the stream holds, so it doesn't depend on whether the garbage collector or another call has already dropped the stream's share of the result (round 2 found that dependency), and it works after the connection is gone. A warning raised during a release, which can't fail, is dropped if it is made an error, and an exiting handler around the release doesn't run; released by the garbage collector, they are top-level warnings. They are lost if none of these points comes, as when R drops the connection without another call, or when the last stream is released on a worker after dbDisconnect(): raising them from the connection's finalizer or from a destructor that may run inside other C++ code or on a worker isn't safe, so this loss is documented in NEWS and ?"SQLiteResultArrow-class" instead. The warnings name the column, not the statement.

Other DBI methods. dbColumnInfo() has a method for SQLiteResultArrow that gives the R types nanoarrow converts the Arrow types to, as as.data.frame() of the stream gives them (int32 as integer, int64 as double, binary as blob, the null type as logical); it reads the first chunk through a stream's schema if no fetch has, and the next fetch returns that chunk. show() has a method without side effects or errors, also while a worker reads. The Rd documents the methods' arguments, which R CMD check had flagged. dbGetStatement(), dbGetRowCount(), dbGetRowsAffected(), dbHasCompleted() and dbClearResult() work through DBI's methods for DBIResultArrow, and dbIsValid() through RSQLite's. The fetch-kind error now carries the call of the DBI method (rethrow()), as in "Error in dbFetch():". The docs say that dbFetchArrowChunk(), dbFetchArrow() and further streams share one cursor.

Parameters. params of dbSendQueryArrow() and dbGetQueryArrow() binds a list or data frame as dbBind() does, and any other value (a nanoarrow_array_stream, or anything nanoarrow::as_nanoarrow_array_stream() converts) through the Arrow bind path of #967–#971, as dbBindArrow() does. dbBindArrow() binds natively both for SQLiteResultArrow and for SQLiteResult. DBI documents params as "see dbBind()", and the Arrow path converts R vectors differently (#970: difftime units, no factor warning, int64 as INTEGER), so R values keep dbBind()'s conversions.

Other changes. The fetch-kind error now reads "Can't fetch a result as a data frame that is fetched as Arrow arrays." instead of "... after fetching it as Arrow arrays.", since a result of dbSendQueryArrow() is claimed before any fetch (snapshot of #954 updated). ?"RSQLite-conditions" names the calls of dbGetQueryArrow()'s errors and says that errors while a stream reads come from its consumer. Comments that called the internal functions unused by DBI methods are updated.

DBItest. The Arrow tests were already enabled (test_all()) and passed through DBI's defaults. They all run with the native methods, without new skips: test_arrow() has 153 tests, FAIL 0, SKIP 16 (the existing tweak and internal skips), 2760 expectations; the meta (incl. arrow_bind_* and arrow_stream_bind_*), result and connection suites pass too. A first version typed all integer columns as int64, which nanoarrow converts to double, and failed 11 roundtrip tests that expect the integer vectors they wrote; the integer rule above fixes them.

Tests in the new tests/testthat/test-arrow-dbi.R: types of each storage class, declared DATE and the null type, chunk and stream agreeing; chunk sizes of 65536, the zero-row chunk after completion with the same formats, dbHasCompleted() and dbGetRowCount() after each chunk and as a stream is read, a second stream after the end; params as unnamed list, unnamed data frame, nanoarrow stream by position and by name (a named stream for anonymous placeholders refused), dbBindArrow() returning invisibly, dbBind() on an Arrow result, dbBindArrow() on a dbSendQuery() result; failed binds and syntax errors leaving no open result; conversion warnings from a chunk and from a stream; an SQLite error after the first 65536 rows failing the stream for good and dbFetchArrowChunk() with an RSQLite_error; dbClearResult() ending a live stream, dbFetchArrow()/dbFetchArrowChunk() after clear, dbDisconnect() with an uncleared result warning while the stream reads on; dbGetQueryArrow() lifetime (other queries meanwhile without warning, the read lock blocking DROP TABLE until the stream ends, is released, or is collected, dbDisconnect() without warning and reading on); a dbGetQueryArrow() stream read on a worker thread; mixing with dbFetch(res@result) refused, also before an Arrow fetch (snapshot), DBI's dbFetch() converting; and a second dbSendQueryArrow() closing the first with a warning; integers that fit into 32 bits (also -2^31 and an all-NULL INTEGER column, compared with dbGetQuery()), integers beyond 32 bits with each bigint, an int32 column overflowing in a later chunk (chunk and stream, with the warning), and the internal fetches keeping int64; an integer beyond 32 bits and a real after the first chunk with the default bigint (NULL and 2, pinned as the current decision); warnings of a dbGetQueryArrow() stream read on a worker thread reaching R at release, at the next query, at a call on another result of the connection and in dbDisconnect(); dbColumnInfo() per bigint and the int32 rule, consistent with the converted data frame and keeping the first chunk; the other result methods with show() snapshots, also while a worker reads; warnings of a released stream after a gc() and another stream's call, after dbDisconnect() and the connection's collection, dbDisconnect() under warn = 2 leaving the connection closed, and a queued warning under warn = 2 failing a query before it runs; the "character" wording. Each test_that() block runs on its own after load_all() (188 expectations, also against the installed package). Full suite with NOT_CRAN=true: FAIL 0, WARN 3 (the zh_TW.UTF-8 locale is missing in the container), SKIP 64, PASS 14239 (#980: SKIP 64, PASS 14027); R CMD check --no-manual: 0 errors, 0 warnings (only the NOTE about the worktree's .git file).

Decisions worth a look by the maintainer, implemented as described: integer columns as int32 when the first chunk fits (and the NULL for later overflow that this costs), lists and data frames in params bound by dbBind()'s conversions rather than through nanoarrow, the claim for Arrow at dbSendQueryArrow() time with the reworded fetch-kind message, and the hand-over in dbGetQueryArrow(), whose stream keeps a read lock until it is read or released.

Plan item 16, a layer of the rebuilt chain planned in #880; based on #980 (item 14). Not ported from an old PR: the old chain had no DBI methods.

Coordinating session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4


https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4


Generated by Claude Code

…rowChunk()` natively

RSQLite's own methods for DBI's Arrow generics replace DBI's defaults,
which fetched data frames and converted them.
`dbSendQueryArrow()` returns an `SQLiteResultArrow` claimed for Arrow fetches,
`dbFetchArrowChunk()` fetches chunks of 65536 rows,
and `dbFetchArrow()` returns the lazy stream of `read_arrow_stream()`.
`dbGetQueryArrow()` hands its result over to the stream instead of clearing it,
so that the stream is readable once returned.
`dbBindArrow()` and a `params` value other than a list bind through the Arrow bind path.
DBItest's roundtrip tests that expect integer vectors back are skipped,
since integer columns are int64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
@krlmlr
krlmlr added this pull request to stack #928 December 1, 2026 15:19
The Arrow fetches of DBI's methods type a column of integers as int32
when every integer of the first chunk fits into 32 bits,
and otherwise by the connection's `bigint`, as `dbFetch()` does:
int64, int32 with NULL, double, or utf8 digits.
A later integer beyond 32 bits in an int32 column is NULL with a warning.
The internal fetches keep int64.
DBItest's roundtrip tests run again without skips.

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

krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the DBI Arrow methods return INTEGER columns as int32 or int64?

SQLite stores integers in 64 bits. Before this pull request, DBI's default Arrow methods went through dbFetch() and returned R integers for INTEGER columns whose values fit 32 bits, so the columns came back as int32. The native methods here infer the type from the first chunk instead. With int64 for every integer column, 11 DBItest roundtrip tests failed, because nanoarrow converts int64 to double; skipping them isn't allowed. So the native methods now follow dbFetch(): an INTEGER column whose first chunk fits 32 bits becomes int32, and a column with a larger value follows bigint (int64 for the default "integer64", double for "numeric", utf8 for "character"), see settle_integers(). The cost: a later chunk with an integer beyond 32 bits can't widen the fixed column, so that value becomes NULL with a warning. Internal fetches and requested types keep int64. This is a change from DBI's default methods, which went through dbGetQuery() and kept such values: with the default bigint, dbGetQueryArrow() and dbReadTableArrow() now return NULL for an integer beyond 32 bits after the first 65536 rows, and truncate a real that arrives after the first chunk (2.5 becomes 2), each with a warning. DBItest has no tweak that would let its Arrow roundtrip tests accept int64: they compare with expect_identical() after convert_array_stream().

  • int32 when the first chunk fits, else per bigint, as implemented: matches dbFetch() and DBI's defaults, DBItest passes, but large values in later chunks become NULL with a warning (recommended)
  • int64 always: no value lost, Arrow-native, but as.data.frame() gives doubles where users got integers before, and the DBItest roundtrip expectations would need a tweak in DBItest itself
  • int32 only for columns declared INT/INTEGER with small values in the first chunk, int64 for undeclared or computed columns: closer to the schema, but still lossy in later chunks

Kirill decides. Until then the first option stays as implemented.


Generated by Claude Code

claude and others added 4 commits December 1, 2026 15:45
…cost

Warnings of chunks read on another thread from a result that R no longer
holds, as after `dbGetQueryArrow()`, go to its connection.
R raises them before the next query on the connection, in `dbDisconnect()`,
at R's next call on any of its results, or when R's main thread releases
a stream.
NEWS and the docs say that the int32 default makes later integers beyond
32 bits NULL and truncates later reals, where DBI's default methods kept them,
and a test pins it.
`dbColumnInfo()` and `show()` get methods for `SQLiteResultArrow`,
the fetch-kind error names the DBI method,
and text read as an integer for `bigint = "character"` warns as int64.

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

The warnings of chunks read on another thread from a result that R no longer
holds go to a queue that the connection and its streams share.
The release of a stream on R's main thread takes them from its own share
of the queue, whatever the garbage collector or other calls dropped before,
and `dbDisconnect()` raises them after closing the connection.
Their loss when R drops the connection first is documented.
`dbColumnInfo()` on an Arrow result gives the R types of the Arrow types,
`show()` has no side effects,
and the Rd documents the arguments of the methods.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
NEWS and the Rd name the cases in which the warnings are lost,
a comment points to `DbConnection::orphan_queue()`,
and `show()` labels only the error of a read on another thread as such.

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants