core: Remove redundant updateSchemaVersion() call
[quassel.git] / src / core / abstractsqlstorage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 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 "logmessage.h"
30 #include "quassel.h"
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         quInfo() << qPrintable(tr("Installed database 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         emit dbUpgradeInProgress(true);
146         auto upgradeResult = upgradeDb();
147         emit dbUpgradeInProgress(false);
148         if (!upgradeResult) {
149             qWarning() << qPrintable(tr("Upgrade failed..."));
150             return NotAvailable;
151         }
152         // Add a message when migration succeeds to avoid confusing folks by implying the schema upgrade failed if
153         // later functionality does not work.
154         quInfo() << qPrintable(tr("Installed database schema successfully upgraded to version %1.").arg(schemaVersion()));
155     }
156
157     quInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
158     return IsReady;
159 }
160
161
162 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
163 {
164     QFileInfo queryInfo;
165
166     // The current schema is stored in the root folder, while upgrade queries are stored in the
167     // 'versions/##' subfolders.
168     if (version == 0) {
169         // Use the current SQL schema, not a versioned request
170         queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName));
171         // If version is needed later, get it via version = schemaVersion();
172     } else {
173         // Use the specified schema version, not the general folder
174         queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql")
175                               .arg(displayName()).arg(version).arg(queryName));
176     }
177
178     if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
179         qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
180         return QString();
181     }
182
183     QFile queryFile(queryInfo.filePath());
184     if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
185         return QString();
186     QString query = QTextStream(&queryFile).readAll();
187     queryFile.close();
188
189     return query.trimmed();
190 }
191
192
193 QList<AbstractSqlStorage::SqlQueryResource> AbstractSqlStorage::setupQueries()
194 {
195     QList<SqlQueryResource> queries;
196     // The current schema is stored in the root folder, including setup scripts.
197     QDir dir = QDir(QString(":/SQL/%1/").arg(displayName()));
198     foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
199         queries << SqlQueryResource(queryString(fileInfo.baseName()), fileInfo.baseName());
200     }
201     return queries;
202 }
203
204
205 bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
206                                bool loadFromEnvironment)
207 {
208     setConnectionProperties(settings, environment, loadFromEnvironment);
209     QSqlDatabase db = logDb();
210     if (!db.isOpen()) {
211         qCritical() << "Unable to setup Logging Backend!";
212         return false;
213     }
214
215     db.transaction();
216     foreach (auto queryResource, setupQueries()) {
217         QSqlQuery query = db.exec(queryResource.queryString);
218         if (!watchQuery(query)) {
219             qCritical() << qPrintable(QString("Unable to setup Logging Backend!  Setup query failed (step: %1).")
220                                       .arg(queryResource.queryFilename));
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 QList<AbstractSqlStorage::SqlQueryResource> AbstractSqlStorage::upgradeQueries(int version)
235 {
236     QList<SqlQueryResource> 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 << SqlQueryResource(queryString(fileInfo.baseName(), version), fileInfo.baseName());
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     // TODO: For databases that support it (e.g. almost only PostgreSQL), wrap upgrades in a
254     // transaction.  This will need careful testing of potential additional space requirements and
255     // any database modifications that might not be allowed in a transaction.
256
257     // Check if we're resuming an interrupted multi-step upgrade: is an upgrade step stored?
258     const QString previousLaunchUpgradeStep = schemaVersionUpgradeStep();
259     bool resumingUpgrade = !previousLaunchUpgradeStep.isEmpty();
260
261     for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
262         foreach (auto queryResource, upgradeQueries(ver)) {
263             if (resumingUpgrade) {
264                 // An upgrade was interrupted.  Check if this matches the the last successful query.
265                 if (previousLaunchUpgradeStep == queryResource.queryFilename) {
266                     // Found the matching query!
267                     quInfo() << qPrintable(QString("Resuming interrupted upgrade for schema version %1 (last step: %2)")
268                                            .arg(QString::number(ver), previousLaunchUpgradeStep));
269
270                     // Stop searching for queries
271                     resumingUpgrade = false;
272                     // Continue past the previous query with the next not-yet-tried query
273                     continue;
274                 }
275                 else {
276                     // Not yet matched, keep looking
277                     continue;
278                 }
279             }
280
281             // Run the upgrade query
282             QSqlQuery query = db.exec(queryResource.queryString);
283             if (!watchQuery(query)) {
284                 // Individual upgrade query failed, bail out
285                 qCritical() << qPrintable(QString("Unable to upgrade Logging Backend!  Upgrade query in schema version %1 failed (step: %2).")
286                                           .arg(QString::number(ver), queryResource.queryFilename));
287                 return false;
288             }
289             else {
290                 // Mark as successful
291                 setSchemaVersionUpgradeStep(queryResource.queryFilename);
292             }
293         }
294
295         if (resumingUpgrade) {
296             // Something went wrong and the last successful SQL query to resume from couldn't be
297             // found.
298             // 1.  The storage of successful query glitched, or the database was manually changed
299             // 2.  Quassel changed the filenames of upgrade queries, and the local Quassel core
300             //     version was replaced during an interrupted schema upgrade
301             //
302             // Both are unlikely, but it's a good idea to handle it anyways.
303
304             qCritical() << qPrintable(QString("Unable to resume interrupted upgrade in Logging "
305                                               "Backend!  Missing upgrade step in schema version %1 "
306                                               "(expected step: %2)")
307                                       .arg(QString::number(ver), previousLaunchUpgradeStep));
308             return false;
309         }
310
311         // Update the schema version for each intermediate step and mark the step as done.  This
312         // ensures that any interrupted upgrades have a greater chance of resuming correctly after
313         // core restart.
314         //
315         // Almost all databases make single queries atomic (fully works or fully fails, no partial),
316         // and with many of the longest migrations being a single query, this makes upgrade
317         // interruptions much more likely to leave the database in a valid intermediate schema
318         // version.
319         if (!updateSchemaVersion(ver, true)) {
320             // Updating the schema version failed, bail out
321             qCritical() << "Unable to upgrade Logging Backend!  Setting schema version"
322                         << ver << "failed.";
323             return false;
324         }
325     }
326
327     // If we made it here, everything seems to have worked!
328     return true;
329 }
330
331
332 int AbstractSqlStorage::schemaVersion()
333 {
334     // returns the newest Schema Version!
335     // not the currently used one! (though it can be the same)
336     if (_schemaVersion > 0)
337         return _schemaVersion;
338
339     int version;
340     bool ok;
341     // Schema versions are stored in the 'version/##' subfolders.
342     QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
343     foreach(QFileInfo fileInfo, dir.entryInfoList()) {
344         if (!fileInfo.isDir())
345             continue;
346
347         version = fileInfo.fileName().toInt(&ok);
348         if (!ok)
349             continue;
350
351         if (version > _schemaVersion)
352             _schemaVersion = version;
353     }
354     return _schemaVersion;
355 }
356
357
358 QString AbstractSqlStorage::schemaVersionUpgradeStep()
359 {
360     // By default, assume there's no pending upgrade
361     return {};
362 }
363
364
365 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
366 {
367     bool queryError = query.lastError().isValid();
368     if (queryError || _debug) {
369         if (queryError)
370             qCritical() << "unhandled Error in QSqlQuery!";
371         qCritical() << "                  last Query:\n" << qPrintable(query.lastQuery());
372         qCritical() << "              executed Query:\n" << qPrintable(query.executedQuery());
373         QVariantMap boundValues = query.boundValues();
374         QStringList valueStrings;
375         QVariantMap::const_iterator iter;
376         for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
377             QString value;
378             QSqlField field;
379             if (query.driver()) {
380                 // let the driver do the formatting
381                 field.setType(iter.value().type());
382                 if (iter.value().isNull())
383                     field.clear();
384                 else
385                     field.setValue(iter.value());
386                 value =  query.driver()->formatValue(field);
387             }
388             else {
389                 switch (iter.value().type()) {
390                 case QVariant::Invalid:
391                     value = "NULL";
392                     break;
393                 case QVariant::Int:
394                     value = iter.value().toString();
395                     break;
396                 default:
397                     value = QString("'%1'").arg(iter.value().toString());
398                 }
399             }
400             valueStrings << QString("%1=%2").arg(iter.key(), value);
401         }
402         qCritical() << "                bound Values:" << qPrintable(valueStrings.join(", "));
403         qCritical() << "                Error Number:" << query.lastError().number();
404         qCritical() << "               Error Message:" << qPrintable(query.lastError().text());
405         qCritical() << "              Driver Message:" << qPrintable(query.lastError().driverText());
406         qCritical() << "                  DB Message:" << qPrintable(query.lastError().databaseText());
407
408         return !queryError;
409     }
410     return true;
411 }
412
413
414 void AbstractSqlStorage::connectionDestroyed()
415 {
416     QMutexLocker locker(&_connectionPoolMutex);
417     _connectionPool.remove(sender()->thread());
418 }
419
420
421 // ========================================
422 //  AbstractSqlStorage::Connection
423 // ========================================
424 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
425     : QObject(parent),
426     _name(name.toLatin1())
427 {
428 }
429
430
431 AbstractSqlStorage::Connection::~Connection()
432 {
433     {
434         QSqlDatabase db = QSqlDatabase::database(name(), false);
435         if (db.isOpen()) {
436             db.commit();
437             db.close();
438         }
439     }
440     QSqlDatabase::removeDatabase(name());
441 }
442
443
444 // ========================================
445 //  AbstractSqlMigrator
446 // ========================================
447 AbstractSqlMigrator::AbstractSqlMigrator()
448     : _query(0)
449 {
450 }
451
452
453 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
454 {
455     Q_ASSERT(!_query);
456     _query = new QSqlQuery(db);
457     _query->prepare(query);
458 }
459
460
461 void AbstractSqlMigrator::resetQuery()
462 {
463     delete _query;
464     _query = 0;
465 }
466
467
468 bool AbstractSqlMigrator::exec()
469 {
470     Q_ASSERT(_query);
471     _query->exec();
472     return !_query->lastError().isValid();
473 }
474
475
476 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
477 {
478     switch (moType) {
479     case QuasselUser:
480         return "QuasselUser";
481     case Sender:
482         return "Sender";
483     case Identity:
484         return "Identity";
485     case IdentityNick:
486         return "IdentityNick";
487     case Network:
488         return "Network";
489     case Buffer:
490         return "Buffer";
491     case Backlog:
492         return "Backlog";
493     case IrcServer:
494         return "IrcServer";
495     case UserSetting:
496         return "UserSetting";
497     case CoreState:
498         return "CoreState";
499     };
500     return QString();
501 }
502
503
504 QVariantList AbstractSqlMigrator::boundValues()
505 {
506     QVariantList values;
507     if (!_query)
508         return values;
509
510     int numValues = _query->boundValues().count();
511     for (int i = 0; i < numValues; i++) {
512         values << _query->boundValue(i);
513     }
514     return values;
515 }
516
517
518 void AbstractSqlMigrator::dumpStatus()
519 {
520     qWarning() << "  executed Query:";
521     qWarning() << qPrintable(executedQuery());
522     qWarning() << "  bound Values:";
523     QList<QVariant> list = boundValues();
524     for (int i = 0; i < list.size(); ++i)
525         qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
526     qWarning() << "  Error Number:"   << lastError().number();
527     qWarning() << "  Error Message:"   << lastError().text();
528 }
529
530
531 // ========================================
532 //  AbstractSqlMigrationReader
533 // ========================================
534 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
535     : AbstractSqlMigrator(),
536     _writer(0)
537 {
538 }
539
540
541 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
542 {
543     if (!transaction()) {
544         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
545         return false;
546     }
547     if (!writer->transaction()) {
548         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
549         rollback(); // close the reader transaction;
550         return false;
551     }
552
553     _writer = writer;
554
555     // due to the incompatibility across Migration objects we can't run this in a loop... :/
556     QuasselUserMO quasselUserMo;
557     if (!transferMo(QuasselUser, quasselUserMo))
558         return false;
559
560     IdentityMO identityMo;
561     if (!transferMo(Identity, identityMo))
562         return false;
563
564     IdentityNickMO identityNickMo;
565     if (!transferMo(IdentityNick, identityNickMo))
566         return false;
567
568     NetworkMO networkMo;
569     if (!transferMo(Network, networkMo))
570         return false;
571
572     BufferMO bufferMo;
573     if (!transferMo(Buffer, bufferMo))
574         return false;
575
576     SenderMO senderMo;
577     if (!transferMo(Sender, senderMo))
578         return false;
579
580     BacklogMO backlogMo;
581     if (!transferMo(Backlog, backlogMo))
582         return false;
583
584     IrcServerMO ircServerMo;
585     if (!transferMo(IrcServer, ircServerMo))
586         return false;
587
588     UserSettingMO userSettingMo;
589     if (!transferMo(UserSetting, userSettingMo))
590         return false;
591
592     CoreStateMO coreStateMO;
593     if (!transferMo(CoreState, coreStateMO))
594         return false;
595
596     if (!_writer->postProcess())
597         abortMigration();
598     return finalizeMigration();
599 }
600
601
602 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
603 {
604     qWarning() << "Migration Failed!";
605     if (!errorMsg.isNull()) {
606         qWarning() << qPrintable(errorMsg);
607     }
608     if (lastError().isValid()) {
609         qWarning() << "ReaderError:";
610         dumpStatus();
611     }
612
613     if (_writer->lastError().isValid()) {
614         qWarning() << "WriterError:";
615         _writer->dumpStatus();
616     }
617
618     rollback();
619     _writer->rollback();
620     _writer = 0;
621 }
622
623
624 bool AbstractSqlMigrationReader::finalizeMigration()
625 {
626     resetQuery();
627     _writer->resetQuery();
628
629     commit();
630     if (!_writer->commit()) {
631         _writer = 0;
632         return false;
633     }
634     _writer = 0;
635     return true;
636 }
637
638
639 template<typename T>
640 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
641 {
642     resetQuery();
643     _writer->resetQuery();
644
645     if (!prepareQuery(moType)) {
646         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
647         return false;
648     }
649     if (!_writer->prepareQuery(moType)) {
650         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
651         return false;
652     }
653
654     qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
655     int i = 0;
656     QFile file;
657     file.open(stdout, QIODevice::WriteOnly);
658
659     while (readMo(mo)) {
660         if (!_writer->writeMo(mo)) {
661             abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
662             return false;
663         }
664         i++;
665         if (i % 1000 == 0) {
666             file.write("*");
667             file.flush();
668         }
669     }
670     if (i > 1000) {
671         file.write("\n");
672         file.flush();
673     }
674
675     qDebug() << "Done.";
676     return true;
677 }
678
679 uint qHash(const SenderData &key) {
680     return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
681 }
682
683 bool operator==(const SenderData &a, const SenderData &b) {
684     return a.sender == b.sender &&
685         a.realname == b.realname &&
686         a.avatarurl == b.avatarurl;
687 }