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