Skip to content

Commit f4a8269

Browse files
committed
Merge bitcoin/bitcoin#27801: wallet: Add tracing for sqlite statements
ff9d961 wallet: Add tracing for sqlite statements (Ryan Ofsky) Pull request description: I found sqlite tracing was useful for debugging a test in #27790, and thought it might be helpful in other contexts too, so this PR adds an option to enable it. Tracing is still disabled by default and only shown with `-debug=walletdb -loglevel=walletdb:trace` options. ACKs for top commit: achow101: ACK ff9d961 kevkevinpal: ACK bitcoin/bitcoin@ff9d961 theStack: ACK ff9d961 Tree-SHA512: 592fabfab3218cec36c2d00a21cd535fa840daa126ee8440c384952fbb3913180aa3796066c630087e933d6517f19089b867f158e0b737f25283a14799eefb05
2 parents 7f20197 + ff9d961 commit f4a8269

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/wallet/sqlite.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,21 @@ static void ErrorLogCallback(void* arg, int code, const char* msg)
3535
LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg);
3636
}
3737

38+
static int TraceSqlCallback(unsigned code, void* context, void* param1, void* param2)
39+
{
40+
auto* db = static_cast<SQLiteDatabase*>(context);
41+
if (code == SQLITE_TRACE_STMT) {
42+
auto* stmt = static_cast<sqlite3_stmt*>(param1);
43+
// To be conservative and avoid leaking potentially secret information
44+
// in the log file, only expand statements that query the database, not
45+
// statements that update the database.
46+
char* expanded{sqlite3_stmt_readonly(stmt) ? sqlite3_expanded_sql(stmt) : nullptr};
47+
LogPrintf("[%s] SQLite Statement: %s\n", db->Filename(), expanded ? expanded : sqlite3_sql(stmt));
48+
if (expanded) sqlite3_free(expanded);
49+
}
50+
return SQLITE_OK;
51+
}
52+
3853
static bool BindBlobToStatement(sqlite3_stmt* stmt,
3954
int index,
4055
Span<const std::byte> blob,
@@ -240,6 +255,13 @@ void SQLiteDatabase::Open()
240255
if (ret != SQLITE_OK) {
241256
throw std::runtime_error(strprintf("SQLiteDatabase: Failed to enable extended result codes: %s\n", sqlite3_errstr(ret)));
242257
}
258+
// Trace SQL statements if tracing is enabled with -debug=walletdb -loglevel=walletdb:trace
259+
if (LogAcceptCategory(BCLog::WALLETDB, BCLog::Level::Trace)) {
260+
ret = sqlite3_trace_v2(m_db, SQLITE_TRACE_STMT, TraceSqlCallback, this);
261+
if (ret != SQLITE_OK) {
262+
LogPrintf("Failed to enable SQL tracing for %s\n", Filename());
263+
}
264+
}
243265
}
244266

245267
if (sqlite3_db_readonly(m_db, "main") != 0) {

0 commit comments

Comments
 (0)