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

Open
achow101 wants to merge 10 commits from sqlite-stmt-raii into master AGit
achow101 commented 2025-07-21 22:43:08 +00:00 (Migrated from github.com)

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.

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 commented 2025-07-21 22:43:12 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/33033 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/33033.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/33033#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [pablomartin4btc](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-6162559167) | | Concept ACK | [rkrux](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-3404260829), [polespinasa](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-5302743415) | | Stale ACK | [w0xlt](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-3049382506), [vasild](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-3487577017) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2025-07-22 02:33:18 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `previous releases, depends DEBUG`: https://github.com/bitcoin/bitcoin/runs/46428794695</sub> <sub>LLM reason (✨ experimental): The CI failure is caused by a static assertion failure in the sqlite.cpp file during compilation.</sub> <details><summary>Hints</summary> 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. </details>
maflcko (Migrated from github.com) reviewed 2025-07-22 08:07:39 +00:00
Lines 132-134
maflcko (Migrated from github.com) commented 2025-07-22 08:07:39 +00:00

nit: you can use ALWAYS_FALSE for this, so that the workaround docs for the C++23 defect report are in one place only.

nit: you can use `ALWAYS_FALSE` for this, so that the workaround docs for the C++23 defect report are in one place only.
achow101 (Migrated from github.com) reviewed 2025-07-22 17:01:15 +00:00
Lines 132-134
achow101 (Migrated from github.com) commented 2025-07-22 17:01:15 +00:00

Done

Done
w0xlt (Migrated from github.com) reviewed 2025-07-23 21:00:23 +00:00
w0xlt (Migrated from github.com) commented 2025-07-23 21:00:19 +00:00

Is there any specific reason not to use unsigned char directly, like std::span<const unsigned char > sp) ?

Is there any specific reason not to use `unsigned char` directly, like `std::span<const unsigned char > sp)` ?
achow101 (Migrated from github.com) reviewed 2025-07-23 21:15:55 +00:00
achow101 (Migrated from github.com) commented 2025-07-23 21:15:55 +00:00

In theory we could change uint256's value_type, and we wouldn't need to make any changes here in that case.

In theory we could change `uint256`'s `value_type`, and we wouldn't need to make any changes here in that case.
w0xlt (Migrated from github.com) reviewed 2025-07-23 23:03:08 +00:00
w0xlt (Migrated from github.com) left a comment
Looks good to me ACK https://github.com/bitcoin/bitcoin/pull/33033/commits/b2c824a3ce0877f2cb7cbed1731088ed8ba6171a
maflcko (Migrated from github.com) reviewed 2025-07-24 07:58:20 +00:00
maflcko (Migrated from github.com) commented 2025-07-24 07:58:10 +00:00

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_identifier possible again. The constructor transaction_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.

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_identifier` possible again. The constructor `transaction_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.
maflcko (Migrated from github.com) commented 2025-07-24 07:13:54 +00:00
encapsualtes -> encapsulates [spelling error in comment “encapsualtes” makes the word misspelled]
encapsualtes -> encapsulates [spelling error in comment “encapsualtes” makes the word misspelled]
achow101 (Migrated from github.com) reviewed 2025-07-24 17:40:19 +00:00
achow101 (Migrated from github.com) commented 2025-07-24 17:40:19 +00:00

In SQLiteStatement::Column<T>(), one of the ways we construct the appropriate data from a blob is to do reinterpret_cast<T::value_type>. Txid met all of the requirements for using that constructor, except that it didn't have a value_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.

In `SQLiteStatement::Column<T>()`, one of the ways we construct the appropriate data from a blob is to do `reinterpret_cast<T::value_type>`. `Txid` met all of the requirements for using that constructor, except that it didn't have a `value_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.
maflcko (Migrated from github.com) reviewed 2025-07-24 19:50:09 +00:00
maflcko (Migrated from github.com) commented 2025-07-24 19:50:09 +00:00

I see. Though, it may still be good to make this one explicit to avoid silent uint256 conversions in the future?

