Skip to content

wallet, sqlite: Encapsulate SQLite statements in a RAII class - #33033

Open
achow101 wants to merge 10 commits into
bitcoin:masterfrom
achow101:sqlite-stmt-raii
Open

achow101 wants to merge 10 commits into
bitcoin:masterfrom
achow101:sqlite-stmt-raii

Conversation

@achow101

Copy link
Copy Markdown
Member

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.

@DrahtBot

DrahtBot commented Jul 21, 2025 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
ACK pablomartin4btc
Concept ACK rkrux, polespinasa
Stale ACK w0xlt, vasild

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.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task previous releases, depends DEBUG: https://github.com/bitcoin/bitcoin/runs/46428794695
LLM 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.

@achow101
achow101 force-pushed the sqlite-stmt-raii branch 3 times, most recently from e1bf41a to 2c1edcc Compare July 22, 2025 06:11
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/util/transaction_identifier.h Resolved

@w0xlt w0xlt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me

ACK b2c824a

Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/util/transaction_identifier.h Resolved

@rkrux rkrux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

  • 818989093d9e6b8ee765c21630f7342b99af7fa0 "sqlite: Make SQLiteStatement::Bind a template function"
  • 07cac74e1340c7e771850633dd9418ff3efa5bb7 "sqlite: Make SQLiteDatabase::Column an std::optional"
  • ff47eea527e58071bdaff5c2acbc98ee97294021 "sqlite: Add additional blob types to SQLiteStatement::Column"

Comment thread src/wallet/sqlite.h Resolved

