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