Also, Txid::data is std::byte*, so value_type should probably be std::byte as well.

I haven't tried, but I presume both modifications should compile with afe99b3b7df6c658fb4068c6418dfd7ebf151460

I see. Though, it may still be good to make this one `explicit` to avoid silent uint256 conversions in the future? Also, `Txid::data` is `std::byte*`, so `value_type` should probably be `std::byte` as well. I haven't tried, but I presume both modifications should compile with afe99b3b7df6c658fb4068c6418dfd7ebf151460
achow101 (Migrated from github.com) reviewed 2025-07-24 20:49:51 +00:00
achow101 (Migrated from github.com) commented 2025-07-24 20:49:51 +00:00

I've dropped this commit from this PR and moved it to #33034. Also dropped value_type and made the constructor just take span<const std::byte> and that seems to work.

I've dropped this commit from this PR and moved it to #33034. Also dropped `value_type` and made the constructor just take `span<const std::byte>` and that seems to work.
achow101 (Migrated from github.com) reviewed 2025-07-24 20:50:47 +00:00
achow101 (Migrated from github.com) commented 2025-07-24 20:50:47 +00:00

Done

Done
rkrux (Migrated from github.com) reviewed 2025-10-31 14:22:57 +00:00
rkrux (Migrated from github.com) left a comment

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"
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"
rkrux (Migrated from github.com) commented 2025-10-31 13:23:16 +00:00

In d13ffed94ad5f5d488f8d72e4d5d7f1c3fb27c2b "sqlite: Have SQLiteCursor store SQLiteStatement"

It doesn't seem to be used anymore here; builds and tests fine without it.

--- a/src/wallet/sqlite.h
+++ b/src/wallet/sqlite.h
@@ -12,7 +12,6 @@

struct bilingual_str;

-struct sqlite3_stmt;
struct sqlite3;

namespace wallet {
In d13ffed94ad5f5d488f8d72e4d5d7f1c3fb27c2b "sqlite: Have SQLiteCursor store SQLiteStatement" It doesn't seem to be used anymore here; builds and tests fine without it. ```diff --- a/src/wallet/sqlite.h +++ b/src/wallet/sqlite.h @@ -12,7 +12,6 @@ struct bilingual_str; -struct sqlite3_stmt; struct sqlite3; namespace wallet { ```
vasild (Migrated from github.com) reviewed 2025-11-12 16:21:35 +00:00
vasild (Migrated from github.com) left a comment

Approach ACK 1829b3512d7bf430ec44daa801eb8fadf46cd30b

Approach ACK 1829b3512d7bf430ec44daa801eb8fadf46cd30b
vasild (Migrated from github.com) commented 2025-11-12 10:04:52 +00:00

Looks like m_db can never be nullptr since it is initialized by the constructor to a presumably non-null value. Consider making this a reference sqlite3& 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.

Looks like `m_db` can never be `nullptr` since it is initialized by the constructor to a presumably non-null value. Consider making this a reference `sqlite3& 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.
vasild (Migrated from github.com) commented 2025-11-12 13:17:36 +00:00

The class name is SQLiteStatement, is this intentionally SQLiteDatabase?

The class name is `SQLiteStatement`, is this intentionally `SQLiteDatabase`?
vasild (Migrated from github.com) commented 2025-11-12 13:18:44 +00:00

I think it would be useful to print the statement as well (stmt_text).

I think it would be useful to print the statement as well (`stmt_text`).
Lines 74-76
vasild (Migrated from github.com) commented 2025-11-12 10:12:57 +00:00

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.

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](https://sqlite.org/c3ref/prepare.html) and [Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op](https://sqlite.org/c3ref/finalize.html). So it is ok to omit the finalize call.
vasild (Migrated from github.com) commented 2025-11-12 15:28:27 +00:00

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()?

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](https://sqlite.org/rescode.html) or [extended error code](https://sqlite.org/rescode.html#extrc) 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()`?
Lines 82-85
vasild (Migrated from github.com) commented 2025-11-12 13:24:07 +00:00

Reset() is not needed here?

`Reset()` is not needed here?
Lines 116-121
vasild (Migrated from github.com) commented 2025-11-12 13:35:36 +00:00

From https://sqlite.org/c3ref/column_blob.html:

if the column index is out of range, the result is undefined

Maybe at the beginning of the function, add:

Assert(col < sqlite3_column_count());
From https://sqlite.org/c3ref/column_blob.html: > if the column index is out of range, the result is undefined Maybe at the beginning of the function, add: ```cpp Assert(col < sqlite3_column_count()); ```
vasild (Migrated from github.com) commented 2025-11-12 13:52:18 +00:00

What happens if T is 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 unsigned Ts)

