4ecf623bc592f728059c77bbf35f7cb41dc2e3ff
[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     };
413     return QString();
414 }
415
416
417 QVariantList AbstractSqlMigrator::boundValues()
418 {
419     QVariantList values;
420     if (!_query)
421         return values;
422
423     int numValues = _query->boundValues().count();
424     for (int i = 0; i < numValues; i++) {
425         values << _query->boundValue(i);
426     }
427     return values;
428 }
429
430
431 void AbstractSqlMigrator::dumpStatus()
432 {
433     qWarning() << "  executed Query:";
434     qWarning() << qPrintable(executedQuery());
435     qWarning() << "  bound Values:";
436     QList<QVariant> list = boundValues();
437     for (int i = 0; i < list.size(); ++i)
438         qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
439     qWarning() << "  Error Number:"   << lastError().number();
440     qWarning() << "  Error Message:"   << lastError().text();
441 }
442
443
444 // ========================================
445 //  AbstractSqlMigrationReader
446 // ========================================
447 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
448     : AbstractSqlMigrator(),
449     _writer(0)
450 {
451 }
452
453
454 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
455 {
456     if (!transaction()) {
457         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
458         return false;
459     }
460     if (!writer->transaction()) {
461         qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
462         rollback(); // close the reader transaction;
463         return false;
464     }
465
466     _writer = writer;
467
468     // due to the incompatibility across Migration objects we can't run this in a loop... :/
469     QuasselUserMO quasselUserMo;
470     if (!transferMo(QuasselUser, quasselUserMo))
471         return false;
472
473     IdentityMO identityMo;
474     if (!transferMo(Identity, identityMo))
475         return false;
476
477     IdentityNickMO identityNickMo;
478     if (!transferMo(IdentityNick, identityNickMo))
479         return false;
480
481     NetworkMO networkMo;
482     if (!transferMo(Network, networkMo))
483         return false;
484
485     BufferMO bufferMo;
486     if (!transferMo(Buffer, bufferMo))
487         return false;
488
489     SenderMO senderMo;
490     if (!transferMo(Sender, senderMo))
491         return false;
492
493     BacklogMO backlogMo;
494     if (!transferMo(Backlog, backlogMo))
495         return false;
496
497     IrcServerMO ircServerMo;
498     if (!transferMo(IrcServer, ircServerMo))
499         return false;
500
501     UserSettingMO userSettingMo;
502     if (!transferMo(UserSetting, userSettingMo))
503         return false;
504
505     if (!_writer->postProcess())
506         abortMigration();
507     return finalizeMigration();
508 }
509
510
511 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
512 {
513     qWarning() << "Migration Failed!";
514     if (!errorMsg.isNull()) {
515         qWarning() << qPrintable(errorMsg);
516     }
517     if (lastError().isValid()) {
518         qWarning() << "ReaderError:";
519         dumpStatus();
520     }
521
522     if (_writer->lastError().isValid()) {
523         qWarning() << "WriterError:";
524         _writer->dumpStatus();
525     }
526
527     rollback();
528     _writer->rollback();
529     _writer = 0;
530 }
531
532
533 bool AbstractSqlMigrationReader::finalizeMigration()
534 {
535     resetQuery();
536     _writer->resetQuery();
537
538     commit();
539     if (!_writer->commit()) {
540         _writer = 0;
541         return false;
542     }
543     _writer = 0;
544     return true;
545 }
546
547
548 template<typename T>
549 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
550 {
551     resetQuery();
552     _writer->resetQuery();
553
554     if (!prepareQuery(moType)) {
555         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
556         return false;
557     }
558     if (!_writer->prepareQuery(moType)) {
559         abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
560         return false;
561     }
562
563     qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
564     int i = 0;
565     QFile file;
566     file.open(stdout, QIODevice::WriteOnly);
567
568     while (readMo(mo)) {
569         if (!_writer->writeMo(mo)) {
570             abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
571             return false;
572         }
573         i++;
574         if (i % 1000 == 0) {
575             file.write("*");
576             file.flush();
577         }
578     }
579     if (i > 1000) {
580         file.write("\n");
581         file.flush();
582     }
583
584     qDebug() << "Done.";
585     return true;
586 }
587
588 uint qHash(const SenderData &key) {
589     return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
590 }
591
592 bool operator==(const SenderData &a, const SenderData &b) {
593     return a.sender == b.sender &&
594         a.realname == b.realname &&
595         a.avatarurl == b.avatarurl;
596 }