1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "abstractsqlstorage.h"
26 #include <QMutexLocker>
32 int AbstractSqlStorage::_nextConnectionId = 0;
33 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
40 AbstractSqlStorage::~AbstractSqlStorage()
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);
51 QSqlDatabase AbstractSqlStorage::logDb()
53 if (!_connectionPool.contains(QThread::currentThread()))
54 addConnectionToPool();
56 QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(),false);
59 qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread() << "was lost, attempting to reconnect...";
67 void AbstractSqlStorage::addConnectionToPool()
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()))
75 QThread *currentThread = QThread::currentThread();
77 int connectionId = _nextConnectionId++;
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;
86 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
87 db.setDatabaseName(databaseName());
89 if (!hostName().isEmpty())
90 db.setHostName(hostName());
95 if (!userName().isEmpty()) {
96 db.setUserName(userName());
97 db.setPassword(password());
104 void AbstractSqlStorage::dbConnect(QSqlDatabase &db)
107 quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
108 quWarning() << "-" << db.lastError().text();
111 if (!initDbSession(db)) {
112 quWarning() << "Unable to initialize database" << displayName() << "for thread" << QThread::currentThread();
119 Storage::State AbstractSqlStorage::init(const QVariantMap &settings,
120 const QProcessEnvironment &environment,
121 bool loadFromEnvironment)
123 setConnectionProperties(settings, environment, loadFromEnvironment);
125 _debug = Quassel::isOptionSet("debug");
127 QSqlDatabase db = logDb();
128 if (!db.isValid() || !db.isOpen())
131 if (installedSchemaVersion() == -1) {
132 qCritical() << "Storage Schema is missing!";
136 if (installedSchemaVersion() > schemaVersion()) {
137 qCritical() << "Installed Schema is newer then any known Version.";
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.
148 qWarning() << qPrintable(tr("Upgrade failed..."));
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()));
158 quInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
163 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
167 // The current schema is stored in the root folder, while upgrade queries are stored in the
168 // 'versions/##' subfolders.
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();
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));
179 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
180 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
184 QFile queryFile(queryInfo.filePath());
185 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
187 QString query = QTextStream(&queryFile).readAll();
190 return query.trimmed();
194 QStringList AbstractSqlStorage::setupQueries()
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());
206 bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
207 bool loadFromEnvironment)
209 setConnectionProperties(settings, environment, loadFromEnvironment);
210 QSqlDatabase db = logDb();
212 qCritical() << "Unable to setup Logging Backend!";
217 foreach(QString queryString, setupQueries()) {
218 QSqlQuery query = db.exec(queryString);
219 if (!watchQuery(query)) {
220 qCritical() << "Unable to setup Logging Backend!";
225 bool success = setupSchemaVersion(schemaVersion());
234 QStringList AbstractSqlStorage::upgradeQueries(int version)
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);
246 bool AbstractSqlStorage::upgradeDb()
248 if (schemaVersion() <= installedSchemaVersion())
251 QSqlDatabase db = logDb();
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.
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"
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.
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
275 if (!updateSchemaVersion(ver)) {
276 // Updating the schema version failed, bail out
277 qCritical() << "Unable to upgrade Logging Backend! Setting schema version"
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.";
292 // If we made it here, everything seems to have worked!
297 int AbstractSqlStorage::schemaVersion()
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;
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())
312 version = fileInfo.fileName().toInt(&ok);
316 if (version > _schemaVersion)
317 _schemaVersion = version;
319 return _schemaVersion;
323 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
325 bool queryError = query.lastError().isValid();
326 if (queryError || _debug) {
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) {
337 if (query.driver()) {
338 // let the driver do the formatting
339 field.setType(iter.value().type());
340 if (iter.value().isNull())
343 field.setValue(iter.value());
344 value = query.driver()->formatValue(field);
347 switch (iter.value().type()) {
348 case QVariant::Invalid:
352 value = iter.value().toString();
355 value = QString("'%1'").arg(iter.value().toString());
358 valueStrings << QString("%1=%2").arg(iter.key(), value);
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());
372 void AbstractSqlStorage::connectionDestroyed()
374 QMutexLocker locker(&_connectionPoolMutex);
375 _connectionPool.remove(sender()->thread());
379 // ========================================
380 // AbstractSqlStorage::Connection
381 // ========================================
382 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
384 _name(name.toLatin1())
389 AbstractSqlStorage::Connection::~Connection()
392 QSqlDatabase db = QSqlDatabase::database(name(), false);
398 QSqlDatabase::removeDatabase(name());
402 // ========================================
403 // AbstractSqlMigrator
404 // ========================================
405 AbstractSqlMigrator::AbstractSqlMigrator()
411 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
414 _query = new QSqlQuery(db);
415 _query->prepare(query);
419 void AbstractSqlMigrator::resetQuery()
426 bool AbstractSqlMigrator::exec()
430 return !_query->lastError().isValid();
434 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
438 return "QuasselUser";
444 return "IdentityNick";
454 return "UserSetting";
462 QVariantList AbstractSqlMigrator::boundValues()
468 int numValues = _query->boundValues().count();
469 for (int i = 0; i < numValues; i++) {
470 values << _query->boundValue(i);
476 void AbstractSqlMigrator::dumpStatus()
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();
489 // ========================================
490 // AbstractSqlMigrationReader
491 // ========================================
492 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
493 : AbstractSqlMigrator(),
499 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
501 if (!transaction()) {
502 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
505 if (!writer->transaction()) {
506 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
507 rollback(); // close the reader transaction;
513 // due to the incompatibility across Migration objects we can't run this in a loop... :/
514 QuasselUserMO quasselUserMo;
515 if (!transferMo(QuasselUser, quasselUserMo))
518 IdentityMO identityMo;
519 if (!transferMo(Identity, identityMo))
522 IdentityNickMO identityNickMo;
523 if (!transferMo(IdentityNick, identityNickMo))
527 if (!transferMo(Network, networkMo))
531 if (!transferMo(Buffer, bufferMo))
535 if (!transferMo(Sender, senderMo))
539 if (!transferMo(Backlog, backlogMo))
542 IrcServerMO ircServerMo;
543 if (!transferMo(IrcServer, ircServerMo))
546 UserSettingMO userSettingMo;
547 if (!transferMo(UserSetting, userSettingMo))
550 CoreStateMO coreStateMO;
551 if (!transferMo(CoreState, coreStateMO))
554 if (!_writer->postProcess())
556 return finalizeMigration();
560 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
562 qWarning() << "Migration Failed!";
563 if (!errorMsg.isNull()) {
564 qWarning() << qPrintable(errorMsg);
566 if (lastError().isValid()) {
567 qWarning() << "ReaderError:";
571 if (_writer->lastError().isValid()) {
572 qWarning() << "WriterError:";
573 _writer->dumpStatus();
582 bool AbstractSqlMigrationReader::finalizeMigration()
585 _writer->resetQuery();
588 if (!_writer->commit()) {
598 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
601 _writer->resetQuery();
603 if (!prepareQuery(moType)) {
604 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
607 if (!_writer->prepareQuery(moType)) {
608 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
612 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
615 file.open(stdout, QIODevice::WriteOnly);
618 if (!_writer->writeMo(mo)) {
619 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
637 uint qHash(const SenderData &key) {
638 return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
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;