modernize: Replace most remaining old-style connects by PMF ones
[quassel.git] / src / core / abstractsqlstorage.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #pragma once
22
23 #include "storage.h"
24
25 #include <memory>
26
27 #include <QSqlDatabase>
28 #include <QSqlQuery>
29 #include <QSqlError>
30
31 class AbstractSqlMigrationReader;
32 class AbstractSqlMigrationWriter;
33
34 class AbstractSqlStorage : public Storage
35 {
36     Q_OBJECT
37
38 public:
39     AbstractSqlStorage(QObject *parent = nullptr);
40     ~AbstractSqlStorage() override;
41
42     virtual std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() { return {}; }
43     virtual std::unique_ptr<AbstractSqlMigrationWriter> createMigrationWriter() { return {}; }
44
45 public slots:
46     State init(const QVariantMap &settings = QVariantMap(),
47                        const QProcessEnvironment &environment = {},
48                        bool loadFromEnvironment = false) override;
49     bool setup(const QVariantMap &settings = QVariantMap(),
50                        const QProcessEnvironment &environment = {},
51                        bool loadFromEnvironment = false) override;
52
53 protected:
54     inline void sync() override {};
55
56     QSqlDatabase logDb();
57
58     /**
59      * Fetch an SQL query string by name and optional schema version
60      *
61      * Loads the named SQL query from the built-in SQL resource collection, returning it as a
62      * string.  If a version is specified, it'll be loaded from the schema version-specific folder
63      * instead.
64      *
65      * @see schemaVersion()
66      *
67      * @param[in] queryName  File name of the SQL query, minus the .sql extension
68      * @param[in] version
69      * @parblock
70      * SQL schema version; if 0, fetches from current version, otherwise loads from the specified
71      * schema version instead of the current schema files.
72      * @endparblock
73      * @return String with the requested SQL query, ready for parameter substitution
74      */
75     QString queryString(const QString &queryName, int version = 0);
76
77     QStringList setupQueries();
78
79     QStringList upgradeQueries(int ver);
80     bool upgradeDb();
81
82     bool watchQuery(QSqlQuery &query);
83
84     int schemaVersion();
85     virtual int installedSchemaVersion() { return -1; };
86     virtual bool updateSchemaVersion(int newVersion) = 0;
87     virtual bool setupSchemaVersion(int version) = 0;
88
89     virtual void setConnectionProperties(const QVariantMap &properties,
90                                          const QProcessEnvironment &environment,
91                                          bool loadFromEnvironment) = 0;
92     virtual QString driverName() = 0;
93     inline virtual QString hostName() { return QString(); }
94     inline virtual int port() { return -1; }
95     virtual QString databaseName() = 0;
96     inline virtual QString userName() { return QString(); }
97     inline virtual QString password() { return QString(); }
98
99     //! Initialize db specific features on connect
100     /** This is called every time a connection to a specific SQL backend is established
101      *  the default implementation does nothing.
102      *
103      *  When reimplementing this method, don't use logDB() inside this function as
104      *  this would cause as we're just about to initialize that DB connection.
105      */
106     inline virtual bool initDbSession(QSqlDatabase & /* db */) { return true; }
107
108 private slots:
109     void connectionDestroyed();
110
111 private:
112     void addConnectionToPool();
113     void dbConnect(QSqlDatabase &db);
114
115     int _schemaVersion{0};
116     bool _debug;
117
118     static int _nextConnectionId;
119     QMutex _connectionPoolMutex;
120     // we let a Connection Object manage each actual db connection
121     // those objects reside in the thread the connection belongs to
122     // which allows us thread safe termination of a connection
123     class Connection;
124     QHash<QThread *, Connection *> _connectionPool;
125 };
126
127 struct SenderData {
128     QString sender;
129     QString realname;
130     QString avatarurl;
131
132     friend uint qHash(const SenderData &key);
133     friend bool operator==(const SenderData &a, const SenderData &b);
134 };
135
136 // ========================================
137 //  AbstractSqlStorage::Connection
138 // ========================================
139 class AbstractSqlStorage::Connection : public QObject
140 {
141     Q_OBJECT
142
143 public:
144     Connection(const QString &name, QObject *parent = nullptr);
145     ~Connection() override;
146
147     inline QLatin1String name() const { return QLatin1String(_name); }
148
149 private:
150     QByteArray _name;
151 };
152
153
154 // ========================================
155 //  AbstractSqlMigrator
156 // ========================================
157 class AbstractSqlMigrator
158 {
159 public:
160     // migration objects
161     struct QuasselUserMO {
162         UserId id;
163         QString username;
164         QString password;
165         int hashversion;
166         QString authenticator;
167     };
168
169     struct SenderMO {
170         qint64 senderId{0};
171         QString sender;
172         QString realname;
173         QString avatarurl;
174     };
175
176     struct IdentityMO {
177         IdentityId id;
178         UserId userid;
179         QString identityname;
180         QString realname;
181         QString awayNick;
182         bool awayNickEnabled;
183         QString awayReason;
184         bool awayReasonEnabled;
185         bool autoAwayEnabled;
186         int autoAwayTime;
187         QString autoAwayReason;
188         bool autoAwayReasonEnabled;
189         bool detachAwayEnabled;
190         QString detachAwayReason;
191         bool detachAwayReasonEnabled;
192         QString ident;
193         QString kickReason;
194         QString partReason;
195         QString quitReason;
196         QByteArray sslCert;
197         QByteArray sslKey;
198     };
199
200     struct IdentityNickMO {
201         int nickid;
202         IdentityId identityId;
203         QString nick;
204     };
205
206     struct NetworkMO {
207         UserId userid;
208         QString networkname;
209         QString perform;
210         QString autoidentifyservice;
211         QString autoidentifypassword;
212         QString saslaccount;
213         QString saslpassword;
214         QString servercodec;
215         QString encodingcodec;
216         QString decodingcodec;
217         QString usermode;
218         QString awaymessage;
219         QString attachperform;
220         QString detachperform;
221         NetworkId networkid;
222         IdentityId identityid;
223         int messagerateburstsize;
224         int messageratedelay;
225         int autoreconnectinterval;
226         int autoreconnectretries;
227         bool rejoinchannels;
228         bool userandomserver;
229         bool useautoidentify;
230         bool usesasl;
231         bool useautoreconnect;
232         bool unlimitedconnectretries;
233         bool usecustommessagerate;
234         bool unlimitedmessagerate;
235         bool connected;
236     };
237
238     struct BufferMO {
239         BufferId bufferid;
240         UserId userid;
241         int groupid;
242         NetworkId networkid;
243         QString buffername;
244         QString buffercname;
245         int buffertype;
246         qint64 lastmsgid;
247         qint64 lastseenmsgid;
248         qint64 markerlinemsgid;
249         int bufferactivity;
250         int highlightcount;
251         QString key;
252         bool joined;
253         QString cipher;
254     };
255
256     struct BacklogMO {
257         MsgId messageid;
258         QDateTime time; // has to be in UTC!
259         BufferId bufferid;
260         int type;
261         int flags;
262         qint64 senderid;
263         QString senderprefixes;
264         QString message;
265     };
266
267     struct IrcServerMO {
268         int serverid;
269         UserId userid;
270         NetworkId networkid;
271         QString hostname;
272         int port;
273         QString password;
274         bool ssl;
275         bool sslverify;     /// If true, validate SSL certificates
276         int sslversion;
277         bool useproxy;
278         int proxytype;
279         QString proxyhost;
280         int proxyport;
281         QString proxyuser;
282         QString proxypass;
283     };
284
285     struct UserSettingMO {
286         UserId userid;
287         QString settingname;
288         QByteArray settingvalue;
289     };
290
291     struct CoreStateMO {
292         QString key;
293         QByteArray value;
294     };
295
296     enum MigrationObject {
297         QuasselUser,
298         Sender,
299         Identity,
300         IdentityNick,
301         Network,
302         Buffer,
303         Backlog,
304         IrcServer,
305         UserSetting,
306         CoreState
307     };
308
309     virtual ~AbstractSqlMigrator() = default;
310
311     static QString migrationObject(MigrationObject moType);
312
313 protected:
314     void newQuery(const QString &query, QSqlDatabase db);
315     virtual void resetQuery();
316     virtual bool prepareQuery(MigrationObject mo) = 0;
317     bool exec();
318     inline bool next() { return _query->next(); }
319     inline QVariant value(int index) { return _query->value(index); }
320     inline void bindValue(const QString &placeholder, const QVariant &val) { _query->bindValue(placeholder, val); }
321     inline void bindValue(int pos, const QVariant &val) { _query->bindValue(pos, val); }
322
323     inline QSqlError lastError() { return _query ? _query->lastError() : QSqlError(); }
324     void dumpStatus();
325     inline QString executedQuery() { return _query ? _query->executedQuery() : QString(); }
326     inline QVariantList boundValues();
327
328     virtual bool transaction() = 0;
329     virtual void rollback() = 0;
330     virtual bool commit() = 0;
331
332 private:
333     QSqlQuery *_query{nullptr};
334 };
335
336
337 class AbstractSqlMigrationReader : public AbstractSqlMigrator
338 {
339 public:
340     AbstractSqlMigrationReader();
341
342     virtual bool readMo(QuasselUserMO &user) = 0;
343     virtual bool readMo(IdentityMO &identity) = 0;
344     virtual bool readMo(IdentityNickMO &identityNick) = 0;
345     virtual bool readMo(NetworkMO &network) = 0;
346     virtual bool readMo(BufferMO &buffer) = 0;
347     virtual bool readMo(SenderMO &sender) = 0;
348     virtual bool readMo(BacklogMO &backlog) = 0;
349     virtual bool readMo(IrcServerMO &ircserver) = 0;
350     virtual bool readMo(UserSettingMO &userSetting) = 0;
351     virtual bool readMo(CoreStateMO &coreState) = 0;
352
353     bool migrateTo(AbstractSqlMigrationWriter *writer);
354
355 private:
356     void abortMigration(const QString &errorMsg = QString());
357     bool finalizeMigration();
358
359     template<typename T> bool transferMo(MigrationObject moType, T &mo);
360
361     AbstractSqlMigrationWriter *_writer{nullptr};
362 };
363
364
365 class AbstractSqlMigrationWriter : public AbstractSqlMigrator
366 {
367 public:
368     virtual bool writeMo(const QuasselUserMO &user) = 0;
369     virtual bool writeMo(const IdentityMO &identity) = 0;
370     virtual bool writeMo(const IdentityNickMO &identityNick) = 0;
371     virtual bool writeMo(const NetworkMO &network) = 0;
372     virtual bool writeMo(const BufferMO &buffer) = 0;
373     virtual bool writeMo(const SenderMO &sender) = 0;
374     virtual bool writeMo(const BacklogMO &backlog) = 0;
375     virtual bool writeMo(const IrcServerMO &ircserver) = 0;
376     virtual bool writeMo(const UserSettingMO &userSetting) = 0;
377     virtual bool writeMo(const CoreStateMO &coreState) = 0;
378
379     inline bool migrateFrom(AbstractSqlMigrationReader *reader) { return reader->migrateTo(this); }
380
381     // called after migration process
382     virtual inline bool postProcess() { return true; }
383     friend class AbstractSqlMigrationReader;
384 };