Skip to content

Commit ff9d961

Browse files
committed
wallet: Add tracing for sqlite statements
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.
1 parent 9e54dde commit ff9d961

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
@@ -34,6 +34,21 @@ static void ErrorLogCallback(void* arg, int code, const char* msg)
3434
LogPrintf("SQLite Error. Code: %d. Message: %s\n", code, msg);
3535
}
3636

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

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

0 commit comments

Comments
 (0)