mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:44:38 +00:00
wallet, sqlite: Encapsulate SQLite statements in a RAII class #33033
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!33033
Loading…
Reference in a new issue
No description provided.
Delete branch "sqlite-stmt-raii"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
SQLite statements are C objects which can be long lived, so having them be initialized in a constructor, and cleanup everything in a destructor, makes the sqlite code cleaner and easier to read. This also lets us have the various functions needed to interact with sqlite statements be member functions.
This will be particularly useful in future work which makes use of more complicated SQL statements.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
No conflicts as of last run.
🚧 At least one of the CI tasks failed.
Task
previous releases, depends DEBUG: https://github.com/bitcoin/bitcoin/runs/46428794695LLM reason (✨ experimental): The CI failure is caused by a static assertion failure in the sqlite.cpp file during compilation.
Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
nit: you can use
ALWAYS_FALSEfor this, so that the workaround docs for the C++23 defect report are in one place only.Done
Is there any specific reason not to use
unsigned chardirectly, likestd::span<const unsigned char > sp)?In theory we could change
uint256'svalue_type, and we wouldn't need to make any changes here in that case.Looks good to me
ACK https://github.com/bitcoin/bitcoin/pull/33033/commits/b2c824a3ce0877f2cb7cbed1731088ed8ba6171a
I don't understand this change. The commit message just says "util: Add value_type and span constructor to (W)Txid", but it doesn't say why or where this is needed. Compiling without this (locally) seems to pass.
Also, conceptually, it seems to go in the opposite direction that we want to go in. This makes implicit construction from any byte span to
transaction_identifierpossible again. The constructortransaction_identifier(const uint256& wrapped)is private and will still catch those cases, but if this implementation detail is changed in the future, I presume direct and implicit construction from uint256 will be possible again.I think it would be good to explain this change a bit better for reviewers.
In
SQLiteStatement::Column<T>(), one of the ways we construct the appropriate data from a blob is to doreinterpret_cast<T::value_type>.Txidmet all of the requirements for using that constructor, except that it didn't have avalue_type, hence this commit adding it.But it looks like I didn't include that commit in this PR. Rather, it's https://github.com/bitcoin/bitcoin/pull/33034/commits/afe99b3b7df6c658fb4068c6418dfd7ebf151460 in #33034.
I see. Though, it may still be good to make this one
explicitto avoid silent uint256 conversions in the future?Also,
Txid::dataisstd::byte*, sovalue_typeshould probably bestd::byteas well.I haven't tried, but I presume both modifications should compile with afe99b3b7df6c658fb4068c6418dfd7ebf151460
I've dropped this commit from this PR and moved it to #33034. Also dropped
value_typeand made the constructor just takespan<const std::byte>and that seems to work.Done
Started reviewing; I'm not opposed to this introduction at the moment and I will get more clarity soon in the review.
Initial Concept ACK 1829b3512d7bf430ec44daa801eb8fadf46cd30b
These 3 commits from #33034 looks pretty generic and related enough. Can they be included in this PR?
In d13ffed94ad5f5d488f8d72e4d5d7f1c3fb27c2b "sqlite: Have SQLiteCursor store SQLiteStatement"
It doesn't seem to be used anymore here; builds and tests fine without it.
Approach ACK 1829b3512d7bf430ec44daa801eb8fadf46cd30b
Looks like
m_dbcan never benullptrsince it is initialized by the constructor to a presumably non-null value. Consider making this a referencesqlite3& m_db;. That would signal to the readers that it can never be null and will also make it impossible to have weird states of this class that somehow end up having a null member.The class name is
SQLiteStatement, is this intentionallySQLiteDatabase?I think it would be useful to print the statement as well (
stmt_text).Just an observation:
Some of the callers of
sqlite3_prepare_v2()callsqlite3_finalize()on failure. The doc says that if prepare fails then *ppStmt is set to NULL and Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.So it is ok to omit the finalize call.
Some of the callers of
sqlite3_finalize()used to check its return value. Here in the destructor it is too late to signal an error to the caller.From: https://sqlite.org/c3ref/finalize.html
I am not sure what is the best way to handle this. Ignoring the return value does not look good.
Maybe assert that
sqlite3_finalize()returnsSQLITE_OK? And also somehow make sure that if "the most recent evaluation of statement S failed", then this is handled already, before the destructor is called. That would mean ifsqlite3_step(), called fromStep()fails (result is notSQLITE_ROWorSQLITE_DONE) then to callsqlite3_finalize()from insideStep()?Reset()is not needed here?From https://sqlite.org/c3ref/column_blob.html:
Maybe at the beginning of the function, add:
What happens if
Tis unsigned? Maybe add https://en.cppreference.com/w/cpp/types/is_signed.html here:std::integral<T> && std::is_signed<T>? (and leave it to drop to "else assert always false" for unsignedTs)sqlite3_column_text()can returnnullptr, better check that. The previous caller did check:Previously on error
ReadPragmaInteger()would have returnednullopt. Now it wouldthrow. Its only caller isSQLiteDatabase::Verify()which would have returnedfalseand now would let the exception propagate. The only caller ofSQLiteDatabase::Verify()isMakeSQLiteDatabase(). Before, onVerify()failure (returnfalse)MakeSQLiteDatabase()would have setstatus = DatabaseStatus::FAILED_VERIFYand now (exception) it would setstatus = DatabaseStatus::FAILED_LOAD. Is this ok?Now
ReadPragmaInteger()would returnnullopton some errors andthrowon others. What about making it to onlythrow? Then its return type would change fromstd::optional<int>tointand its callers would not need to checkif (!read_result.has_value()) ....I guess also
SQLiteStatement::Step()canthrowif the return value ofsqlite3_step()is notSQLITE_ROWorSQLITE_DONE.The second element in the pair (
stmt_description) is not used. This snippet can be reduced to:Or simple stupid:
nit, here and in the other constructor:
Maybe (not tested):
Related to https://github.com/bitcoin/bitcoin/pull/33033#discussion_r2518504627
This text reads to me as
sqlite3_finalizepropagating any previous errors, e.g. fromsqlite3_step. Since any errors from that should already be handled, I think it's ok to ignore the result of finalize. I think the previous code is actually incorrect since the error result is not actually a result of finalize failing.Done
Done
Done
Done
Removed
Done
Done
I've changed this to catch the exception and return
std::nullopt.Changed to catch the exception.
Done, returns an empty string now.
But the only time
sqlite3_column_textshould return NULL is if the column contains a NULL value. Empty strings are not stored as NULL.Done
Done
ACK 0af7c2a11819a21e11abf34b4229c5c21150d827
Yeah, I was thinking the same. It is just super odd to ignore database errors (in general). I guess the sqlite API is odd here.
Edit: if you retouch, maybe change
int Step()to[[nodiscard]] int Step()to hint the callers to not ignore the return value.I wonder if the introduction of
SQLiteStatementmeans we can do better than initializing every statement as a member of every batch: Given that we areReset()'ing statements every single time they are used, and AFAICT batches tend to be short-lived, I think it would be cheaper and less complicated to initialize statement objects just before they are used in the variousRead*()Erase*(), and it takes better advantage of the fact that statements are RAII than manually calling a closing function in Batch's destructor and asserting at the beginning of everyWalletBatch()function that the relevantstmtobject exists, here's one take of how something like this could be done:github.com/davidgumberg/bitcoin@b67e0301fdnit: IMO this is neater with
ExecEraseStatementremoved andrepeated in
EraseKeyandErasePrefix, in total it's only ~2 more LOC.ExecEraseStatement()internally has nothing to do with erasing, except that it happens to be the case that both eraseprefix and erasekey statements only have one parameter.Done
We still want to have the statements persist across multiple queries in a single
SQLiteBatchto avoid sqlite having to parse the same statement text over and over. However, we can construct theSQLiteStatementon first use instead of always, so I've added a commit to do that.🚧 At least one of the CI tasks failed.
Task
test max 6 ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/20667709652/job/59343191929LLM reason (✨ experimental): Compilation failed: use of undeclared identifier 'blob' in wallet/sqlite.cpp causing build error.
Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Ping @davidgumberg @vasild for hopefully another round of review.
https://github.com/bitcoin/bitcoin/pull/33033/commits/1682818a7b19c7c391fe4a75d96f620b1ac5127c:
Looks good to me. Left some comments.
https://github.com/bitcoin/bitcoin/pull/33033/commits/bfa96f8c12ba40fbc66499fa72251bec9e3367e1:
I think it's useful to document that
SQLiteStatementcan only handle one statement instmt_textor, preferably, provide thepzTailargument and throw an error ifpzTailis not Null aftersqlite3_prepare_v2(this indicates that there is uncompiled SQL code left).https://github.com/bitcoin/bitcoin/pull/33033/commits/b79895c87a3e50de09f7a61887f1389030a94823:
I wonder if
Bindshould throw anExceptioninstead? It doesn't look like we can recover from a failure tosqlite3_bind_blob.Not all callers of this will have exception handling, but they all should have handling if it fails.
If I need to retouch.
Looks like a good candidate for
[[nodiscard]]ACK 1682818a7b19
Left some inline nits. Two broader observations I think worth noting:
GetNewPrefixCursorbind failure is now a throw instead ofnullptr-Previously
GetNewPrefixCursorreturnednullptrwhenBindBlobToStatementfailed, and callers handled that. Now theSQLiteCursorconstructor throwsstd::runtime_errorif either bind call fails, and no caller catches it — so it propagates up the stack. Also, since this PR introduces the behaviour change, wouldn't be natural to clean up the now-dead null-checks inwalletdb.cpp(lines 193, 470, 523)?sqlite3_prepare_v2ignores trailing SQL (pzTail) -The
SQLiteStatementconstructor passesnullptras thepzTailout-parameter, so ifstmt_textever contained more than one statement (e.g. a stray semicolon —"INSERT INTO main VALUES(?,?); DROP TABLE main"), SQLite would silently prepare only the first and discard the rest (@Eunovo raised it also).worth considering a
LogWarningor at least a doc comment?nit:
nit (more consistently within the repo):
nit:
nit: same as here.
nit: per doc/developer-notes.md, prefer
enum classover plainenum.nit:
ExecEraseStatementis never used nor implemented.No. A column that stores a string could contain nothing in it if there is no string to store, which is equivalent to the empty string.
Done
Done
Removed
Done
Done
Done
Done
GetNewPrefixCursorcan still returnnullptr.🚧 At least one of the CI tasks failed.
Task
MSan, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/33007141761/job/98303718292LLM reason (✨ experimental): CI failed because the
fuzztargetscriptpubkeymanhit a libc++ hardening assertion (attempted to dereference an end iterator), causing an abort (exit code 1).Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
cACK
in
4ace00b4c6sqlite: Add SQLiteStatement RAII classI think is worth to disallow copies? Similar as
DatabaseBatchdoes indb.h? A copy would double finalizem_stmt(I think that would crash).in
244554b20fsqlite: Make Column template functionI think the static_cast is a no-op. sqlite3_column_int64 already returns an int_64.
Also isn't
sizeof(T) <= 8also a no-op?Maybe:
in
84dd0c3848sqlite: Refactor common writing code from WriteKey and ExecStatementYou mention in the commit message that ExecStatement is renamed to
ExecEraseStatement, but this last is never defined in .cpp.+1 This should be marked
nodiscard🟠 Minor · Prefix cursor buffers are freed before their statement is finalized
Destroying a successfully constructed nonempty prefix cursor leaves its SQLITE_STATIC bindings pointing to freed vector storage until finalization, violating SQLite's lifetime contract without an established invalid read.
Location:
src/wallet/sqlite.h:25(head).🔵 Suggestion · Recoverable statement failures now produce generic error-level logs
The shared executor raises handled write failures from warning to error level and removes the previous write-versus-erase context.
Location:
src/wallet/sqlite.cpp:543(head).🔵 Suggestion · BLOB accessor no longer guarantees blob-before-bytes evaluation
The inlined accessor loses SQLite's documented safe call order, although wallet-written BLOBs need no conversion and no concrete misread was established.
Location:
src/wallet/sqlite.cpp:135(head).Review coverage was incomplete.
Reviewed:
774fbc89c9bd· Full review report · Previous reportspermalink
It's a
sqlite3_int64which is a typedef oflong long int. The static cast is to put it into a type that we actually use.Possibly, but it doesn't hurt.
🐙 This pull request conflicts with the target branch and needs rebase.
re-ACK
774fbc89c9Thanks for addressing my nits.
Also since my previous review, @Eunovo and @polespinasa feedback were addressed.
I went through some findings from Ralph and verified the following 3 against the code, which may be worth fixing if you retouch:
ExecStatementreintroducesLogErrorand the trailing\nthat master changed toLogWarninginfa45a1503e;m_cursor_stmtis declared beforem_prefix_range_start/m_prefix_range_end, so the vectors (bound withSQLITE_STATIC) are destroyed before the statement is finalized; declaring it after them would fix that;SpanFromBlobused brace-init, which guaranteedsqlite3_column_blobis evaluated beforesqlite3_column_bytes; the inlinedT(...)doesn't, whileT{...}would.