database.hpp 10.1 KB
Newer Older
1 2
#pragma once

3 4 5
#include <biboumi.h>
#ifdef USE_DATABASE

6 7 8
#include <database/table.hpp>
#include <database/column.hpp>
#include <database/count_query.hpp>
9

louiz’'s avatar
louiz’ committed
10 11
#include <database/engine.hpp>

12
#include <utils/optional_bool.hpp>
louiz’'s avatar
louiz’ committed
13
#include <utils/datetime.hpp>
14

15
#include <chrono>
16 17 18
#include <string>

#include <memory>
19
#include <map>
20

21 22
class Database
{
23
 public:
24
  struct RecordNotFound: public std::exception {};
25
  enum class Paging { first, last };
26

27
  struct Uuid: Column<std::string> { static constexpr auto name = "uuid_"; };
28

29
  struct Owner: Column<std::string> { static constexpr auto name = "owner_"; };
30

louiz’'s avatar
louiz’ committed
31
  struct IrcChanName: Column<std::string> { static constexpr auto name = "ircchanname_"; };
32

33
  struct Channel: Column<std::string> { static constexpr auto name = "channel_"; };
34

louiz’'s avatar
louiz’ committed
35
  struct IrcServerName: Column<std::string> { static constexpr auto name = "ircservername_"; };
36

37
  struct Server: Column<std::string> { static constexpr auto name = "server_"; };
38

louiz’'s avatar
louiz’ committed
39 40
  struct OldDate: Column<std::chrono::system_clock::time_point::rep> { static constexpr auto name = "date_"; };
  struct Date: Column<DateTime> { static constexpr auto name = "date_"; };
41

42
  struct Body: Column<std::string> { static constexpr auto name = "body_"; };
43

44
  struct Nick: Column<std::string> { static constexpr auto name = "nick_"; };
45

46
  struct Pass: Column<std::string> { static constexpr auto name = "pass_"; };
47

48 49
  struct Ports: Column<std::string> { static constexpr auto name = "ports_";
    Ports(): Column<std::string>("6667") {} };
50

louiz’'s avatar
louiz’ committed
51
  struct TlsPorts: Column<std::string> { static constexpr auto name = "tlsports_";
52
    TlsPorts(): Column<std::string>("6697;6670") {} };
53

54
  struct Username: Column<std::string> { static constexpr auto name = "username_"; };
55

56
  struct Realname: Column<std::string> { static constexpr auto name = "realname_"; };
57

louiz’'s avatar
louiz’ committed
58
  struct AfterConnectionCommand: Column<std::string> { static constexpr auto name = "afterconnectioncommand_"; };
59

louiz’'s avatar
louiz’ committed
60
  struct TrustedFingerprint: Column<std::string> { static constexpr auto name = "trustedfingerprint_"; };
61

louiz’'s avatar
louiz’ committed
62
  struct EncodingOut: Column<std::string> { static constexpr auto name = "encodingout_"; };
63

louiz’'s avatar
louiz’ committed
64
  struct EncodingIn: Column<std::string> { static constexpr auto name = "encodingin_"; };
65

louiz’'s avatar
louiz’ committed
66
  struct MaxHistoryLength: Column<int> { static constexpr auto name = "maxhistorylength_";
67
    MaxHistoryLength(): Column<int>(20) {} };
68

louiz’'s avatar
louiz’ committed
69
  struct RecordHistory: Column<bool> { static constexpr auto name = "recordhistory_";
70
    RecordHistory(): Column<bool>(true) {}};
71

72
  struct RecordHistoryOptional: Column<OptionalBool> { static constexpr auto name = "recordhistory_"; };
73

louiz’'s avatar
louiz’ committed
74
  struct VerifyCert: Column<bool> { static constexpr auto name = "verifycert_";
75
    VerifyCert(): Column<bool>(true) {} };
76 77

