7e436fce41a12ed1121693d2c43b79c100e05296
[quassel.git] / src / core / abstractsqlstorage.cpp
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 #include "abstractsqlstorage.h"
22 #include "quassel.h"
23
24 #include "logger.h"
25
26 #include <QMutexLocker>
27 #include <QSqlDriver>
28 #include <QSqlError>
29 #include <QSqlField>
30 #include <QSqlQuery>
31
32 int AbstractSqlStorage::_nextConnectionId = 0;
33 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
34     : Storage(parent),
35     _schemaVersion(0)
36 {
37 }
38
39
40 AbstractSqlStorage::~AbstractSqlStorage()
41 {
42     // disconnect the connections, so their deletion is no longer interessting for us
43     QHash<QThread *, Connection *>::iterator conIter;
44     for (conIter = _connectionPool.begin(); conIter != _connectionPool.end(); ++conIter) {
45         QSqlDatabase::removeDatabase(conIter.value()->name());
46         disconnect(conIter.value(), 0, this, 0);
47     }
48 }
49
50
51 QSqlDatabase AbstractSqlStorage::logDb()
52 {
53     if (!_connectionPool.contains(QThread::currentThread()))
54         addConnectionToPool();
55
56     QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(),false);
57
58     if (!db.isOpen()) {
59         qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread() << "was lost, attempting to reconnect...";
60         dbConnect(db);
61     }
62
63     return db;
64 }
65
66
67 void AbstractSqlStorage::addConnectionToPool()
68 {
69     QMutexLocker locker(&_connectionPoolMutex);
70     // we have to recheck if the connection pool already contains a connection for
71     // this thread. Since now (after the lock) we can only tell for sure
72     if (_connectionPool.contains(QThread::currentThread()))
73         return;
74
75     QThread *currentThread = QThread::currentThread();
76
77     int connectionId = _nextConnectionId++;
78
79     Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
80     connection->moveToThread(currentThread);
81     connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
82     connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
83     connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
84     _connectionPool[currentThread] = connection;
85
86     QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
87     db.setDatabaseName(databaseName());
88
89     if (!hostName().isEmpty())
90         db.setHostName(hostName());
91
92     if (port() != -1)
93         db.setPort(port());
94
95     if (!userName().isEmpty()) {
96         db.setUserName(userName());
97         db.setPassword(password());
98     }
99
100     dbConnect(db);
101 }
102
103
104 void AbstractSqlStorage::dbConnect(QSqlDatabase &db)
105 {
106     if (!db.open()) {
107         quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
108         quWarning() << "-" << db.lastError().text();
109     }
110     else {
111         if (!initDbSession(db)) {
112             quWarning() << "Unable to initialize database" << displayName() << "for thread" << QThread::currentThread();
113             db.close();
114         }
115     }
116 }
117
118
119 Storage::State AbstractSqlStorage::init(const QVariantMap &settings,
120                                         const QProcessEnvironment &environment,
121                                         bool loadFromEnvironment)
122 {
123     setConnectionProperties(settings, environment, loadFromEnvironment);
124
125     _debug = Quassel::isOptionSet("debug");
126
127     QSqlDatabase db = logDb();
128     if (!db.isValid() || !db.isOpen())
129         return NotAvailable;
130
131     if (installedSchemaVersion() == -1) {
132         qCritical() << "Storage Schema is missing!";
133         return NeedsSetup;
134     }
135
136     if (installedSchemaVersion() > schemaVersion()) {
137         qCritical() << "Installed Schema is newer then any known Version.";
138         return NotAvailable;
139     }
140
141     if (installedSchemaVersion() < schemaVersion()) {
142         qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to "
143                                     "version %2...  This may take a while for major upgrades."
144                                     ).arg(installedSchemaVersion()).arg(schemaVersion()));
145         // TODO: The monolithic client won't show this message unless one looks into the debug log.
146         // This should be made more friendly, e.g. a popup message in the GUI.
147         if (!upgradeDb()) {
148             qWarning() << qPrintable(tr("Upgrade failed..."));
149             return NotAvailable;
150         }
151         // Warning messages are also sent to the console, while Info messages aren't.  Add a message
152         // when migration succeeds to avoid confusing folks by implying the schema upgrade failed if
153         // later functionality does not work.
154         qWarning() << qPrintable(tr("Installed Schema successfully upgraded to version %1."
155                                     ).arg(schemaVersion()));
156     }
157
158     quInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
159     return IsReady;
160 }
161
162
163 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
164 {
165     QFileInfo queryInfo;
166
167     // The current schema is stored in the root folder, while upgrade queries are stored in the
168     // 'versions/##' subfolders.
169     if (version == 0) {
170         // Use the current SQL schema, not a versioned request
171         queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName));
172         // If version is needed later, get it via version = schemaVersion();
173     } else {
174         // Use the specified schema version, not the general folder
175         queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql")
176                               .arg(displayName()).arg(version).arg(queryName));
177     }
178
179     if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
180         qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
181         return QString();
182     }
183
184     QFile queryFile(queryInfo.filePath());
185     if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
186         return QString();
187     QString query = QTextStream(&queryFile).readAll();
188     queryFile.close();
189
190     return query.trimmed();
191 }
192
193
194 QStringList AbstractSqlStorage::setupQueries()
195 {
196     QStringList queries;
197     // The current schema is stored in the root folder, including setup scripts.
198     QDir dir = QDir(QString(":/SQL/%1/").arg(displayName()));
199     foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
200         queries << queryString(fileInfo.baseName());
201     }
202     return queries;
203 }
204
205
206 bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
207                                bool loadFromEnvironment)
208 {
209     setConnectionProperties(settings, environment, loadFromEnvironment);
210     QSqlDatabase db = logDb();
211     if (!db.isOpen()) {
212         qCritical() << "Unable to setup Logging Backend!";
213         return false;
214     }
215
216     db.transaction();
217     foreach(QString queryString, setupQueries()) {
218         QSqlQuery query = db.exec(queryString);
219         if (!watchQuery(query)) {
220             qCritical() << "Unable to setup Logging Backend!";
221             db.rollback();
222             return false;
223         }
224     }
225     bool success = setupSchemaVersion(schemaVersion());
226     if (success)
227         db.commit();
228     else
229         db.rollback();
230     return success;
231 }
232
233
234 QStringList AbstractSqlStorage::upgradeQueries(int version)
235 {
236     QStringList queries;
237     // Upgrade queries are stored in the 'version/##' subfolders.
238     QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version));
239     foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
240         queries << queryString(fileInfo.baseName(), version);
241     }
242     return queries;
243 }
244
245
246 bool AbstractSqlStorage::upgradeDb()
247 {
248     if (schemaVersion() <= installedSchemaVersion())
249         return true;
250
251     QSqlDatabase db = logDb();
252
253     for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
254         foreach(QString queryString, upgradeQueries(ver)) {
255             QSqlQuery query = db.exec(queryString);
256             if (!watchQuery(query)) {
257                 qCritical() << "Unable to upgrade Logging Backend!";
258                 return false;
259             }
260         }
261     }
262     return updateSchemaVersion(schemaVersion());
263 }
264
265
266 int AbstractSqlStorage::schemaVersion()
267 {
268     // returns the newest Schema Version!
269     // not the currently used one! (though it can be the same)
270     if (_schemaVersion > 0)
271         return _schemaVersion;
272
273     int version;
274     bool ok;
275     // Schema versions are stored in the 'version/##' subfolders.
276     QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
277     foreach(QFileInfo fileInfo, dir.entryInfoList()) {
278         if (!fileInfo.isDir())
279             continue;
280
281         version = fileInfo.fileName().toInt(&ok);
282         if (!ok)
283             continue;
284
285         if (version > _schemaVersion)
286             _schemaVersion = version;
287     }
288     return _schemaVersion;
289 }
290
291
292 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
293 {
294     bool queryError = query.lastError().isValid();
295     if (queryError || _debug) {
296         if (queryError)
297             qCritical() << "unhandled Error in QSqlQuery!";
298         qCritical() << "                  last Query:\n" << qPrintable(query.lastQuery());
299         qCritical() << "              executed Query:\n" << qPrintable(query.executedQuery());
300         QVariantMap boundValues = query.boundValues();
301         QStringList valueStrings;
302         QVariantMap::const_iterator iter;
303         for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
304             QString value;
305             QSqlField field;
306             if (query.driver()) {
307                 // let the driver do the formatting
308                 field.setType(iter.value().type());
309                 if (iter.value().isNull())
310                     field.clear();
311                 else
312                     field.setValue(iter.value());
313                 value =  query.driver()->formatValue(field);
314             }
315             else {
316                 switch (iter.value().type()) {
317                 case QVariant::Invalid:
318                     value = "NULL";
319                     break;
320                 case QVariant::Int:
321                     value = iter.value().toString();
322                     break;
323                 default:
324                     value = QString("'%1'").arg(iter.value().toString());
325                 }
326             }
327             valueStrings << QString("%1=%2").arg(iter.key(), value);
328         }
329         qCritical() << "                bound Values:" << qPrintable(valueStrings.join(", "));
330         qCritical() << "                Error Number:" << query.lastError().number();
331         qCritical() << "               Error Message:" << qPrintable(query.lastError().text());
332         qCritical() << "              Driver Message:" << qPrintable(query.lastError().driverText());
333         qCritical() << "                  DB Message:" << qPrintable(query.lastError().databaseText());
334
335         return !queryError;
336     }
337     return true;
338 }
339
340
341 void AbstractSqlStorage::connectionDestroyed()
342 {
343     QMutexLocker locker(&_connectionPoolMutex);
344     _connectionPool.remove(sender()->thread());
345 }
346
347
348 // ========================================
349 //  AbstractSqlStorage::Connection
350 // ========================================
351 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
352     : QObject(parent),
353     _name(name.toLatin1())
354 {
355 }
356
357
358 AbstractSqlStorage::Connection::~Connection()
359 {
360     {
361         QSqlDatabase db = QSqlDatabase::database(name(), false);
362         if (db.isOpen()) {
363             db.commit();
364             db.close();
365         }
366     }
367     QSqlDatabase::removeDatabase(name());
368 }
369
370
371 // ========================================
372 //  AbstractSqlMigrator
373 // ========================================
374 AbstractSqlMigrator::AbstractSqlMigrator()
375     : _query(0)
376 {
377 }
378
379
380 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
381 {
382     Q_ASSERT(!_query);
383     _query = new QSqlQuery(db);
384     _query->prepare(query);
385 }
386
387
388 void AbstractSqlMigrator::resetQuery()
389 {
390     delete _query;
391     _query = 0;
392 }
393
394
395 bool AbstractSqlMigrator::exec()
396 {
397     Q_ASSERT(_query);
398     _query->exec();
399     return !_query->lastError().isValid();
400 }
401
402
403 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
404 {
405     switch (moType) {
406     case QuasselUser:
407         return "QuasselUser";
408     case Sender:
409         return "Sender";
410     case Identity:
411         return "Identity";
412     case IdentityNick:
413         return "IdentityNick";
414     case Network:
415         return "Network";
416     case Buffer:
417         return "Buffer";
418     case Backlog:
419         return "Backlog";
420     case IrcServer:
421         return "IrcServer";
422     case UserSetting:
423         return "UserSetting";
424     case CoreState:
425         return "CoreState";
426     };
427     return QString();
428 }
429
430
431 QVariantList AbstractSqlMigrator::boundValues()
432 {
433     QVariantList values;
434     if (!_query)
435         return values;
436
437     int numValues = _query->boundValues().count();
438     for (int i = 0; i < numValues; i++) {
439         values << _query->boundValue(i);
440     }
441     return values;
442 }
443
444
445 void AbstractSqlMigrator::dumpStatus()
446 {
447     qWarning() << "  executed Query:";
448     qWarning() << qPrintable(executedQuery());
449     qWarning() << "  bound Values:";
450     QList<QVariant> list = boundValues();
451     for (int i = 0; i < list.size(); ++i)
452         qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
453     qWarning() << "  Error Number:"   << lastError().number();
454     qWarning() << "  Error Message:"   << lastError().text();
455 }
456
457
458 // ========================================
459 //  AbstractSqlMigrationReader
460 // ========================================
461 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
462     : AbstractSqlMigrator(),
463     _writer(0)
464 {
465 }
466
467
468 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
469 {
470     if (!transaction()) {
471         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
472         return false;
473     }
474     if (!writer->transaction()) {
475         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
476         rollback(); // close the reader transaction;
477         return false;
478     }
479
480     _writer = writer;
481
482     // due to the incompatibility across Migration objects we can't run this in a loop... :/
483     QuasselUserMO quasselUserMo;
484     if (!transferMo(QuasselUser, quasselUserMo))
485         return false;
486
487     IdentityMO identityMo;
488     if (!transferMo(Identity, identityMo))
489         return false;
490
491     IdentityNickMO identityNickMo;
492     if (!transferMo(IdentityNick, identityNickMo))
493         return false;
494
495     NetworkMO networkMo;
496     if (!transferMo(Network, networkMo))
497         return false;
498
499     BufferMO bufferMo;
500     if (!transferMo(Buffer, bufferMo))
501         return false;
502
503     SenderMO senderMo;
504     if (!transferMo(Sender, senderMo))
505         return false;
506
507     BacklogMO backlogMo;
508     if (!transferMo(Backlog, backlogMo))
509         return false;
510
511     IrcServerMO ircServerMo;
512     if (!transferMo(IrcServer, ircServerMo))
513         return false;
514
515     UserSettingMO userSettingMo;
516     if (!transferMo(UserSetting, userSettingMo))
517         return false;
518
519     CoreStateMO coreStateMO;
520     if (!transferMo(CoreState, coreStateMO))
521         return false;
522
523     if (!_writer->postProcess())
524         abortMigration();
525     return finalizeMigration();
526 }
527
528
529 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
530 {
531     qWarning() << "Migration Failed!";
532     if (!errorMsg.isNull()) {
533         qWarning() << qPrintable(errorMsg);
534     }
535     if (lastError().isValid()) {
536         qWarning() << "ReaderError:";
537         dumpStatus();
538     }
539
540     if (_writer->lastError().isValid()) {
541         qWarning() << "WriterError:";
542         _writer->dumpStatus();
543     }
544
545     rollback();
546     _writer->rollback();
547     _writer = 0;
548 }
549
550
551 bool AbstractSqlMigrationReader::finalizeMigration()
552 {
553     resetQuery();
554     _writer->resetQuery();
555
556     commit();
557     if (!_writer->commit()) {
558         _writer = 0;
559         return false;
560     }
561     _writer = 0;
562     return true;
563 }
564
565
566 template<typename T>
567 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
568 {
569     resetQuery();
570     _writer->resetQuery();
571
572     if (!prepareQuery(moType)) {
573         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
574         return false;
575     }
576     if (!_writer->prepareQuery(moType)) {
577         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
578         return false;
579     }
580
581     qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
582     int i = 0;
583     QFile file;
584     file.open(stdout, QIODevice::WriteOnly);
585
586     while (readMo(mo)) {
587         if (!_writer->writeMo(mo)) {
588             abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
589             return false;
590         }
591         i++;
592         if (i % 1000 == 0) {
593             file.write("*");
594             file.flush();
595         }
596     }
597     if (i > 1000) {
598         file.write("\n");
599         file.flush();
600     }
601
602     qDebug() << "Done.";
603     return true;
604 }
605
606 uint qHash(const SenderData &key) {
607     return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
608 }
609
610 bool operator==(const SenderData &a, const SenderData &b) {
611     return a.sender == b.sender &&
612         a.realname == b.realname &&
613         a.avatarurl == b.avatarurl;
614 }