Skip to content

fix: Validate blobs that are read into a text column - #799

Closed
krlmlr wants to merge 9 commits into
mainfrom
claude/elegant-tesla-mja103-blob-text
Closed

krlmlr wants to merge 9 commits into
mainfrom
claude/elegant-tesla-mja103-blob-text

Conversation

@krlmlr

@krlmlr krlmlr commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

When a column is typed as text from its first values and a blob turns up later, the blob was read with sqlite3_column_text() as a C string: it was silently cut at the first NUL byte, and bytes that are not UTF-8 were handed to R as a string marked UTF-8. A blob X'00ff' came back as "".

A blob in a text column is now read with sqlite3_column_blob() and sqlite3_column_bytes() and validated in fetch_string(). A blob that is well-formed UTF-8 without NUL bytes becomes the full string, an empty blob becomes "", and anything else becomes NA, with one warning per column and fetch that counts the replaced values, next to the existing mixed-type warning:

Column `x`: 2 blob values are not valid UTF-8 text, NA is returned
Column `x`: mixed type, first seen values of type string, coercing other values of type blob

Because sqlite3_column_text() is never called on a blob, the value keeps its storage class. A peek with dbFetch(res, n = 0) or dbColumnInfo(res) therefore no longer switches the check off for the next fetch of the same row, and in a UTF-16 database the blob is no longer transcoded before the check (X'6162' used to come back as "扡"). The peek itself does not warn about invalid blobs; the fetch that returns the row does, so each value is reported once. Both column warnings now pass their message as an argument rather than as a format, so a column name containing % is printed as is; on main, a column name containing %n aborted R (*** %n in writable segment detected ***).

Behavior change: a blob holding a NUL byte, such as a NUL-terminated C string stored with its terminator, now becomes NA with a warning, where main returned the string up to the NUL.

Text values are not checked and are read as before: text with an embedded NUL is still cut silently, and text that is not valid UTF-8 is still returned marked as UTF-8. The warning text for a non-ASCII column name is not marked as UTF-8, as in the existing mixed-type warning, and a peek still emits the mixed-type warning, so it appears twice for the same row, as on main. The validator lives in a new header src/utf8.h, shared with the Arrow path of #795; whether it moves into a .cpp file is an open question on #829.

The tests in tests/testthat/test-blob.R cover the malformed UTF-8 forms (overlong, surrogate, beyond U+10FFFF, truncated), a NUL-terminated C string, an empty blob, a fetch in chunks where a later chunk holds only blobs, a peek between two chunks, a UTF-16 database, and a column name containing %s%d.

No open issue covers this. The closed #439 is the related case of text coerced to 0 in numeric columns.

A clean review of 867813e found one Medium and six Low issues. The Medium and four of the Low ones are fixed in d26413c, which a second clean review confirmed without High or Medium findings; what remains is listed under Accepted limitations.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

A blob that turns up in a column typed as text was read as a C string,
so it was silently cut at the first NUL byte,
and bytes that are not UTF-8 were passed on as an R string marked UTF-8.
The bytes are now checked:
well-formed UTF-8 without NUL bytes becomes the full string,
anything else becomes NA with one warning per column that counts the values.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6

krlmlr commented Sep 27, 2026

Copy link
Copy Markdown
Member Author

Review of this PR at 65a0c07, by a Claude Code reviewer with clean context that read the diff against main and ran test-blob.R on a load_all() build of the branch. No findings.

Checked and found sound: the UTF-8 validator in src/utf8.h follows the RFC 3629 byte ranges and rejects overlong forms, surrogates, code points above U+10FFFF and NUL; fetch_string() in src/SqliteColumnDataSource.cpp reads the storage class before sqlite3_column_text(), so sqlite3_column_type() is never consulted after a conversion; the warning is raised once per column per fetch; test-blob.R passes.


Generated by Claude Code

@krlmlr

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Does rsqlite_is_utf8_string() need to be defined in a header?

Did the reviewer find no limitations?

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

