Skip to content

Commit

Permalink
Implement SQLiteDatabase::Verify
Browse files Browse the repository at this point in the history
  • Loading branch information
achow101 committed Oct 14, 2020
1 parent b4df8fd commit 727e6b2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
52 changes: 51 additions & 1 deletion src/wallet/sqlite.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,44 @@ void SQLiteDatabase::Cleanup() noexcept
}
}

bool SQLiteDatabase::Verify(bilingual_str& error)
{
assert(m_db);

sqlite3_stmt* stmt{nullptr};
ret = sqlite3_prepare_v2(m_db, "PRAGMA integrity_check", -1, &stmt, nullptr);
if (ret != SQLITE_OK) {
sqlite3_finalize(stmt);
error = strprintf(_("SQLiteDatabase: Failed to prepare statement to verify database: %s"), sqlite3_errstr(ret));
return false;
}
while (true) {
ret = sqlite3_step(stmt);
if (ret == SQLITE_DONE) {
break;
}
if (ret != SQLITE_ROW) {
error = strprintf(_("SQLiteDatabase: Failed to execute statement to verify database: %s"), sqlite3_errstr(ret));
break;
}
const char* msg = (const char*)sqlite3_column_text(stmt, 0);
if (!msg) {
error = strprintf(_("SQLiteDatabase: Failed to read database verification error: %s"), sqlite3_errstr(ret));
break;
}
std::string str_msg(msg);
if (str_msg == "ok") {
continue;
}
if (error.empty()) {
error = _("Failed to verify database") + Untranslated("\n");
}
error += Untranslated(strprintf("%s\n", str_msg));
}
sqlite3_finalize(stmt);
return error.empty();
}

void SQLiteDatabase::Open()
{
int flags = SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
Expand Down Expand Up @@ -468,7 +506,19 @@ bool ExistsSQLiteDatabase(const fs::path& path)

std::unique_ptr<SQLiteDatabase> MakeSQLiteDatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error)
{
return MakeUnique<SQLiteDatabase>(path, path / DATABASE_FILENAME);
const fs::path file = path / DATABASE_FILENAME;
try {
auto db = MakeUnique<SQLiteDatabase>(path, file);
if (options.verify && !db->Verify(error)) {
status = DatabaseStatus::FAILED_VERIFY;
return nullptr;
}
return db;
} catch (const std::runtime_error& e) {
status = DatabaseStatus::FAILED_LOAD;
error.original = e.what();
return nullptr;
}
}

std::string SQLiteDatabaseVersion()
Expand Down
2 changes: 2 additions & 0 deletions src/wallet/sqlite.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ class SQLiteDatabase : public WalletDatabase

~SQLiteDatabase();

bool Verify(bilingual_str& error);

/** Open the database if it is not already opened */
void Open() override;

Expand Down

0 comments on commit 727e6b2

Please sign in to comment.