What happens if `T` is 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 unsigned `T`s)
Lines 126-133
vasild (Migrated from github.com) commented 2025-11-12 14:43:59 +00:00

sqlite3_column_text() can return nullptr, better check that. The previous caller did check:

-        const char* msg = (const char*)sqlite3_column_text(stmt, 0);
-        if (!msg) {                                                                                               
-            error = ...
`sqlite3_column_text()` can return `nullptr`, better check that. The previous caller did check: ```diff - const char* msg = (const char*)sqlite3_column_text(stmt, 0); - if (!msg) { - error = ... ```
Lines 138-141
vasild (Migrated from github.com) commented 2025-11-12 14:14:55 +00:00

Previously on error ReadPragmaInteger() would have returned nullopt. Now it would throw. Its only caller is SQLiteDatabase::Verify() which would have returned false and now would let the exception propagate. The only caller of SQLiteDatabase::Verify() is MakeSQLiteDatabase(). Before, on Verify() failure (return false) MakeSQLiteDatabase() would have set status = DatabaseStatus::FAILED_VERIFY and now (exception) it would set status = DatabaseStatus::FAILED_LOAD. Is this ok?

Previously on error `ReadPragmaInteger()` would have returned `nullopt`. Now it would `throw`. Its only caller is `SQLiteDatabase::Verify()` which would have returned `false` and now would let the exception propagate. The only caller of `SQLiteDatabase::Verify()` is `MakeSQLiteDatabase()`. Before, on `Verify()` failure (return `false`) `MakeSQLiteDatabase()` would have set `status = DatabaseStatus::FAILED_VERIFY` and now (exception) it would set `status = DatabaseStatus::FAILED_LOAD`. Is this ok?
Lines 143-147
vasild (Migrated from github.com) commented 2025-11-12 14:21:58 +00:00

Now ReadPragmaInteger() would return nullopt on some errors and throw on others. What about making it to only throw? Then its return type would change from std::optional<int> to int and its callers would not need to check if (!read_result.has_value()) ....

I guess also SQLiteStatement::Step() can throw if the return value of sqlite3_step() is not SQLITE_ROW or SQLITE_DONE.

Now `ReadPragmaInteger()` would return `nullopt` on some errors and `throw` on others. What about making it to only `throw`? Then its return type would change from `std::optional<int>` to `int` and its callers would not need to check `if (!read_result.has_value()) ...`. I guess also `SQLiteStatement::Step()` can `throw` if the return value of `sqlite3_step()` is not `SQLITE_ROW` or `SQLITE_DONE`.
Lines 457-488
vasild (Migrated from github.com) commented 2025-11-12 15:18:58 +00:00

The second element in the pair (stmt_description) is not used. This snippet can be reduced to:

    for (auto stmt : {&m_read_stmt, &m_insert_stmt, &m_overwrite_stmt, &m_delete_stmt, &m_delete_prefix_stmt}) {
        stmt->reset();
    }                   

Or simple stupid:

    m_read_stmt.reset();
    m_insert_stmt.reset();
    m_overwrite_stmt.reset();
    m_delete_stmt.reset();
    m_delete_prefix_stmt.reset();
The second element in the pair (`stmt_description`) is not used. This snippet can be reduced to: ```cpp for (auto stmt : {&m_read_stmt, &m_insert_stmt, &m_overwrite_stmt, &m_delete_stmt, &m_delete_prefix_stmt}) { stmt->reset(); } ``` Or simple stupid: ```cpp m_read_stmt.reset(); m_insert_stmt.reset(); m_overwrite_stmt.reset(); m_delete_stmt.reset(); m_delete_prefix_stmt.reset(); ```
Lines 591-594
vasild (Migrated from github.com) commented 2025-11-12 14:54:05 +00:00

nit, here and in the other constructor:

SQLiteCursor::SQLiteCursor(sqlite3* db, const std::string& stmt_text)
    : m_cursor_stmt(std::make_unique<SQLiteStatement>(db, stmt_text)) {}
nit, here and in the other constructor: ```cpp SQLiteCursor::SQLiteCursor(sqlite3* db, const std::string& stmt_text) : m_cursor_stmt(std::make_unique<SQLiteStatement>(db, stmt_text)) {} ```
vasild (Migrated from github.com) reviewed 2025-11-14 06:02:56 +00:00
vasild (Migrated from github.com) commented 2025-11-14 06:02:56 +00:00

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 https://github.com/bitcoin/bitcoin/pull/33033#discussion_r2518504627

Maybe (not tested): ```cpp 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 https://github.com/bitcoin/bitcoin/pull/33033#discussion_r2518504627
achow101 (Migrated from github.com) reviewed 2025-11-17 21:11:47 +00:00
achow101 (Migrated from github.com) commented 2025-11-17 21:11:47 +00:00

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.

> > If the most recent evaluation of statement S failed, then sqlite3_finalize(S) returns the appropriate [error code](https://sqlite.org/rescode.html) or [extended error code](https://sqlite.org/rescode.html#extrc) > > 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.
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:15 +00:00
achow101 (Migrated from github.com) commented 2025-11-17 21:26:15 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:22 +00:00
achow101 (Migrated from github.com) commented 2025-11-17 21:26:22 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:41 +00:00
achow101 (Migrated from github.com) commented 2025-11-17 21:26:41 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:45 +00:00
achow101 (Migrated from github.com) commented 2025-11-17 21:26:45 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:53 +00:00
Lines 82-85
achow101 (Migrated from github.com) commented 2025-11-17 21:26:53 +00:00

Removed

Removed
achow101 (Migrated from github.com) reviewed 2025-11-17 21:26:58 +00:00
Lines 116-121
achow101 (Migrated from github.com) commented 2025-11-17 21:26:58 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:27:04 +00:00
Lines 118-121
achow101 (Migrated from github.com) commented 2025-11-17 21:27:04 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:27:27 +00:00
Lines 138-141
achow101 (Migrated from github.com) commented 2025-11-17 21:27:27 +00:00

I've changed this to catch the exception and return std::nullopt.

I've changed this to catch the exception and return `std::nullopt`.
achow101 (Migrated from github.com) reviewed 2025-11-17 21:27:42 +00:00
Lines 143-147
achow101 (Migrated from github.com) commented 2025-11-17 21:27:42 +00:00

Changed to catch the exception.

Changed to catch the exception.
achow101 (Migrated from github.com) reviewed 2025-11-17 21:28:25 +00:00
Lines 126-133
achow101 (Migrated from github.com) commented 2025-11-17 21:28:25 +00:00

Done, returns an empty string now.

But the only time sqlite3_column_text should return NULL is if the column contains a NULL value. Empty strings are not stored as NULL.

Done, returns an empty string now. But the only time `sqlite3_column_text` should return NULL is if the column contains a NULL value. Empty strings are not stored as NULL.
achow101 (Migrated from github.com) reviewed 2025-11-17 21:28:37 +00:00
Lines 591-594
achow101 (Migrated from github.com) commented 2025-11-17 21:28:37 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2025-11-17 21:28:43 +00:00
Lines 457-488
achow101 (Migrated from github.com) commented 2025-11-17 21:28:43 +00:00

Done

Done
vasild (Migrated from github.com) approved these changes 2025-11-20 12:23:54 +00:00
vasild (Migrated from github.com) left a comment

ACK 0af7c2a11819a21e11abf34b4229c5c21150d827

ACK 0af7c2a11819a21e11abf34b4229c5c21150d827
vasild (Migrated from github.com) reviewed 2025-11-20 12:38:39 +00:00
vasild (Migrated from github.com) commented 2025-11-20 12:38:39 +00:00

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.

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.
davidgumberg (Migrated from github.com) reviewed 2025-12-25 01:20:51 +00:00
davidgumberg (Migrated from github.com) commented 2025-12-24 23:56:00 +00:00

I wonder if the introduction of SQLiteStatement means we can do better than initializing every statement as a member of every batch: Given that we are Reset()'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 various Read*() 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 every WalletBatch() function that the relevant stmt object exists, here's one take of how something like this could be done:

github.com/davidgumberg/bitcoin@b67e0301fd

I wonder if the introduction of `SQLiteStatement` means we can do better than initializing every statement as a member of every batch: Given that we are `Reset()`'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 various `Read*()` `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 every `WalletBatch()` function that the relevant `stmt` object exists, here's one take of how something like this could be done: https://github.com/davidgumberg/bitcoin/commit/b67e0301fd30564188470a29d3c10df2ff561e9c
Lines 567-591
davidgumberg (Migrated from github.com) commented 2025-12-24 22:15:06 +00:00

nit: IMO this is neater with ExecEraseStatement removed and

    if (!m_database.m_db) return false;
    assert(stmt);

    // Bind: leftmost parameter in statement is index 1
    if (!stmt->Bind(1, blob, "key")) return false;

repeated in EraseKey and ErasePrefix, 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.

nit: IMO this is neater with `ExecEraseStatement` removed and ```cpp if (!m_database.m_db) return false; assert(stmt); // Bind: leftmost parameter in statement is index 1 if (!stmt->Bind(1, blob, "key")) return false; ``` repeated in `EraseKey` and `ErasePrefix`, 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.
achow101 (Migrated from github.com) reviewed 2026-01-02 22:09:24 +00:00
Lines 567-591
achow101 (Migrated from github.com) commented 2026-01-02 22:09:24 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-01-02 22:11:09 +00:00
achow101 (Migrated from github.com) commented 2026-01-02 22:11:09 +00:00

We still want to have the statements persist across multiple queries in a single SQLiteBatch to avoid sqlite having to parse the same statement text over and over. However, we can construct the SQLiteStatement on first use instead of always, so I've added a commit to do that.

We still want to have the statements persist across multiple queries in a single `SQLiteBatch` to avoid sqlite having to parse the same statement text over and over. However, we can construct the `SQLiteStatement` on first use instead of always, so I've added a commit to do that.
DrahtBot commented 2026-01-02 23:36:01 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task test max 6 ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/20667709652/job/59343191929
LLM 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `test max 6 ancestor commits`: https://github.com/bitcoin/bitcoin/actions/runs/20667709652/job/59343191929</sub> <sub>LLM reason (✨ experimental): Compilation failed: use of undeclared identifier 'blob' in wallet/sqlite.cpp causing build error.</sub> <details><summary>Hints</summary> 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. </details>
sedited commented 2026-07-24 07:46:53 +00:00 (Migrated from github.com)

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

Ping @davidgumberg @vasild for hopefully another round of review.
Eunovo (Migrated from github.com) reviewed 2026-07-24 13:01:08 +00:00
Eunovo (Migrated from github.com) left a comment
https://github.com/bitcoin/bitcoin/pull/33033/commits/1682818a7b19c7c391fe4a75d96f620b1ac5127c: Looks good to me. Left some comments.
Eunovo (Migrated from github.com) commented 2026-07-24 12:58:49 +00:00

https://github.com/bitcoin/bitcoin/pull/33033/commits/bfa96f8c12ba40fbc66499fa72251bec9e3367e1:

I think it's useful to document that SQLiteStatement can only handle one statement in stmt_text or, preferably, provide the pzTail argument and throw an error if pzTail is not Null after sqlite3_prepare_v2 (this indicates that there is uncompiled SQL code left).

https://github.com/bitcoin/bitcoin/pull/33033/commits/bfa96f8c12ba40fbc66499fa72251bec9e3367e1: I think it's useful to document that `SQLiteStatement` can only handle one statement in `stmt_text` or, preferably, provide the `pzTail` argument and throw an error if `pzTail` is not Null after `sqlite3_prepare_v2` (this indicates that there is uncompiled SQL code left).
Eunovo (Migrated from github.com) commented 2026-07-24 12:47:40 +00:00

https://github.com/bitcoin/bitcoin/pull/33033/commits/b79895c87a3e50de09f7a61887f1389030a94823:

I wonder if Bind should throw an Exception instead? It doesn't look like we can recover from a failure to sqlite3_bind_blob.

https://github.com/bitcoin/bitcoin/pull/33033/commits/b79895c87a3e50de09f7a61887f1389030a94823: I wonder if `Bind` should throw an `Exception` instead? It doesn't look like we can recover from a failure to `sqlite3_bind_blob`.
achow101 (Migrated from github.com) reviewed 2026-07-24 19:09:50 +00:00
achow101 (Migrated from github.com) commented 2026-07-24 19:09:50 +00:00

Not all callers of this will have exception handling, but they all should have handling if it fails.

Not all callers of this will have exception handling, but they all should have handling if it fails.
achow101 (Migrated from github.com) reviewed 2026-07-24 19:13:38 +00:00
achow101 (Migrated from github.com) commented 2026-07-24 19:13:38 +00:00

If I need to retouch.

If I need to retouch.
Eunovo (Migrated from github.com) reviewed 2026-07-27 07:36:05 +00:00
Eunovo (Migrated from github.com) commented 2026-07-27 07:36:05 +00:00

Looks like a good candidate for [[nodiscard]]

Looks like a good candidate for `[[nodiscard]]`
pablomartin4btc (Migrated from github.com) reviewed 2026-07-27 20:16:48 +00:00
pablomartin4btc (Migrated from github.com) left a comment

ACK 1682818a7b19

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).