No, it doesn't need to be. It is a header only so that this pull request and #795, whose Arrow path validates text with the same function, can each add the identical src/utf8.h and merge cleanly in either order; inline is what lets two translation units include the definition. A declaration in utf8.h with the definition in a new src/utf8.cpp works just as well and fits the repository better: the only other function defined in a header under src/ is the one-line INTEGER64(). The extra call per validated value is negligible next to the loop over its bytes. Moving it means the same change on #795 and a merge up the Arrow stack, so I've posted it as a question on #829.

On limitations: the only review of this pull request is the one above, from 2026-09-27 at 65a0c07. It read the diff and ran test-blob.R, found nothing, and so left nothing to accept. That is a thin review for a change to the C++ fetch path, and I didn't run another one in this round when I should have. A fresh clean review of the current head (867813e) is starting now; its findings, the fixes, and an "Accepted limitations" comment will follow here.


Generated by Claude Code

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review of this PR at 867813e, by a Claude Code reviewer with clean context that read the full diff against main and the surrounding fetch code (DbColumn, DbColumnStorage, DbDataFrame, SqliteColumnDataSource, SqliteResultImpl), built the branch and main, ran probe scripts against both, compared the validator exhaustively with an independent reference decoder under ASan/UBSan, ran devtools::test() and R CMD check --no-manual, and posted nothing itself.

Line numbers refer to commit 867813e. "Confirmed" means reproduced by running code; "by reading" means not run.

What holds. All of the following are Confirmed.

  • The validator in src/utf8.h agrees with an independent decode-and-check reference on every byte sequence of length 0 to 3 and on all 2^31 four-byte sequences with a lead byte >= 0x80 (zero mismatches, exactly 1,048,576 valid four-byte forms). Overlong forms, surrogates, values above U+10FFFF, truncated sequences and NUL are rejected.
  • Through R, 182,318 crafted blobs (all 1- and 2-byte sequences, boundary 3- and 4-byte ones) come back as NA exactly when they are invalid; the valid ones round-trip byte-identically.
  • Chunked dbFetch(n = ) warns per chunk with the right count, because a new data source is created per fetch call. dbBind() with several parameter sets, a rebind, two columns, NULLs, empty blobs (X'' gives ""), zeroblob(), integers and reals in a text column, extended_types columns, options(warn = 2) and a 50 MB blob (0.3 s) all behave as described.
  • The new test fails on main ("" and "\xff" instead of NA).
  • devtools::test() gives 4 failures that are identical on main and environmental: three test-httpvfs.R tests need network, and test-dbConnect.R:159 needs an installed RSQLite in a callr subprocess. R CMD check --no-manual on the built tarball gives 0 errors, 0 warnings, and 1 NOTE that is an artifact of checking from a git worktree (.git file).

High

No findings.

Medium

M1. dbFetch(res, n = 0) or dbColumnInfo(res) on a pending blob row turns the fix off for that row. src/SqliteColumnDataSource.cpp#L88-L92

peek_first_row() runs set_col_values() on the current row without stepping, so fetch_string() calls sqlite3_column_text() on the blob. SQLite then marks the value as text in place, which is exactly the hazard the new comment mentions. The next real fetch reads the same row, sees SQLITE_TEXT, and takes the old Rf_mkCharCE() path.

Confirmed with:

con <- dbConnect(SQLite())
dbExecute(con, "CREATE TABLE t (x)")
dbExecute(con, "INSERT INTO t VALUES ('a'), (X'00ff'), (X'6162')")
res <- dbSendQuery(con, "SELECT x FROM t")
dbFetch(res, 1)
dbColumnInfo(res)   # or dbFetch(res, 0)
dbFetch(res)$x

The peek warns "1 blob value is not valid UTF-8 text, NA is returned" although it returns no rows. The last call then returns "" for X'00ff', not NA, with no invalid-UTF-8 warning. This is the old behavior of main, so it is an incomplete fix and not a regression.

Suggested fix: for a blob, do not call sqlite3_column_text() at all. Read the bytes with sqlite3_column_bytes() and sqlite3_column_blob(), which leave the storage class alone, then validate and build the string from those. I prototyped this in a scratch copy: the sequence above then returns NA "ab" with the warning. Pass "" rather than the NULL pointer that sqlite3_column_blob() returns for a zero-length blob. Please add a regression test with dbFetch(res, 0) between two chunks.

Low

L1. In a UTF-16 database the blob bytes are transcoded before validation. src/SqliteColumnDataSource.cpp#L89-L90

