2019-10-03 19:15:15 +02:00
|
|
|
//
|
2022-01-01 01:35:39 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022
|
2019-10-03 19:15:15 +02: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/SqliteConnectionSafe.h"
|
|
|
|
|
|
|
|
#include "td/utils/common.h"
|
|
|
|
#include "td/utils/format.h"
|
|
|
|
#include "td/utils/logging.h"
|
|
|
|
|
|
|
|
namespace td {
|
|
|
|
|
2020-08-14 16:48:43 +02:00
|
|
|
SqliteConnectionSafe::SqliteConnectionSafe(string path, DbKey key, optional<int32> cipher_version)
|
|
|
|
: path_(std::move(path))
|
2022-07-30 11:33:57 +02:00
|
|
|
, lsls_connection_([path = path_, close_state_ptr = &close_state_, key = std::move(key),
|
|
|
|
cipher_version = std::move(cipher_version)] {
|
2021-09-22 18:04:56 +02:00
|
|
|
auto r_db = SqliteDb::open_with_key(path, false, key, cipher_version.copy());
|
2019-10-03 19:15:15 +02:00
|
|
|
if (r_db.is_error()) {
|
2022-07-30 11:33:57 +02:00
|
|
|
LOG(FATAL) << "Can't open database in state " << *close_state_ptr << ": " << r_db.error().message();
|
2019-10-03 19:15:15 +02:00
|
|
|
}
|
|
|
|
auto db = r_db.move_as_ok();
|
2021-09-23 10:20:42 +02:00
|
|
|
db.exec("PRAGMA journal_mode=WAL").ensure();
|
2019-10-03 19:15:15 +02:00
|
|
|
db.exec("PRAGMA secure_delete=1").ensure();
|
|
|
|
return db;
|
|
|
|
}) {
|
|
|
|
}
|
|
|
|
|
2020-08-14 16:11:58 +02:00
|
|
|
void SqliteConnectionSafe::set(SqliteDb &&db) {
|
|
|
|
lsls_connection_.set(std::move(db));
|
|
|
|
}
|
|
|
|
|
2019-10-03 19:15:15 +02:00
|
|
|
SqliteDb &SqliteConnectionSafe::get() {
|
|
|
|
return lsls_connection_.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
void SqliteConnectionSafe::close() {
|
2019-10-03 19:38:47 +02:00
|
|
|
LOG(INFO) << "Close SQLite database " << tag("path", path_);
|
2022-07-30 11:33:57 +02:00
|
|
|
close_state_++;
|
2019-10-03 19:15:15 +02:00
|
|
|
lsls_connection_.clear_values();
|
|
|
|
}
|
|
|
|
|
|
|
|
void SqliteConnectionSafe::close_and_destroy() {
|
|
|
|
close();
|
2019-10-03 19:38:47 +02:00
|
|
|
LOG(INFO) << "Destroy SQLite database " << tag("path", path_);
|
2022-07-30 11:33:57 +02:00
|
|
|
close_state_ += 65536;
|
2019-10-03 19:38:47 +02:00
|
|
|
SqliteDb::destroy(path_).ignore();
|
2019-10-03 19:15:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
} // namespace td
|