2018-12-31 20:04:05 +01:00
|
|
|
//
|
2022-01-01 01:35:39 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// 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"
|
2018-12-31 20:04:05 +01:00
|
|
|
#include "td/utils/port/path.h"
|
2018-06-07 21:56:03 +02:00
|
|
|
#include "td/utils/port/Stat.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
|
2022-06-30 00:32:32 +02:00
|
|
|
#include <atomic>
|
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
namespace td {
|
|
|
|
namespace detail {
|
2018-06-26 01:43:11 +02:00
|
|
|
|
2022-06-30 00:32:32 +02:00
|
|
|
static std::atomic<bool> was_database_destroyed{false};
|
|
|
|
|
2022-08-04 13:37:08 +02:00
|
|
|
Status RawSqliteDb::last_error(tdsqlite3 *db, CSlice path) {
|
|
|
|
return Status::Error(PSLICE() << Slice(tdsqlite3_errmsg(db)) << " for database \"" << path << '"');
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
2018-06-26 01:43:11 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
Status RawSqliteDb::destroy(Slice path) {
|
2018-06-07 21:56:03 +02:00
|
|
|
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()) {
|
2020-02-19 02:34:55 +01:00
|
|
|
error = Status::Error(PSLICE() << "Failed to delete file \"" << path << '"');
|
2018-06-07 21:56:03 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
return error;
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
2018-06-26 01:43:11 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
Status RawSqliteDb::last_error() {
|
|
|
|
//If database was corrupted, try to delete it.
|
2022-08-04 13:37:08 +02:00
|
|
|
auto code = tdsqlite3_errcode(db_);
|
2018-12-31 20:04:05 +01:00
|
|
|
if (code == SQLITE_CORRUPT) {
|
2022-06-30 00:32:32 +02:00
|
|
|
was_database_destroyed.store(true, std::memory_order_relaxed);
|
2018-12-31 20:04:05 +01:00
|
|
|
destroy(path_).ignore();
|
|
|
|
}
|
|
|
|
|
2020-02-19 02:34:55 +01:00
|
|
|
return last_error(db_, path());
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
2018-06-26 01:43:11 +02:00
|
|
|
|
2022-06-30 00:32:32 +02:00
|
|
|
bool RawSqliteDb::was_any_database_destroyed() {
|
|
|
|
return was_database_destroyed.load(std::memory_order_relaxed);
|
|
|
|
}
|
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
RawSqliteDb::~RawSqliteDb() {
|
2022-08-04 13:37:08 +02:00
|
|
|
auto rc = tdsqlite3_close(db_);
|
2020-02-19 02:34:55 +01:00
|
|
|
LOG_IF(FATAL, rc != SQLITE_OK) << last_error(db_, path());
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace detail
|
|
|
|
} // namespace td
|