ACK 1682818a7b19 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](https://github.com/bitcoin/bitcoin/pull/33033/changes#r3645464121) it also).
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:55:54 +00:00

worth considering a LogWarning or at least a doc comment?

worth considering a `LogWarning` or at least a doc comment?
Lines 126-127
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:08:11 +00:00

nit:

            return std::string(text, size);
nit: ```suggestion return std::string(text, size); ```
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:20:38 +00:00

nit (more consistently within the repo):

    } catch (const std::runtime_error& e) {
nit (more consistently within the repo): ```suggestion } catch (const std::runtime_error& e) { ```
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:21:13 +00:00

nit:

        return pragma_read_stmt.Column<int>(0);
nit: ```suggestion return pragma_read_stmt.Column<int>(0); ```
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:49:10 +00:00

nit: same as here.

nit: same as [here](https://github.com/bitcoin/bitcoin/pull/33033/changes#r3659824157).
pablomartin4btc (Migrated from github.com) commented 2026-07-27 20:15:53 +00:00

nit: per doc/developer-notes.md, prefer enum class over plain enum.

    enum class SQLiteStatementType
nit: per [doc/developer-notes.md](https://github.com/bitcoin/bitcoin/blob/master/doc/developer-notes.md), prefer `enum class` over plain `enum`. ```suggestion enum class SQLiteStatementType ```
pablomartin4btc (Migrated from github.com) commented 2026-07-27 18:04:35 +00:00

nit: ExecEraseStatement is never used nor implemented.

nit: `ExecEraseStatement` is never used nor implemented. ```suggestion ```
achow101 (Migrated from github.com) reviewed 2026-08-26 19:40:11 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:40:11 +00:00

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.

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.
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:08 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:49:08 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:14 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:49:14 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:27 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:49:27 +00:00

Removed

Removed
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:33 +00:00
Lines 126-127
achow101 (Migrated from github.com) commented 2026-08-26 19:49:33 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:36 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:49:36 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:45 +00:00
Lines 149-150
achow101 (Migrated from github.com) commented 2026-08-26 19:49:45 +00:00

Done

Done
achow101 (Migrated from github.com) reviewed 2026-08-26 19:49:51 +00:00
achow101 (Migrated from github.com) commented 2026-08-26 19:49:51 +00:00

Done

Done
achow101 commented 2026-08-26 19:51:13 +00:00 (Migrated from github.com)
  • 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.

> * 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 commented 2026-08-26 21:16:41 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `MSan, fuzz`: https://github.com/bitcoin/bitcoin/actions/runs/33007141761/job/98303718292</sub> <sub>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).</sub> <details><summary>Hints</summary> 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. </details>
polespinasa (Migrated from github.com) reviewed 2026-09-24 10:40:58 +00:00
polespinasa (Migrated from github.com) left a comment

cACK

cACK
polespinasa (Migrated from github.com) commented 2026-09-24 09:51:50 +00:00

in 4ace00b4c6 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;

in 4ace00b4c6cd015901f5dcf6e503601c73b54605 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). ```c++ SQLiteStatement(const SQLiteStatement&) = delete; SQLiteStatement& operator=(const SQLiteStatement&) = delete; ```
Lines 138-139
polespinasa (Migrated from github.com) commented 2026-09-24 10:14:02 +00:00

in 244554b20f 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:

        } 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);
