mono: Show a popup during database migration
[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         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 QStringList AbstractSqlStorage::setupQueries()
194 {
195     QStringList 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 << queryString(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(QString queryString, setupQueries()) {
217         QSqlQuery query = db.exec(queryString);
218         if (!watchQuery(query)) {
219             qCritical() << "Unable to setup Logging Backend!";
220             db.rollback();
221             return false;
222         }
223     }
224     bool success = setupSchemaVersion(schemaVersion());
225     if (success)
226         db.commit();
227     else
228         db.rollback();
229     return success;
230 }
231
232
233 QStringList AbstractSqlStorage::upgradeQueries(int version)
234 {
235     QStringList queries;
236     // Upgrade queries are stored in the 'version/##' subfolders.
237     QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version));
238     foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
239         queries << queryString(fileInfo.baseName(), version);
240     }
241     return queries;
242 }
243
244
245 bool AbstractSqlStorage::upgradeDb()
246 {
247     if (schemaVersion() <= installedSchemaVersion())
248         return true;
249
250     QSqlDatabase db = logDb();
251
252     // TODO: For databases that support it (e.g. almost only PostgreSQL), wrap upgrades in a
253     // transaction.  This will need careful testing of potential additional space requirements and
254     // any database modifications that might not be allowed in a transaction.
255
256     for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
257         foreach(QString queryString, upgradeQueries(ver)) {
258             QSqlQuery query = db.exec(queryString);
259             if (!watchQuery(query)) {
260                 // Individual upgrade query failed, bail out
261                 qCritical() << "Unable to upgrade Logging Backend!  Upgrade query in schema version"
262                             << ver << "failed.";
263                 return false;
264             }
265         }
266
267         // Update the schema version for each intermediate step.  This ensures that any interrupted
268         // upgrades have a greater chance of resuming correctly after core restart.
269         //
270         // Almost all databases make single queries atomic (fully works or fully fails, no partial),
271         // and with many of the longest migrations being a single query, this makes upgrade
272         // interruptions much more likely to leave the database in a valid intermediate schema
273         // version.
274         if (!updateSchemaVersion(ver)) {
275             // Updating the schema version failed, bail out
276             qCritical() << "Unable to upgrade Logging Backend!  Setting schema version"
277                         << ver << "failed.";
278             return false;
279         }
280     }
281
282     // Update the schema version for the final step.  Split this out to offer more informative
283     // logging (though setting schema version really should not fail).
284     if (!updateSchemaVersion(schemaVersion())) {
285         // Updating the final schema version failed, bail out
286         qCritical() << "Unable to upgrade Logging Backend!  Setting final schema version"
287                     << schemaVersion() << "failed.";
288         return false;
289     }
290
291     // If we made it here, everything seems to have worked!
292     return true;
293 }
294
295
296 int AbstractSqlStorage::schemaVersion()
297 {
298     // returns the newest Schema Version!
299     // not the currently used one! (though it can be the same)
300     if (_schemaVersion > 0)
301         return _schemaVersion;
302
303     int version;
304     bool ok;
305     // Schema versions are stored in the 'version/##' subfolders.
306     QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
307     foreach(QFileInfo fileInfo, dir.entryInfoList()) {
308         if (!fileInfo.isDir())
309             continue;
310
311         version = fileInfo.fileName().toInt(&ok);
312         if (!ok)
313             continue;
314
315         if (version > _schemaVersion)
316             _schemaVersion = version;
317     }
318     return _schemaVersion;
319 }
320
321
322 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
323 {
324     bool queryError = query.lastError().isValid();
325     if (queryError || _debug) {
326         if (queryError)
327             qCritical() << "unhandled Error in QSqlQuery!";
328         qCritical() << "                  last Query:\n" << qPrintable(query.lastQuery());
329         qCritical() << "              executed Query:\n" << qPrintable(query.executedQuery());
330         QVariantMap boundValues = query.boundValues();
331         QStringList valueStrings;
332         QVariantMap::const_iterator iter;
333         for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
334             QString value;
335             QSqlField field;
336             if (query.driver()) {
337                 // let the driver do the formatting
338                 field.setType(iter.value().type());
339                 if (iter.value().isNull())
340                     field.clear();
341                 else
342                     field.setValue(iter.value());
343                 value =  query.driver()->formatValue(field);
344             }
345             else {
346                 switch (iter.value().type()) {
347                 case QVariant::Invalid:
348                     value = "NULL";
349                     break;
350                 case QVariant::Int:
351                     value = iter.value().toString();
352                     break;
353                 default:
354                     value = QString("'%1'").arg(iter.value().toString());
355                 }
356             }
357             valueStrings << QString("%1=%2").arg(iter.key(), value);
358         }
359         qCritical() << "                bound Values:" << qPrintable(valueStrings.join(", "));
360         qCritical() << "                Error Number:" << query.lastError().number();
361         qCritical() << "               Error Message:" << qPrintable(query.lastError().text());
362         qCritical() << "              Driver Message:" << qPrintable(query.lastError().driverText());
363         qCritical() << "                  DB Message:" << qPrintable(query.lastError().databaseText());
364
365         return !queryError;
366     }
367     return true;
368 }
369
370
371 void AbstractSqlStorage::connectionDestroyed()
372 {
373     QMutexLocker locker(&_connectionPoolMutex);
374     _connectionPool.remove(sender()->thread());
375 }
376
377
378 // ========================================
379 //  AbstractSqlStorage::Connection
380 // ========================================
381 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
382     : QObject(parent),
383     _name(name.toLatin1())
384 {
385 }
386
387
388 AbstractSqlStorage::Connection::~Connection()
389 {
390     {
391         QSqlDatabase db = QSqlDatabase::database(name(), false);
392         if (db.isOpen()) {
393             db.commit();
394             db.close();
395         }
396     }
397     QSqlDatabase::removeDatabase(name());
398 }
399
400
401 // ========================================
402 //  AbstractSqlMigrator
403 // ========================================
404 AbstractSqlMigrator::AbstractSqlMigrator()
405     : _query(0)
406 {
407 }
408
409
410 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
411 {
412     Q_ASSERT(!_query);
413     _query = new QSqlQuery(db);
414     _query->prepare(query);
415 }
416
417
418 void AbstractSqlMigrator::resetQuery()
419 {
420     delete _query;
421     _query = 0;
422 }
423
424
425 bool AbstractSqlMigrator::exec()
426 {
427     Q_ASSERT(_query);
428     _query->exec();
429     return !_query->lastError().isValid();
430 }
431
432
433 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
434 {
435     switch (moType) {
436     case QuasselUser:
437         return "QuasselUser";
438     case Sender:
439         return "Sender";
440     case Identity:
441         return "Identity";
442     case IdentityNick:
443         return "IdentityNick";
444     case Network:
445         return "Network";
446     case Buffer:
447         return "Buffer";
448     case Backlog:
449         return "Backlog";
450     case IrcServer:
451         return "IrcServer";
452     case UserSetting:
453         return "UserSetting";
454     case CoreState:
455         return "CoreState";
456     };
457     return QString();
458 }
459
460
461 QVariantList AbstractSqlMigrator::boundValues()
462 {
463     QVariantList values;
464     if (!_query)
465         return values;
466
467     int numValues = _query->boundValues().count();
468     for (int i = 0; i < numValues; i++) {
469         values << _query->boundValue(i);
470     }
471     return values;
472 }
473
474
475 void AbstractSqlMigrator::dumpStatus()
476 {
477     qWarning() << "  executed Query:";
478     qWarning() << qPrintable(executedQuery());
479     qWarning() << "  bound Values:";
480     QList<QVariant> list = boundValues();
481     for (int i = 0; i < list.size(); ++i)
482         qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
483     qWarning() << "  Error Number:"   << lastError().number();
484     qWarning() << "  Error Message:"   << lastError().text();
485 }
486
487
488 // ========================================
489 //  AbstractSqlMigrationReader
490 // ========================================
491 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
492     : AbstractSqlMigrator(),
493     _writer(0)
494 {
495 }
496
497
498 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
499 {
500     if (!transaction()) {
501         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
502         return false;
503     }
504     if (!writer->transaction()) {
505         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
506         rollback(); // close the reader transaction;
507         return false;
508     }
509
510     _writer = writer;
511
512     // due to the incompatibility across Migration objects we can't run this in a loop... :/
513     QuasselUserMO quasselUserMo;
514     if (!transferMo(QuasselUser, quasselUserMo))
515         return false;
516
517     IdentityMO identityMo;
518     if (!transferMo(Identity, identityMo))
519         return false;
520
521     IdentityNickMO identityNickMo;
522     if (!transferMo(IdentityNick, identityNickMo))
523         return false;
524
525     NetworkMO networkMo;
526     if (!transferMo(Network, networkMo))
527         return false;
528
529     BufferMO bufferMo;
530     if (!transferMo(Buffer, bufferMo))
531         return false;
532
533     SenderMO senderMo;
534     if (!transferMo(Sender, senderMo))
535         return false;
536
537     BacklogMO backlogMo;
538     if (!transferMo(Backlog, backlogMo))
539         return false;
540
541     IrcServerMO ircServerMo;
542     if (!transferMo(IrcServer, ircServerMo))
543         return false;
544
545     UserSettingMO userSettingMo;
546     if (!transferMo(UserSetting, userSettingMo))
547         return false;
548
549     CoreStateMO coreStateMO;
550     if (!transferMo(CoreState, coreStateMO))
551         return false;
552
553     if (!_writer->postProcess())
554         abortMigration();
555     return finalizeMigration();
556 }
557
558
559 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
560 {
561     qWarning() << "Migration Failed!";
562     if (!errorMsg.isNull()) {
563         qWarning() << qPrintable(errorMsg);
564     }
565     if (lastError().isValid()) {
566         qWarning() << "ReaderError:";
567         dumpStatus();
568     }
569
570     if (_writer->lastError().isValid()) {
571         qWarning() << "WriterError:";
572         _writer->dumpStatus();
573     }
574
575     rollback();
576     _writer->rollback();
577     _writer = 0;
578 }
579
580
581 bool AbstractSqlMigrationReader::finalizeMigration()
582 {
583     resetQuery();
584     _writer->resetQuery();
585
586     commit();
587     if (!_writer->commit()) {
588         _writer = 0;
589         return false;
590     }
591     _writer = 0;
592     return true;
593 }
594
595
596 template<typename T>
597 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
598 {
599     resetQuery();
600     _writer->resetQuery();
601
602     if (!prepareQuery(moType)) {
603         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
604         return false;
605     }
606     if (!_writer->prepareQuery(moType)) {
607         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
608         return false;
609     }
610
611     qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
612     int i = 0;
613     QFile file;
614     file.open(stdout, QIODevice::WriteOnly);
615
616     while (readMo(mo)) {
617         if (!_writer->writeMo(mo)) {
618             abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
619             return false;
620         }
621         i++;
622         if (i % 1000 == 0) {
623             file.write("*");
624             file.flush();
625         }
626     }
627     if (i > 1000) {
628         file.write("\n");
629         file.flush();
630     }
631
632     qDebug() << "Done.";
633     return true;
634 }
635
636 uint qHash(const SenderData &key) {
637     return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
638 }
639
640 bool operator==(const SenderData &a, const SenderData &b) {
641     return a.sender == b.sender &&
642         a.realname == b.realname &&
643         a.avatarurl == b.avatarurl;
644 }