@vasild vasild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach ACK 1829b3512d7bf430ec44daa801eb8fadf46cd30b

Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Outdated
Comment on lines +72 to +74
int res = sqlite3_prepare_v2(m_db, stmt_text.c_str(), -1, &m_stmt, nullptr);
if (res != SQLITE_OK) {
throw std::runtime_error(strprintf(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just an observation:

Some of the callers of sqlite3_prepare_v2() call sqlite3_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.

Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp
~SQLiteStatement()
{
Reset();
sqlite3_finalize(m_stmt);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

If the most recent evaluation of statement S failed, then sqlite3_finalize(S) returns the appropriate error code or extended error code

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() returns SQLITE_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 if sqlite3_step(), called from Step() fails (result is not SQLITE_ROW or SQLITE_DONE) then to call sqlite3_finalize() from inside Step()?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe (not tested):

    int Step()
    {
        const int ret = sqlite3_step(m_stmt);
        if (ret == SQLITE_ROW || ret == SQLITE_DONE) {
            return ret;
        }
        sqlite3_finalize(m_stmt);
        m_stmt = nullptr;
        // then the destructor can assert(sqlite3_finalize(m_stmt) == SQLITE_OK);
    }

Related to #33033 (comment)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the most recent evaluation of statement S failed, then sqlite3_finalize(S) returns the appropriate error code or extended error code

I am not sure what is the best way to handle this. Ignoring the return value does not look good.

This text reads to me as sqlite3_finalize propagating any previous errors, e.g. from sqlite3_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.

@vasild vasild Nov 20, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 This should be marked nodiscard

@vasild vasild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 0af7c2a11819a21e11abf34b4229c5c21150d827

@DrahtBot DrahtBot removed the CI failed label Jan 3, 2026
@sedited
sedited requested a review from davidgumberg March 16, 2026 08:01
@sedited

sedited commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Ping @davidgumberg @vasild for hopefully another round of review.

@Eunovo Eunovo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1682818:

Looks good to me. Left some comments.

Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK 1682818

Left some inline nits. Two broader observations I think worth noting:

  • GetNewPrefixCursor bind failure is now a throw instead of nullptr -
    Previously GetNewPrefixCursor returned nullptr when BindBlobToStatement failed, and callers handled that. Now the SQLiteCursor constructor throws std::runtime_error if 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 in walletdb.cpp (lines 193, 470, 523)?

  • sqlite3_prepare_v2 ignores trailing SQL (pzTail) -
    The SQLiteStatement constructor passes nullptr as the pzTail out-parameter, so if stmt_text ever 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).

Comment thread src/wallet/sqlite.h Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Resolved
Comment thread src/wallet/sqlite.cpp Outdated
error += Untranslated(strprintf("%s\n", str_msg));
}
error += Untranslated(strprintf("%s\n", str_msg));
} catch (std::runtime_error& e) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: same as here.

Comment thread src/wallet/sqlite.cpp
} else if constexpr (std::is_same_v<T, std::string>) {
const char* text = (const char*)sqlite3_column_text(m_stmt, col);
if (!text) {
return "";

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

worth considering a LogWarning or at least a doc comment?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/wallet/sqlite.h Resolved
@DrahtBot
DrahtBot requested a review from vasild July 27, 2026 20:16
@achow101

Copy link
Copy Markdown
Member Author
  • Also, since this PR introduces the behaviour change, wouldn't be natural to clean up the now-dead null-checks in walletdb.cpp (lines 193, 470, 523)?

GetNewPrefixCursor can still return nullptr.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task MSan, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/33007141761/job/98303718292
LLM reason (✨ experimental): CI failed because the fuzz target scriptpubkeyman hit 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.

@polespinasa polespinasa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cACK

Comment thread src/wallet/sqlite.cpp

~SQLiteStatement()
{
sqlite3_finalize(m_stmt);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 4ace00b sqlite: Add SQLiteStatement RAII class

I think is worth to disallow copies? Similar as DatabaseBatch does in db.h? A copy would double finalize m_stmt (I think that would crash).

SQLiteStatement(const SQLiteStatement&) = delete;
SQLiteStatement& operator=(const SQLiteStatement&) = delete;

Comment thread src/wallet/sqlite.cpp
Comment on lines +137 to +138
} else if constexpr (std::integral<T> && std::is_signed_v<T> && sizeof(T) <= 8) {
return static_cast<int64_t>(sqlite3_column_int64(m_stmt, col));

@polespinasa polespinasa Sep 24, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 244554b sqlite: Make Column template function

I think the static_cast is a no-op. sqlite3_column_int64 already returns an int_64.
Also isn't sizeof(T) <= 8 also a no-op?

Maybe:

Suggested change
} else if constexpr (std::integral<T> && std::is_signed_v<T> && sizeof(T) <= 8) {
return static_cast<int64_t>(sqlite3_column_int64(m_stmt, col));
} else if constexpr (std::integral<T> && std::is_signed_v<T>) {
static_assert(sizeof(T) <= 8, "T is larger than 8bytes and would be truncated.");
return sqlite3_column_int64(m_stmt, col);
``

@achow101 achow101 Oct 16, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the static_cast is a no-op. sqlite3_column_int64 already returns an int_64.

It's a sqlite3_int64 which is a typedef of long long int. The static cast is to put it into a type that we actually use.

Also isn't sizeof(T) <= 8 also a no-op?

Possibly, but it doesn't hurt.

Comment thread src/wallet/sqlite.h Outdated
void SetupSQLStatements();
bool ExecStatement(SQLiteStatement* stmt, std::span<const std::byte> blob);
bool ExecStatement(SQLiteStatement* stmt);
bool ExecEraseStatement(SQLiteStatement* stmt, std::span<const std::byte> blob);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in 84dd0c3 sqlite: Refactor common writing code from WriteKey and ExecStatement

You mention in the commit message that ExecStatement is renamed to ExecEraseStatement, but this last is never defined in .cpp.

This class will be used to encapsulate a sqlite3_stmt
WriteKey and ExecStatement use the same code for the actual execution of
the statement.
Instead of constructing all SQLiteStatements when SQLiteBatch is
constructed, construct them once when they are needed before each read,
write, or erase operation. Once constructed, the statement will persist
for the lifetime of the SQLiteBatch to be reused across multiple
statements.

@pablomartin4btc pablomartin4btc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

re-ACK 774fbc8

Thanks 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:

  • ExecStatement reintroduces LogError and the trailing \n that master changed to LogWarning in fa45a15;
  • m_cursor_stmt is declared before m_prefix_range_start/m_prefix_range_end, so the vectors (bound with SQLITE_STATIC) are destroyed before the statement is finalized; declaring it after them would fix that;
  • SpanFromBlob used brace-init, which guaranteed sqlite3_column_blob is evaluated before sqlite3_column_bytes; the inlined T(...) doesn't, while T{...} would.

@DrahtBot
DrahtBot requested a review from polespinasa December 3, 2026 02:16
knst added a commit to knst/dash that referenced this pull request Dec 3, 2026
Every SQLiteBatch prepared all five of its statements in the constructor, and since a connected block opens a batch per wallet, plus short batches such as WriteBestBlock and AddToWallet, profiling IBD with a SQLite wallet showed 10.2% of the scheduler thread's on-CPU samples in sqlite3_prepare_v2 under SQLiteBatch::SetupSQLStatements().
Most batches use one or two of the statements, so prepare each one when the batch first uses it. Preparing still throws on failure, now from the first read or write instead of from MakeBatch. Upstream bitcoin#33033 (open) makes the same change as part of a larger refactor.
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.