tdlight/tddb/td/db/detail/RawSqliteDb.cpp

61 lines
1.6 KiB
C++
Raw Normal View History

//
2022-01-01 01:35:39 +01:00
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/db/detail/RawSqliteDb.h"
#include "sqlite/sqlite3.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
2021-09-22 10:33:28 +02:00
#include "td/utils/misc.h"
#include "td/utils/port/path.h"
#include "td/utils/port/Stat.h"
2022-06-30 00:32:32 +02:00
#include <atomic>
namespace td {
namespace detail {
2022-06-30 00:32:32 +02:00
static std::atomic<bool> was_database_destroyed{false};
Status RawSqliteDb::last_error(sqlite3 *db, CSlice path) {
return Status::Error(PSLICE() << Slice(sqlite3_errmsg(db)) << " for database \"" << path << '"');
}
Status RawSqliteDb::destroy(Slice path) {
Status error;
with_db_path(path, [&](auto path) {
unlink(path).ignore();
2021-09-22 10:33:28 +02:00
if (!ends_with(path, "-shm") && !stat(path).is_error()) {
error = Status::Error(PSLICE() << "Failed to delete file \"" << path << '"');
}
});
return error;
}
Status RawSqliteDb::last_error() {
//If database was corrupted, try to delete it.
auto code = sqlite3_errcode(db_);
if (code == SQLITE_CORRUPT) {
2022-06-30 00:32:32 +02:00
was_database_destroyed.store(true, std::memory_order_relaxed);
destroy(path_).ignore();
}
return last_error(db_, path());
}
2022-06-30 00:32:32 +02:00
bool RawSqliteDb::was_any_database_destroyed() {
return was_database_destroyed.load(std::memory_order_relaxed);
}
RawSqliteDb::~RawSqliteDb() {
auto rc = sqlite3_close(db_);
LOG_IF(FATAL, rc != SQLITE_OK) << last_error(db_, path());
}
} // namespace detail
} // namespace td