Confirmed. With PRAGMA encoding = 'UTF-16le', sqlite3_column_text() treats the blob as UTF-16 and converts it. X'6162' comes back as "扡", X'C3A4' as "꓃", X'61' as "", and X'00ff' as "＀", all without the new warning. The promise "a blob that is well-formed UTF-8 becomes the full string, anything else NA" does not hold there. main behaves the same way, apart from one value that is now NA. The fix suggested for M1 resolves this too: in the prototype the same data gives "ab" "ä" "a" NA NA.

L2. A column name is used as a printf format in the new warning. src/DbColumn.cpp#L105

Confirmed. cpp11::warning(const std::string&) takes a format string. SELECT x AS "ä%s%d" FROM t prints the warning as Column `ä<garbage>` , which reads variadic arguments that do not exist (undefined behavior). The existing mixed-type warning at line 85 has the same defect; the new code copies it. Suggested fix: cpp11::warning("%s", ss.str().c_str()) in both places.

L3. The warning text for a non-ASCII column name is passed as native-encoding bytes. src/DbColumn.cpp#L94-L105

Confirmed. The message is correct in a UTF-8 locale, though the condition message is not marked UTF-8. Under LC_ALL=C the name ä shows as <c3><a4>; in a Latin-1 locale it would be mojibake (by reading). This matches the existing mixed-type warning, so it is consistent, and it can be left for a separate change. The line cpp11::r_string name_utf8 = name; is a plain copy and converts nothing.

L4. The peek counts and warns for a row it does not return. src/DbColumn.cpp#L40

Confirmed, see M1. dbColumnInfo(res) and dbFetch(res, 0) emit "1 blob value is not valid UTF-8 text, NA is returned" for a row that is not part of their result. With M1 fixed, the same value is reported a second time by the fetch that returns it. The mixed-type warning already behaves like this. If it matters, skip warn_invalid_strings() when the data frame has zero rows.

L5. Blobs that hold a NUL-terminated C string now become NA. src/SqliteColumnDataSource.cpp#L98-L101

Confirmed. X'610062' returned "a" on main and returns NA now; by the same rule X'616200' changes from "ab" to NA (by reading). This follows from the description ("anything else becomes NA") and is warned about, so it is a deliberate change. It still breaks callers that store C strings with their terminator as blobs, and deserves an explicit line in the NEWS entry. Text values with an embedded NUL (CAST(X'610062' AS TEXT)) are still truncated silently to "a", and invalid text (CAST(X'ff' AS TEXT)) is still returned marked as UTF-8 (both Confirmed). The description says so, but the inconsistency between the two storage classes remains.

L6. Test coverage is narrower than the claims. tests/testthat/test-blob.R#L49-L77

By reading, plus the run on main. The test covers NUL, a lone 0xff, and one valid two-byte character. It does not cover:

  • an overlong form (X'C080'), a surrogate (X'EDA080'), a value above U+10FFFF (X'F4908080'), or a truncated sequence (X'E282');
  • an empty blob;
  • a fetch in several chunks, including a second chunk that consists only of blobs;
  • dbFetch(n = 0) between chunks (M1).

The values "ab" and "ä" also pass on main. The "no truncation" claim cannot be observed in any test, because a blob with a NUL byte is never valid, so Rf_mkCharLenCE() and Rf_mkCharCE() give the same result for every accepted blob.

Memory safety and the counter. No findings. The validator never reads past size, and it handles a NULL pointer with size 0. sqlite3_column_bytes() is called after sqlite3_column_text(), as SQLite requires. The mutable counter lives in the data source that all copies of a DbColumn share through a shared_ptr, and it starts at zero for every fetch call.


Generated by Claude Code

krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this comment.

