summaryrefslogtreecommitdiff
path: root/protocols/Telegram/tdlib/td/tddb/td/db/SqliteConnectionSafe.h
blob: 6e45e79e63d9100c33a5d8cc848ea7f6e75ed947 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// 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)
//
#pragma once

#include "td/actor/SchedulerLocalStorage.h"

#include "td/db/SqliteDb.h"

#include "td/utils/common.h"
#include "td/utils/format.h"
#include "td/utils/logging.h"

namespace td {

class SqliteConnectionSafe {
 public:
  SqliteConnectionSafe() = default;
  explicit SqliteConnectionSafe(string name, DbKey key = DbKey::empty())
      : lsls_connection_([name = name, key = std::move(key)] {
        auto db = SqliteDb::open_with_key(name, key).move_as_ok();
        db.exec("PRAGMA synchronous=NORMAL").ensure();
        db.exec("PRAGMA temp_store=MEMORY").ensure();
        db.exec("PRAGMA secure_delete=1").ensure();
        db.exec("PRAGMA recursive_triggers=1").ensure();
        return db;
      })
      , name_(std::move(name)) {
  }

  SqliteDb &get() {
    return lsls_connection_.get();
  }

  void close() {
    LOG(INFO) << "Close sqlite db " << tag("path", name_);
    lsls_connection_.clear_values();
  }
  void close_and_destroy() {
    close();
    LOG(INFO) << "Destroy sqlite db " << tag("path", name_);
    SqliteDb::destroy(name_).ignore();
  }

 private:
  LazySchedulerLocalStorage<SqliteDb> lsls_connection_;
  string name_;
};

}  // namespace td