``
in 244554b20f8425357dfa4abdc177624192e0f1dd 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: ```suggestion } 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); ``
polespinasa (Migrated from github.com) commented 2026-09-24 10:39:16 +00:00

in 84dd0c3848 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.

in 84dd0c3848b51e03bffae8050ae23994c194cdbe 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.
davidgumberg (Migrated from github.com) reviewed 2026-09-24 23:57:37 +00:00
davidgumberg (Migrated from github.com) commented 2026-09-24 23:57:37 +00:00

+1 This should be marked nodiscard

+1 This should be marked `nodiscard`
First-time contributor

🟠 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 reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:965af1044d9e41839565702e4d9bd0a751eda81f6e8b6402747fa296ef84ebea:7efd3c3ba41667382004cfa7a7db56605da7d8f9b7ab69bc483f27117390ba48 --> <!-- ralph-base:ddea9196493d3b8fd841a36a6c53efd85dac7a05 --> <!-- ralph-head:774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db --> <!-- ralph-case:51081c5bffab0d0e92be681256fa1fac575eaa0ad73d7be1bbc1f2da6e3f9801 --> **🟠 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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db/src/wallet/sqlite.h#L25>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db/src/wallet/sqlite.cpp#L543>) (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`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db/src/wallet/sqlite.cpp#L135>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`774fbc89c9bd`](<https://git.fish.foo/bitcoin/bitcoin/commit/774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db>) · [Full review report](<https://review.fish.foo/traces/33033-774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db-2019-2.html>) · [Previous reports](<https://review.fish.foo/traces/33033/>) [permalink](<https://review.fish.foo/traces/33033-774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db-2019-2.html>)
achow101 (Migrated from github.com) reviewed 2026-10-16 06:15:02 +00:00
Lines 138-139
achow101 (Migrated from github.com) commented 2026-10-16 06:15:02 +00:00

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.

> 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.
DrahtBot commented 2026-10-20 08:51:04 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
pablomartin4btc (Migrated from github.com) reviewed 2026-12-03 02:16:24 +00:00
pablomartin4btc (Migrated from github.com) left a comment

re-ACK 774fbc89c9

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 fa45a1503e;
  • 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.
re-ACK 774fbc89c9bdd5bcf9bd9fc90a17965231b2b4db Thanks for addressing my nits. Also since my previous [review](https://github.com/bitcoin/bitcoin/pull/33033#pullrequestreview-4790064267), @Eunovo and @polespinasa feedback were addressed. I went through some [findings](https://git.fish.foo/bitcoin/bitcoin/pulls/33033#issuecomment-609120) 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 fa45a1503e; - `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.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!33033
No description provided.