The clean review of 867813e8 found one Medium and six Low issues. The Medium (a peek with dbFetch(res, 0) or dbColumnInfo() turns the fix off for a pending blob) and four of the Low ones (UTF-16 databases, the column name used as a warning format, the warning of a peek, test coverage) are being fixed. This list will be posted again once the fixes are pushed and reviewed. These remain:

  • src/SqliteColumnDataSource.cpp#L98-L101: a blob with a NUL byte, such as a NUL-terminated C string stored with its terminator, becomes NA with a warning, where main returned the string up to the NUL. This is deliberate, and the commit message states it so that the NEWS entry carries it. Relevance: medium; reviewer's confidence: high.
  • src/SqliteColumnDataSource.cpp#L91-L93: text values are read as before, so text with an embedded NUL is still cut silently and text that is not valid UTF-8 is still returned marked as UTF-8; only blobs are checked. Relevance: low; reviewer's confidence: high.
  • src/DbColumn.cpp#L94-L105: the warning text is passed as native bytes and not marked as UTF-8, so a non-ASCII column name shows as <c3><a4> under LC_ALL=C, as in the existing mixed-type warning; left for a separate change. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

A blob in a text column is now read with `sqlite3_column_blob()` and `sqlite3_column_bytes()`, then checked and turned into a string from those bytes.
`sqlite3_column_text()` changed the value to text in place, so after a peek with `dbFetch(res, n = 0)` or `dbColumnInfo(res)` the next fetch of the same row returned it unchecked, as before this pull request.
In a UTF-16 database it also transcoded the blob before the check, so `X'6162'` came back as `"扡"`.
An empty blob still gives `""`.

A blob holding a NUL byte, such as a NUL-terminated C string, now becomes `NA` with a warning, where it was truncated at the NUL byte before.
Text values are read as before and are not checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
A zero-row peek with `dbFetch(res, n = 0)` or `dbColumnInfo(res)` reads the next row without returning it.
It no longer warns about a blob in that row that is not valid UTF-8, so each value is reported once, by the fetch that returns it.
The warning about mixed types in a column is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The warnings about mixed types and about blobs that are not valid UTF-8 passed their message, which holds the column name, to `cpp11::warning()` as the format.
A name such as `x%s%d` printed garbage in its place, reading arguments that did not exist.
Both now pass the message through `"%s"`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The new tests cover the malformed UTF-8 forms (overlong, surrogate, beyond U+10FFFF, truncated) and a NUL-terminated C string, an empty blob, a fetch in chunks where a later chunk holds only blobs, a peek with `dbFetch(res, n = 0)` or `dbColumnInfo(res)` between two chunks, a UTF-16 database, and a column name that holds `%s%d`.

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

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review of the fixes at d26413c (the four commits after 867813e), by a Claude Code reviewer with clean context that read the pull request description, the review of 867813e8, the accepted limitations, the diff 867813e8..d26413c3, the full diff against main, and the fetch code around it (DbColumn, DbColumnStorage, DbDataFrame, SqliteResultImpl, plus sqlite3_value_blob() and sqlite3ValueBytes() in the bundled SQLite 3.54.1); built d26413c, 867813e and main and ran probe scripts against all three; ran the new test-blob.R against those three builds and against five builds that each undo one fix; ran devtools::test() and R CMD check --no-manual; ran test-blob.R and the probes under AddressSanitizer and UndefinedBehaviorSanitizer; and posted nothing itself. Line numbers refer to commit d26413c unless a link says otherwise. "Confirmed" means reproduced by running code; "by reading" means not run.

