cb8fbd117faa2e586ca476e58692efe3bff378fa
[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 {
121     setConnectionProperties(settings);
122
123     _debug = Quassel::isOptionSet("debug");
124
125     QSqlDatabase db = logDb();
126     if (!db.isValid() || !db.isOpen())
127         return NotAvailable;
128
129     if (installedSchemaVersion() == -1) {
130         qCritical() << "Storage Schema is missing!";
131         return NeedsSetup;
132     }
133
134     if (installedSchemaVersion() > schemaVersion()) {
135         qCritical() << "Installed Schema is newer then any known Version.";
136         return NotAvailable;
137     }
138
139     if (installedSchemaVersion() < schemaVersion()) {
140         qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
141         if (!upgradeDb()) {
142             qWarning() << qPrintable(tr("Upgrade failed..."));
143             return NotAvailable;
144         }
145     }
146
147     quInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
148     return IsReady;
149 }
150
151
152 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
153 {
154     QFileInfo queryInfo;
155
156     // The current schema is stored in the root folder, while upgrade queries are stored in the
157     // 'versions/##' subfolders.
158     if (version == 0) {
159         // Use the current SQL schema, not a versioned request
160         queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName));
161         // If version is needed later, get it via version = schemaVersion();
162     } else {
163         // Use the specified schema version, not the general folder
164         queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql")
165                               .arg(displayName()).arg(version).arg(queryName));
166     }
167
168     if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
169         qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
170         return QString();
171     }
172
173     QFile queryFile(queryInfo.filePath());
174     if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
175         return QString();
176     QString query = QTextStream(&queryFile).readAll();
177     queryFile.close();
178
179     return query.trimmed();
180 }
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
195 bool AbstractSqlStorage::setup(const QVariantMap &settings)
196 {
197     setConnectionProperties(settings);
198     QSqlDatabase db = logDb();
199     if (!db.isOpen()) {
200         qCritical() << "Unable to setup Logging Backend!";
201         return false;
202     }
203
204     db.transaction();
205     foreach(QString queryString, setupQueries()) {
206         QSqlQuery query = db.exec(queryString);
207         if (!watchQuery(query)) {
208             qCritical() << "Unable to setup Logging Backend!";
209             db.rollback();
210             return false;
211         }
212     }
213     bool success = setupSchemaVersion(schemaVersion());
214     if (success)
215         db.commit();
216     else
217         db.rollback();
218     return success;
219 }
220
221
222 QStringList AbstractSqlStorage::upgradeQueries(int version)
223 {
224     QStringList queries;
225     // Upgrade queries are stored in the 'version/##' subfolders.
226     QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version));
227     foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
228         queries << queryString(fileInfo.baseName(), version);
229     }
230     return queries;
231 }
232
233
234 bool AbstractSqlStorage::upgradeDb()
235 {
236     if (schemaVersion() <= installedSchemaVersion())
237         return true;
238
239     QSqlDatabase db = logDb();
240
241     for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
242         foreach(QString queryString, upgradeQueries(ver)) {
243             QSqlQuery query = db.exec(queryString);
244             if (!watchQuery(query)) {
245                 qCritical() << "Unable to upgrade Logging Backend!";
246                 return false;
247             }
248         }
249     }
250     return updateSchemaVersion(schemaVersion());
251 }
252
253
254 int AbstractSqlStorage::schemaVersion()
255 {
256     // returns the newest Schema Version!
257     // not the currently used one! (though it can be the same)
258     if (_schemaVersion > 0)
259         return _schemaVersion;
260
261     int version;
262     bool ok;
263     // Schema versions are stored in the 'version/##' subfolders.
264     QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
265     foreach(QFileInfo fileInfo, dir.entryInfoList()) {
266         if (!fileInfo.isDir())
267             continue;
268
269         version = fileInfo.fileName().toInt(&ok);
270         if (!ok)
271             continue;
272
273         if (version > _schemaVersion)
274             _schemaVersion = version;
275     }
276     return _schemaVersion;
277 }
278
279
280 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
281 {
282     bool queryError = query.lastError().isValid();
283     if (queryError || _debug) {
284         if (queryError)
285             qCritical() << "unhandled Error in QSqlQuery!";
286         qCritical() << "                  last Query:\n" << qPrintable(query.lastQuery());
287         qCritical() << "              executed Query:\n" << qPrintable(query.executedQuery());
288         QVariantMap boundValues = query.boundValues();
289         QStringList valueStrings;
290         QVariantMap::const_iterator iter;
291         for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
292             QString value;
293             QSqlField field;
294             if (query.driver()) {
295                 // let the driver do the formatting
296                 field.setType(iter.value().type());
297                 if (iter.value().isNull())
298                     field.clear();
299                 else
300                     field.setValue(iter.value());
301                 value =  query.driver()->formatValue(field);
302             }
303             else {
304                 switch (iter.value().type()) {
305                 case QVariant::Invalid:
306                     value = "NULL";
307                     break;
308                 case QVariant::Int:
309                     value = iter.value().toString();
310                     break;
311                 default:
312                     value = QString("'%1'").arg(iter.value().toString());
313                 }
314             }
315             valueStrings << QString("%1=%2").arg(iter.key(), value);
316         }
317         qCritical() << "                bound Values:" << qPrintable(valueStrings.join(", "));
318         qCritical() << "                Error Number:" << query.lastError().number();
319         qCritical() << "               Error Message:" << qPrintable(query.lastError().text());
320         qCritical() << "              Driver Message:" << qPrintable(query.lastError().driverText());
321         qCritical() << "                  DB Message:" << qPrintable(query.lastError().databaseText());
322
323         return !queryError;
324     }
325     return true;
326 }
327
328
329 void AbstractSqlStorage::connectionDestroyed()
330 {
331     QMutexLocker locker(&_connectionPoolMutex);
332     _connectionPool.remove(sender()->thread());
333 }
334
335
336 // ========================================
337 //  AbstractSqlStorage::Connection
338 // ========================================
339 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
340     : QObject(parent),
341     _name(name.toLatin1())
342 {
343 }
344
345
346 AbstractSqlStorage::Connection::~Connection()
347 {
348     {
349         QSqlDatabase db = QSqlDatabase::database(name(), false);
350         if (db.isOpen()) {
351             db.commit();
352             db.close();
353         }
354     }
355     QSqlDatabase::removeDatabase(name());
356 }
357
358
359 // ========================================
360 //  AbstractSqlMigrator
361 // ========================================
362 AbstractSqlMigrator::AbstractSqlMigrator()
363     : _query(0)
364 {
365 }
366
367
368 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
369 {
370     Q_ASSERT(!_query);
371     _query = new QSqlQuery(db);
372     _query->prepare(query);
373 }
374
375
376 void AbstractSqlMigrator::resetQuery()
377 {
378     delete _query;
379     _query = 0;
380 }
381
382
383 bool AbstractSqlMigrator::exec()
384 {
385     Q_ASSERT(_query);
386     _query->exec();
387     return !_query->lastError().isValid();
388 }
389
390
391 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
392 {
393     switch (moType) {
394     case QuasselUser:
395         return "QuasselUser";
396     case Sender:
397         return "Sender";
398     case Identity:
399         return "Identity";
400     case IdentityNick:
401         return "IdentityNick";
402     case Network:
403         return "Network";
404     case Buffer:
405         return "Buffer";
406     case Backlog:
407         return "Backlog";
408     case IrcServer:
409         return "IrcServer";
410     case UserSetting:
411         return "UserSetting";
412     case CoreState:
413         return "CoreState";
414     };
415     return QString();
416 }
417
418
419 QVariantList AbstractSqlMigrator::boundValues()
420 {
421     QVariantList values;
422     if (!_query)
423         return values;
424
425     int numValues = _query->boundValues().count();
426     for (int i = 0; i < numValues; i++) {
427         values << _query->boundValue(i);
428     }
429     return values;
430 }
431
432
433 void AbstractSqlMigrator::dumpStatus()
434 {
435     qWarning() << "  executed Query:";
436     qWarning() << qPrintable(executedQuery());
437     qWarning() << "  bound Values:";
438     QList<QVariant> list = boundValues();
439     for (int i = 0; i < list.size(); ++i)
440         qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
441     qWarning() << "  Error Number:"   << lastError().number();
442     qWarning() << "  Error Message:"   << lastError().text();
443 }
444
445
446 // ========================================
447 //  AbstractSqlMigrationReader
448 // ========================================
449 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
450     : AbstractSqlMigrator(),
451     _writer(0)
452 {
453 }
454
455
456 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
457 {
458     if (!transaction()) {
459         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
460         return false;
461     }
462     if (!writer->transaction()) {
463         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
464         rollback(); // close the reader transaction;
465         return false;
466     }
467
468     _writer = writer;
469
470     // due to the incompatibility across Migration objects we can't run this in a loop... :/
471     QuasselUserMO quasselUserMo;
472     if (!transferMo(QuasselUser, quasselUserMo))
473         return false;
474
475     IdentityMO identityMo;
476     if (!transferMo(Identity, identityMo))
477         return false;
478
479     IdentityNickMO identityNickMo;
480     if (!transferMo(IdentityNick, identityNickMo))
481         return false;
482
483     NetworkMO networkMo;
484     if (!transferMo(Network, networkMo))
485         return false;
486
487     BufferMO bufferMo;
488     if (!transferMo(Buffer, bufferMo))
489         return false;
490
491     SenderMO senderMo;
492     if (!transferMo(Sender, senderMo))
493         return false;
494
495     BacklogMO backlogMo;
496     if (!transferMo(Backlog, backlogMo))
497         return false;
498
499     IrcServerMO ircServerMo;
500     if (!transferMo(IrcServer, ircServerMo))
501         return false;
502
503     UserSettingMO userSettingMo;
504     if (!transferMo(UserSetting, userSettingMo))
505         return false;
506
507     CoreStateMO coreStateMO;
508     if (!transferMo(CoreState, coreStateMO))
509         return false;
510
511     if (!_writer->postProcess())
512         abortMigration();
513     return finalizeMigration();
514 }
515
516
517 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
518 {
519     qWarning() << "Migration Failed!";
520     if (!errorMsg.isNull()) {
521         qWarning() << qPrintable(errorMsg);
522     }
523     if (lastError().isValid()) {
524         qWarning() << "ReaderError:";
525         dumpStatus();
526     }
527
528     if (_writer->lastError().isValid()) {
529         qWarning() << "WriterError:";
530         _writer->dumpStatus();
531     }
532
533     rollback();
534     _writer->rollback();
535     _writer = 0;
536 }
537
538
539 bool AbstractSqlMigrationReader::finalizeMigration()
540 {
541     resetQuery();
542     _writer->resetQuery();
543
544     commit();
545     if (!_writer->commit()) {
546         _writer = 0;
547         return false;
548     }
549     _writer = 0;
550     return true;
551 }
552
553
554 template<typename T>
555 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
556 {
557     resetQuery();
558     _writer->resetQuery();
559
560     if (!prepareQuery(moType)) {
561         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
562         return false;
563     }
564     if (!_writer->prepareQuery(moType)) {
565         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
566         return false;
567     }
568
569     qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
570     int i = 0;
571     QFile file;
572     file.open(stdout, QIODevice::WriteOnly);
573
574     while (readMo(mo)) {
575         if (!_writer->writeMo(mo)) {
576             abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
577             return false;
578         }
579         i++;
580         if (i % 1000 == 0) {
581             file.write("*");
582             file.flush();
583         }
584     }
585     if (i > 1000) {
586         file.write("\n");
587         file.flush();
588     }
589
590     qDebug() << "Done.";
591     return true;
592 }
593
594 uint qHash(const SenderData &key) {
595     return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
596 }
597
598 bool operator==(const SenderData &a, const SenderData &b) {
599     return a.sender == b.sender &&
600         a.realname == b.realname &&
601         a.avatarurl == b.avatarurl;
602 }