Skip to content

refactor: Fetch rows through a pluggable row sink - #638

Merged
krlmlr merged 4 commits into
mainfrom
claude/fetch-row-sink
Nov 29, 2026
Merged

krlmlr merged 4 commits into
mainfrom
claude/fetch-row-sink

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

This PR turns PqResultImpl::fetch_rows() into a fetch loop, PqResultImpl::fetch_into(PqRowSink& sink), that feeds a pluggable row sink (PqRowSink, new in src/PqRowSink.h). The loop checks that the query is bound and drives step(), the parameter groups from dbBind(), the interrupt check every 1024 rows, completion, and the "Don't need to call dbFetch() for statements" warning. The data frame builder becomes the first sink. PqDataFrameSink is a thin adapter that owns a PqDataFrame and acts as its result source. It is not a subclass, because peek_first_row() keeps using PqDataFrame with PqResultImpl as the source. fetch_rows() builds that sink, calls fetch_into(), and adds the oids as before. The behavior is meant to stay exactly the same.

Why: this is the seam that native Arrow fetch (#631) and ALTREP result columns (#632, phase 0 of design/altrep-columns.md) share. Each of them adds another sink later. This PR adds no Arrow or ALTREP code.

The interface contract, documented in src/PqRowSink.h:

  • begin(names, oids, fmods, types) runs once per fetch_into() call, before the first append(). It gets the column cache as the last step() left it. The column cache now also stores PQfmod(), taken from the first description of the columns. For a prepared query that is PQdescribePrepared(), and for an immediate query it is the first result with columns. Later results are still checked for the same names and OIDs only, so data frames behave as before (the open question is linked below). The cache is final at that point, with one exception. In an immediate multi-statement query whose first row-bearing result has no columns, a later statement fills the cache during the loop. The arguments refer to that live cache, so the sink copies what it needs in begin(). The data frame sink keeps zero columns in that case, which is the existing behavior, and a new test in test-immediate.R pins it.
  • append(const PGresult* res) gets every row-bearing result whole. Today each result holds exactly one row (single-row mode). The loop owns res and clears it right after the call, so the sink copies what it needs and keeps no pointer into it. A TODO records that chunked rows mode needs fetch_into() to keep a row offset into the result, for example with append(res, first_row, n_rows), before PQsetChunkedRowsMode() is used. That is because the loop checks the limit only before each append(). PqDataFrameSink already reads every row of res: PqResultSource gained get_row(), PqColumnDataSource reads that row instead of row 0, and get_result() now returns const PGresult*.
  • remaining() returns how many rows the sink still accepts, or -1 for no limit. It is the only limit of the loop, so fetch_into() takes no n_max.
  • Sinks do not check for interrupts themselves. A sink may throw a C++ exception but must not longjmp past C++ objects, so it calls R through cpp11 or unwind_protect(). After a throw, the caller of fetch_into() discards the sink. If append() throws, the next fetch delivers that row again. If step() or the interrupt check throws, the rows already appended in that call count as fetched and are lost with the sink. That is the existing behavior.

What moved: the interrupt check left DbDataFrame::advance() and now sits in the loop. It runs at the same point as before, after step() and after the row count goes up. nrows_ now goes up by PQntuples() of each appended result, which is 1 today. The unused int& n out-parameter of fetch_rows() is gone.

Tests were run against a local PostgreSQL 16, on a private database. devtools::test() gives the same results before and after the change: all 9193 existing expectations pass, plus the 5 in the new test (which also pass against main), 11 are skipped (9 DBItest skips and 2 timezone tests that need another database), and nothing fails. A probe script covers the following, for prepared and immediate queries:

  • n = 0 / 3 / 1500 / -1, and n larger than the row count
  • dbHasCompleted() and dbGetRowCount() after each fetch
  • an error mid-fetch
  • statements and zero-column results
  • multi-statement immediate queries
  • three dbBind() groups, one of them empty, and a rebind
  • an unbound query
  • mixed column types

Its output is identical before and after the change, apart from the now() timestamp. The full suite and the probe also pass with the package built under AddressSanitizer and UBSan, with no reports. That run was at commit 26bf0aa. The last commit only changes comments and renames two local variables, and after it test-immediate.R and test-dbGetQuery.R pass again. The changed C++ lines are formatted with git clang-format against .clang-format, and the test with air. No R code changed.

Open question: what begin() receives. The PR implements the recommended option.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

`PqResultImpl::fetch_into()` now drives the fetch loop
(stepping through results and parameter groups, interrupt checks, completion)
and hands each row-bearing `PGresult` to a `PqRowSink`.
The data frame builder becomes the first sink, `PqDataFrameSink`,
a thin adapter that serves its own `PqDataFrame` as the result source.
Column data sources now read the sink's current row instead of row 0,
so a sink can take results with more than one row.
The interrupt check every 1024 rows moves from `DbDataFrame::advance()` into the loop.
Behavior is unchanged.

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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: what should begin() receive to describe the columns?

The agreed signature is begin(const PGresult* spec, const std::vector<DATA_TYPE>& types). For prepared queries, a natural spec is pSpec_, the result of PQdescribePrepared(). Immediate queries have no such description, though: pSpec_ is NULL for them, and the columns are known only from the first row-bearing result. The PR therefore passes pSpec_ ? pSpec_ : pRes_ (call site, contract). That pointer is NULL once an immediate query has completed. The cost is that the Arrow sink (#631) and the ALTREP sink (#632) must handle a NULL spec and get the column count from types. The data frame sink ignores spec, so nothing changes today. Kirill decides. If nobody decides, the PR takes the first option below; the change is being implemented now.

  • (recommended) Replace spec with the cached column description, begin(names, oids, fmods, types), with PQfmod() stored in the column cache as well. These values are never NULL, outlive the result, and are the same for prepared and immediate queries. The ALTREP session asked for this in its review and agreed to the signature change; the clean review found that the current fallback hands begin() a PGresult that the first step() clears.
  • Keep spec = pSpec_ ? pSpec_ : pRes_, document that it may be NULL and is valid only during begin(), and treat types as the source of the column count.
  • Replace spec with the cached names and oids only (begin(names, oids, types)), without fmods.
  • Pass spec only for prepared queries, and always NULL for immediate ones.

Generated by Claude Code

krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Compute No_NA from NA-producing cells, including NaN and integer overflow,
and keep all chunk and view state in R objects, so no C finalizer is needed.
Limit the new warnings to the new type mapping, to keep the legacy results identical.
Write the row sink against the begin() signature proposed on #638,
leave interrupt checks to fetch_into(), and amend the sink contract for chunked rows mode.
Chain fixed-size index blocks, note the _cache changes in phase 5,
drop the domain special case because the server reports base types,
and add an open question on fixing the type cache on the default path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T
`begin()` now receives the cached names, type OIDs, type modifiers, and R data types instead of a `PGresult`,
which was NULL for completed immediate queries.
The cache stores `PQfmod()` from the first result that describes the columns;
later results are still checked for names and OIDs only, so data frames behave as before.
`fetch_into()` checks that the query is bound and is limited by the sink's `remaining()` alone.
The header now documents when `begin()` runs, that each result holds one row today,
what chunked rows mode still needs, and how sinks handle interrupts and errors.
A new test pins the columns of an immediate query whose first statement has none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g
`begin()` refers to the live column cache, so a sink copies what it needs.
The type modifiers come from `PQdescribePrepared()` for prepared queries.
Only a throw from `append()` redelivers its row;
a throw from `step()` or the interrupt check loses the rows appended in that call.
Local column counts no longer shadow the cache member `ncols_`.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

These remain after two rounds of clean review and the ALTREP session's review. Each is documented in src/PqRowSink.h (recorded).

  • src/PqRowSink.h#L48: the interface doesn't support libpq 17 chunked rows mode yet. fetch_into() consumes whole PGresults, each holding one row today. A TODO records that a row offset has to be kept in fetch_into() before PQsetChunkedRowsMode() is used. Relevance: low until chunked mode is adopted. Confidence: high. (recorded)
  • src/PqRowSink.h#L29: typmods come from the first result, or from PQdescribePrepared() for a prepared query. They are not compared across dbBind() groups or statements, because comparing them would make SELECT 1::numeric(5,2) AS a; SELECT 2::numeric(6,2) AS a fail, which works today. The ALTREP session agreed. Relevance: low. Confidence: high. (recorded)
  • src/PqRowSink.h#L29: for an immediate multi-statement query whose first statement has no columns, begin() runs before the column cache is final. The header says when it runs, and tests/testthat/test-immediate.R pins today's behavior. Relevance: low. Confidence: high. (recorded)

Behavior that main already shows is not a limitation of this PR. Rows of the current call are lost when an interrupt or a step() error hits in the middle of a fetch, and the 1024-row interrupt check does not cancel the query. The ALTREP session is reproducing these and taking them to Kirill.


Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 12:15
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Describe the row sink exactly as #638 provides it:
begin() with names, OIDs, type modifiers, and types from the column cache,
fetch_into() without a row limit, and interrupt checks in the fetch loop.
Define NA-producing cells by the storage type's NA, including the legacy NAs,
grow the chained data and index blocks geometrically, and state the fixed cost per column.
Gate chunked rows mode on the build alone, with every sink adapted first,
and add the rules for duplicating views and the attributes the sink sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T
krlmlr added a commit to r-dbi/RMariaDB that referenced this pull request Nov 29, 2026
* refactor: Fetch rows into a pluggable row sink

MariaResultPrep::fetch_into() owns the fetch loop:
the bound check, stepping through the parameter sets, row counting and interrupt checks.
A MariaRowSink receives the column metadata in begin() and each row in append(),
through a MariaRowView over the bound result buffers.
The data frame builder becomes the first sink, MariaDataFrameSink,
and fetch() returns its data frame unchanged.
Modeled on r-dbi/RPostgres#638.

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

* test: Fetch past the initial rows across parameter sets

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

* docs: Correct MariaRowSink and MariaRow header comments

Note that MariaDataFrameSink is the known exception to the no-longjmp rule.
Describe where the `fields` metadata of begin() comes from.
Comment out the unused parameter names of the default begin().
Tighten the lifetime of the pointer returned by value_bytes().

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

* chore: Auto-update from GitHub Actions

Run: https://github.com/r-dbi/RMariaDB/actions/runs/46289260868

* test: Compare the fetched placeholder values portably across servers

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

---------

Co-authored-by: Claude <[email protected]>
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Resolve conflicts.

Resolves the conflict in `PqResultImpl::fetch_rows()`:
`main` now raises the "Don't need to call dbFetch() for statements" warning through `defer_warning()` (#669)
and dropped nothing else the row sink needs.
The warning moves into `fetch_into()` with `defer_warning()`,
and the unused row-count argument of `fetch_rows()` from `main` is not carried over.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

I merged main into the branch (94cd000). The only conflict was in PqResultImpl::fetch_rows(). main now raises the "Don't need to call dbFetch() for statements" warning through defer_warning() (#669), so that warning moved into fetch_into() and keeps using defer_warning(). The row-count argument that main added to fetch_rows() is never read, so I didn't carry it over.

The full test suite against PostgreSQL 16 with NOT_CRAN=true gives 9346 passed, 0 failed and 10 skipped.


Generated by Claude Code

@krlmlr
krlmlr merged commit 1b41143 into main Nov 29, 2026
9 checks passed
@krlmlr
krlmlr deleted the claude/fetch-row-sink branch November 29, 2026 19:49
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