The earlier findings.

  • M1 (a peek turns the fix off): fixed. Confirmed. The sequence from the earlier review now returns NA "ab", whether the peek is dbFetch(res, 0) or dbColumnInfo(res). The invalid-UTF-8 warning is raised once, by the fetch that returns the row. 867813e and main return "" "ab". A blob now goes only through sqlite3_column_blob() and sqlite3_column_bytes(); sqlite3_value_blob() only adds MEM_Blob to the value's flags (by reading), so the value is still a blob after a peek.
  • L1 (UTF-16 databases): fixed. Confirmed in UTF-16le and UTF-16be. The values 'a', 'ä€', X'6162', X'C3A4', X'61', X'00ff', X'0061' and X'6100' come back as "a" "ä€" "ab" "ä" "a" NA NA NA with "3 blob values are not valid UTF-8 text". The result is the same after a dbColumnInfo() peek. In UTF-16le, main returns "扡" "꓃" "" "＀" "愀" "a" for the six blobs. Text values are still converted to UTF-8 as before.
  • L2 (column names used as format strings): fixed. Confirmed. The column names 100%%, x%s%d and a%%b%s appear unchanged in both warnings. The fix matters more than the description says: on main and at 867813e, SELECT x AS "x%n" FROM (SELECT 'a' AS x UNION ALL SELECT 1) aborts R with *** %n in writable segment detected ***; at d26413c it gives the normal warning.
  • L4 (the peek's warning): fixed. Confirmed. A peek no longer warns about invalid UTF-8, and each value is counted once, by the fetch that returns it. The peek still emits the mixed-type warning, and the fetch emits it again, as on main.
  • L6 (tests): fixed. Confirmed. The new tests cover every gap the earlier review listed, and each fix has a test that catches it: removing only the n == 0 early return gives 2 failures, in the peek test; putting back the fetch_string() of 867813e gives 6 failures, in the peek and UTF-16 tests; removing either "%s" gives 1 failure, in the format-string test. The new test-blob.R has 9 failures against 867813e and 17 against main. Only "an empty blob in a text column is an empty string" passes on all three builds, which is expected because it guards against a regression.

What else holds. Everything below is Confirmed unless marked otherwise.

  • sqlite3_column_blob() is called before sqlite3_column_bytes(), the order SQLite recommends. For a blob, sqlite3ValueBytes() returns the stored length without converting the value, so the pointer stays valid (by reading). The first call expands a zeroblob(): zeroblob(2) and zeroblob(5) give NA, and zeroblob(0) and X'' give "", also after a peek. The blob bytes are not NUL-terminated, and only calls that take a length read them: rsqlite_is_utf8_string() and Rf_mkCharLenCE() (by reading; no ASan report).
  • The n == 0 early return in warn_invalid_strings() cannot drop the warning of a real fetch (by reading). fetch_rows() reads values only inside its loop, and DbDataFrame::advance() raises the row count after every set_col_values(), so a fetch that read a value has n >= 1; n == 0 happens only in peek_first_row() and in a fetch after the result is complete, which reads nothing. If step() throws after a read, no data frame is built and no warning is raised, as before.
  • Text values take the same path as on main, sqlite3_column_text() then Rf_mkCharCE(), with one extra sqlite3_column_type() call. Fetching 4 million text values took 0.59 s at d26413c and 0.61 s on main (best of 7, measured twice each), so there is no measurable difference. Warnings for column names without % are unchanged.
  • Out of memory: with PRAGMA hard_heap_limit = 50000000, a zeroblob(100000000) in a text column now raises the error "out of memory"; on main the same query segfaults in Rf_mkCharCE(NULL). L7 below explains why the new code ends up with an error.
  • devtools::test(): 10395 passed, 62 skipped, 0 failures and 4 errors, identical on main and caused by the environment (three test-httpvfs.R tests cannot open the local HTTP database here, and test-dbConnect.R:159 needs an installed RSQLite in a callr subprocess). R CMD check --no-manual on a tarball built from a clean export of d26413c: Status OK.
  • ASan and UBSan, with RSQLite instrumented and the sanitizer runtimes preloaded into R: test-blob.R passes (31 passed; the 1e9-byte test was skipped). The probes above, including the UTF-16, zeroblob(), peek, out-of-memory and % cases, produce no report in the new code. The only report is in fetch_blob(), which this pull request does not touch (see below).
  • src/utf8.h is identical byte for byte to the copy on feat: Implement the DBI Arrow interface natively #795 at e273dfb.

High

No findings.

Medium

No findings.

Low

L7. The NULL branch of fetch_string() also covers running out of memory, but its comment says only "An empty blob". src/SqliteColumnDataSource.cpp#L98-L103. The behavior is Confirmed; the comment is assessed by reading. sqlite3_column_blob() returns NULL for a zero-length blob, and also when it fails to expand a zeroblob(). In the second case the code returns "" for that value. This is safe today only because fetch_rows() always calls sqlite3_step() next, and that call fails with SQLITE_NOMEM:

con <- dbConnect(SQLite())
dbGetQuery(con, "PRAGMA hard_heap_limit = 50000000")
q <- "SELECT CASE WHEN column1 = 1 THEN 'a' ELSE zeroblob(100000000) END AS x FROM (VALUES (1), (2), (1))"
dbGetQuery(con, q)   # Error: out of memory (main: segfault)
res <- dbSendQuery(con, q)
dbFetch(res, 1)      # "a"
dbFetch(res, 0)      # zero rows, no error
dbFetch(res)         # Error: out of memory

Suggested fix: the behavior can stay. Extend the comment, for example to "An empty blob, or out of memory while expanding a zeroblob(): the next sqlite3_step() then fails with SQLITE_NOMEM", so that a future code path that reads a row without stepping afterwards does not turn an allocation failure into "" unnoticed.

L8. The description and the accepted limitations are behind the code in a few places. By reading, except where marked. The accepted limitations link to lines of 867813e; at d26413c the rule that turns a blob with a NUL byte into NA is src/SqliteColumnDataSource.cpp#L105-L108, the unchanged text path #L86-L90, and the warning text src/DbColumn.cpp#L100-L111. The description says a peek still emits the mixed-type warning; together with the fetch that follows, that warning is reported twice for the same row (Confirmed, identical on main), which is not listed among the accepted limitations. The description presents the % fix as cosmetic ("printed as is"), but it also stops R from aborting on a column name that contains %n (Confirmed, see above). The NUL behavior change is stated in the body of 2bb0696, so it reaches NEWS only if the squash message keeps it. The phrase "whose review is running" is out of date once this review is posted. Suggested fix: point the three links at d26413c, add the doubled mixed-type warning after a peek as an accepted limitation, mention the %n abort, and keep the NUL sentence in the squash message.

Outside this pull request

These are not findings against this change. Each is the same kind of defect as one this pull request fixes, found while checking it.

  • The format-string defect remains in two other places. Confirmed on main and at d26413c. src/SqliteResultImpl.cpp#L378 passes the text of sqlite3_errmsg() to cpp11::stop() as the format, and src/SqliteResultImpl.cpp#L94 does the same with the ignored rest of a query in cpp11::warning(). dbGetQuery(con, 'SELECT * FROM "x%n"') and dbGetQuery(con, "SELECT 1; SELECT '%n'") both abort R with *** %n in writable segment detected ***; with %s%s%s in place of %n, the message prints garbage from the stack. This is easier to trigger than the column-name case, because a mistyped table name is enough. Suggested fix: pass "%s" as the format, as 9a0c166 does, either here or in a follow-up.
  • fetch_blob() does not handle a NULL pointer from sqlite3_column_blob(). Confirmed. src/SqliteColumnDataSource.cpp#L116-L124 passes the pointer straight to memcpy(). dbGetQuery(con, "SELECT X'' AS x") triggers UBSan's "null pointer passed as argument 2", and the out-of-memory query from L7, with X'00' in place of 'a', segfaults on main and at d26413c. Suggested fix: skip the memcpy() when sqlite3_column_blob() returns NULL; the next step then reports the out-of-memory error.
  • The Arrow path of feat: Implement the DBI Arrow interface natively #795 still reads a blob in a utf8 column with sqlite3_column_text(). By reading, at e273dfb: src/SqliteArrowColumn.cpp#L309-L313. In a UTF-16 database SQLite converts such a blob before rsqlite_is_utf8_string() sees it: the earlier review's L1 again, on the other path.

Generated by Claude Code

krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this comment.

The clean review of 867813e8 found one Medium and six Low issues; the Medium and four of the Low ones are fixed in d26413c, which the second clean review confirmed without High or Medium findings. Its comment on the out-of-memory branch of fetch_string() is added in 7d03e08. Its findings outside this pull request (two more format strings in src/SqliteResultImpl.cpp, a NULL pointer in fetch_blob()) are part of the open question on #829, and the blob in a utf8 Arrow column is being fixed on #795. These remain:

  • src/SqliteColumnDataSource.cpp#L105-L108: a blob with a NUL byte, such as a NUL-terminated C string stored with its terminator, becomes NA with a warning, where main returned the string up to the NUL. This is deliberate; the body of 2bb0696 states it, and the squash message has to keep that sentence for the NEWS entry to carry it. Relevance: medium; reviewer's confidence: high.
  • src/SqliteColumnDataSource.cpp#L86-L90: text values are read as before, so text with an embedded NUL is still cut silently and text that is not valid UTF-8 is still returned marked as UTF-8; only blobs are checked. Relevance: low; reviewer's confidence: high.
  • src/DbColumn.cpp#L100-L111: the warning text is passed as native bytes and not marked as UTF-8, so a non-ASCII column name shows as <c3><a4> under LC_ALL=C, as in the existing mixed-type warning; left for a separate change. Relevance: low; reviewer's confidence: high.
  • src/DbColumn.cpp#L39-L42: a peek with dbFetch(res, 0) or dbColumnInfo() still raises the mixed-type warning for the next row, and the fetch that returns the row raises it again, as on main; only the invalid-UTF-8 warning is now raised once. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

…g()`

`sqlite3_column_blob()` also returns `NULL` when it runs out of memory while expanding a `zeroblob()`, not only for an empty blob.
The comment now says so, and that returning `""` is safe only because the next `sqlite3_step()` then fails with `SQLITE_NOMEM`.
No change in behavior.

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

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

The checks for BLOBs look like an edge case, whereas the lax handling of text columns feels like much more commonplace in practice. This is a breaking change so needs to be behind an option, defaulting to the current behavior.

Reimplement from scratch in a stacked PR: first the UTF-8 infrastructure (that also seems to be needed for the Arrow PRs), then the fixes.

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Reimplemented from main as a stack, as asked: #845 adds the UTF-8 validator, defined in src/utf8.cpp and with no user-visible change, and #846 adds the checks behind dbConnect(check_utf8 = ), which defaults to getOption("RSQLite.check_utf8", FALSE). Fetches therefore behave as on main unless the checks are switched on; with them on, text values are checked as well as blobs, and a value that is not valid UTF-8 or holds a NUL byte becomes NA with one warning per column and fetch. The form of the option and when the Arrow stack moves to the shared validator are open questions on #829 (option, Arrow stack). Clean reviews of both pull requests are running. This pull request can be closed once the replacement suits you.


Generated by Claude Code

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review of 867813e8 found one Medium and six Low issues; the Medium and four of the Low ones are fixed in d26413c, which the second clean review confirmed without High or Medium findings. Its comment on the out-of-memory branch of fetch_string() is added in 7d03e08. Its findings outside this pull request (two more format strings in src/SqliteResultImpl.cpp, a NULL pointer in fetch_blob()) are part of the open question on #829, and the blob in a utf8 Arrow column is being fixed on #795. These remain:

  • src/SqliteColumnDataSource.cpp#L105-L108: a blob with a NUL byte, such as a NUL-terminated C string stored with its terminator, becomes NA with a warning, where main returned the string up to the NUL. This is deliberate; the body of 2bb0696 states it, and the squash message has to keep that sentence for the NEWS entry to carry it. Relevance: medium; reviewer's confidence: high.
  • src/SqliteColumnDataSource.cpp#L86-L90: text values are read as before, so text with an embedded NUL is still cut silently and text that is not valid UTF-8 is still returned marked as UTF-8; only blobs are checked. Relevance: low; reviewer's confidence: high.
  • src/DbColumn.cpp#L100-L111: the warning text is passed as native bytes and not marked as UTF-8, so a non-ASCII column name shows as <c3><a4> under LC_ALL=C, as in the existing mixed-type warning; left for a separate change. Relevance: low; reviewer's confidence: high.
  • src/DbColumn.cpp#L39-L42: a peek with dbFetch(res, 0) or dbColumnInfo() still raises the mixed-type warning for the next row, and the fetch that returns the row raises it again, as on main; only the invalid-UTF-8 warning is now raised once. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

#845 (the UTF-8 validator) and #846 (dbConnect(check_utf8 = TRUE)) replace this pull request: they check text read into a character column, as asked above, rather than only blobs. Marking this as a draft; it will be closed once #846 is merged.


Generated by Claude Code

@krlmlr

krlmlr commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

Closing as superseded: #845 (the UTF-8 validator) and #846 (dbConnect(check_utf8 = TRUE)) are now merged into main and replace the work in this draft, as planned in the coordination of the Arrow rework.


Generated by Claude Code

@krlmlr krlmlr closed this Nov 14, 2026
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.

dbReadTable converts arbitrary text to 0 if initial values in column INTEGER or REAL

2 participants