  struct Persistent: Column<bool> { static constexpr auto name = "persistent_";
78
    Persistent(): Column<bool>(false) {} };
79

80 81 82
  struct GlobalPersistent: Column<bool> { static constexpr auto name = "persistent_";
    GlobalPersistent(); };

83 84 85 86
  struct LocalJid: Column<std::string> { static constexpr auto name = "local"; };

  struct RemoteJid: Column<std::string> { static constexpr auto name = "remote"; };

87
  struct Address: Column<std::string> { static constexpr auto name = "address_"; };
88

89 90
  using MucLogLineTable = Table<Id, Uuid, Owner, IrcChanName, IrcServerName, Date, Body, Nick>;
  using MucLogLine = MucLogLineTable::RowType;
louiz’'s avatar
louiz’ committed
91 92
  using OldMucLogLineTable = Table<Id, Uuid, Owner, IrcChanName, IrcServerName, OldDate, Body, Nick>;
  using OldMucLogLine = OldMucLogLineTable::RowType;
93

94
  using GlobalOptionsTable = Table<Id, Owner, MaxHistoryLength, RecordHistory, GlobalPersistent>;
95 96
  using GlobalOptions = GlobalOptionsTable::RowType;

97
  using IrcServerOptionsTable = Table<Id, Owner, Server, Pass, TlsPorts, Ports, Username, Realname, VerifyCert, TrustedFingerprint, EncodingOut, EncodingIn, MaxHistoryLength, Address, Nick>;
98 99
  using IrcServerOptions = IrcServerOptionsTable::RowType;

100
  using IrcChannelOptionsTable = Table<Id, Owner, Server, Channel, EncodingOut, EncodingIn, MaxHistoryLength, Persistent, RecordHistoryOptional>;
101 102
  using IrcChannelOptions = IrcChannelOptionsTable::RowType;

103 104 105
  using RosterTable = Table<LocalJid, RemoteJid>;
  using RosterItem = RosterTable::RowType;

106 107 108
  using AfterConnectionCommandsTable = Table<Id, ForeignKey, AfterConnectionCommand>;
  using AfterConnectionCommands = std::vector<AfterConnectionCommandsTable::RowType>;

109 110 111
  Database() = default;
  ~Database() = default;

louiz’'s avatar
louiz’ committed
112 113 114 115 116
  Database(const Database&) = delete;
  Database(Database&&) = delete;
  Database& operator=(const Database&) = delete;
  Database& operator=(Database&&) = delete;

117 118
  static GlobalOptions get_global_options(const std::string& owner);
  static IrcServerOptions get_irc_server_options(const std::string& owner,
119
                                                     const std::string& server);
120 121 122 123 124 125 126 127 128
  static IrcChannelOptions get_irc_channel_options(const std::string& owner,
                                                   const std::string& server,
                                                   const std::string& channel);
  static IrcChannelOptions get_irc_channel_options_with_server_default(const std::string& owner,
                                                                       const std::string& server,
                                                                       const std::string& channel);
  static IrcChannelOptions get_irc_channel_options_with_server_and_global_default(const std::string& owner,
                                                                                  const std::string& server,
                                                                                  const std::string& channel);
129 130 131
  static AfterConnectionCommands get_after_connection_commands(const IrcServerOptions& server_options);
  static void set_after_connection_commands(const IrcServerOptions& server_options, AfterConnectionCommands& commands);

132 133
  /**
   * Get all the lines between (optional) start and end dates, with a (optional) limit.
134
   * If after_id is set, only the records after it will be returned.
135
   */
136
  static std::vector<MucLogLine> get_muc_logs(const std::string& owner, const std::string& chan_name, const std::string& server,
137
                                              int limit=-1, const std::string& start="", const std::string& end="",
138
                                              const Id::real_type reference_record_id=Id::unset_value, Paging=Paging::first);
139

140 141 142 143 144
  /**
   * Get just one single record matching the given uuid, between (optional) end and start.
   * If it does not exist (or is not between end and start), throw a RecordNotFound exception.
   */
  static MucLogLine get_muc_log(const std::string& owner, const std::string& chan_name, const std::string& server, const std::string& uuid, const std::string& start="", const std::string& end="");
145
  static std::string store_muc_message(const std::string& owner, const std::string& chan_name, const std::string& server_name,
louiz’'s avatar
louiz’ committed
146
                                       DateTime::time_point date, const std::string& body, const std::string& nick);
147

148 149 150 151 152 153
  static void add_roster_item(const std::string& local, const std::string& remote);
  static bool has_roster_item(const std::string& local, const std::string& remote);
  static void delete_roster_item(const std::string& local, const std::string& remote);
  static std::vector<Database::RosterItem> get_contact_list(const std::string& local);
  static std::vector<Database::RosterItem> get_full_roster();

154
  static void close();
155
  static void open(const std::string& filename);
156

157
  template <typename TableType>
158
  static int64_t count(const TableType& table)
159 160
  {
    CountQuery query{table.get_name()};
louiz’'s avatar
louiz’ committed
161
    return query.execute(*Database::db);
162 163 164 165 166 167
  }

