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