  static MucLogLineTable muc_log_lines;
  static GlobalOptionsTable global_options;
  static IrcServerOptionsTable irc_server_options;
  static IrcChannelOptionsTable irc_channel_options;
168
  static RosterTable roster;
169 170
  static AfterConnectionCommandsTable after_connection_commands;

louiz’'s avatar
louiz’ committed
171
  static std::unique_ptr<DatabaseEngine> db;
172

louiz’'s avatar
louiz’ committed
173 174 175 176 177 178 179
  static DatabaseEngine::EngineType engine_type()
  {
    if (Database::db)
      return Database::db->engine_type();
    return DatabaseEngine::EngineType::None;
  }

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  /**
   * Some caches, to avoid doing very frequent query requests for a few options.
   */
  using CacheKey = std::tuple<std::string, std::string, std::string>;

  static EncodingIn::real_type get_encoding_in(const std::string& owner,
                                        const std::string& server,
                                        const std::string& channel)
  {
    CacheKey channel_key{owner, server, channel};
    auto it = Database::encoding_in_cache.find(channel_key);
    if (it == Database::encoding_in_cache.end())
      {
        auto options = Database::get_irc_channel_options_with_server_default(owner, server, channel);
        EncodingIn::real_type result = options.col<Database::EncodingIn>();
        if (result.empty())
          result = "ISO-8859-1";
        it = Database::encoding_in_cache.insert(std::make_pair(channel_key, result)).first;
      }
    return it->second;
  }
  static void invalidate_encoding_in_cache(const std::string& owner,
                                           const std::string& server,
                                           const std::string& channel)
  {
    CacheKey channel_key{owner, server, channel};
    Database::encoding_in_cache.erase(channel_key);
  }
  static void invalidate_encoding_in_cache()
  {
    Database::encoding_in_cache.clear();
  }

louiz’'s avatar
louiz’ committed
213 214
  static auto raw_exec(const std::string& query)
  {
215
    return Database::db->raw_exec(query);
louiz’'s avatar
louiz’ committed
216 217
  }

218
 private:
219
  static std::string gen_uuid();
220
  static std::map<CacheKey, EncodingIn::real_type> encoding_in_cache;
221
};
222 223 224 225 226 227

class Transaction
{
public:
  Transaction();
  ~Transaction();
louiz’'s avatar
louiz’ committed
228
  void rollback();
229 230 231
  bool success{false};
};

louiz’'s avatar
louiz’ committed
232 233 234 235 236 237 238 239 240 241 242 243
template <typename... T>
void convert_date_format(DatabaseEngine& db, Table<T...> table)
{
  const auto existing_columns = db.get_all_columns_from_table(table.get_name());
  const auto date_pair = existing_columns.find(Database::Date::name);
  if (date_pair != existing_columns.end() && date_pair->second == "integer")
    {
      log_info("Converting Date_ format to the new one.");
      db.convert_date_format(db);
    }
}

244
#endif /* USE_DATABASE */