1 /***************************************************************************
2 * Copyright (C) 2005-2019 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"
23 #include <QMutexLocker>
29 #include "logmessage.h"
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 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..."));
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()));
157 quInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
162 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
166 // The current schema is stored in the root folder, while upgrade queries are stored in the
167 // 'versions/##' subfolders.
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();
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));
178 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
179 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
183 QFile queryFile(queryInfo.filePath());
184 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
186 QString query = QTextStream(&queryFile).readAll();
189 return query.trimmed();
193 QStringList AbstractSqlStorage::setupQueries()
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());
205 bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
206 bool loadFromEnvironment)
208 setConnectionProperties(settings, environment, loadFromEnvironment);
209 QSqlDatabase db = logDb();
211 qCritical() << "Unable to setup Logging Backend!";
216 foreach(QString queryString, setupQueries()) {
217 QSqlQuery query = db.exec(queryString);
218 if (!watchQuery(query)) {
219 qCritical() << "Unable to setup Logging Backend!";
224 bool success = setupSchemaVersion(schemaVersion());
233 QStringList AbstractSqlStorage::upgradeQueries(int version)
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);
245 bool AbstractSqlStorage::upgradeDb()
247 if (schemaVersion() <= installedSchemaVersion())
250 QSqlDatabase db = logDb();
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.
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"
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.
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
274 if (!updateSchemaVersion(ver)) {
275 // Updating the schema version failed, bail out
276 qCritical() << "Unable to upgrade Logging Backend! Setting schema version"
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.";
291 // If we made it here, everything seems to have worked!
296 int AbstractSqlStorage::schemaVersion()
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;
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())
311 version = fileInfo.fileName().toInt(&ok);
315 if (version > _schemaVersion)
316 _schemaVersion = version;
318 return _schemaVersion;
322 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
324 bool queryError = query.lastError().isValid();
325 if (queryError || _debug) {
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) {
336 if (query.driver()) {
337 // let the driver do the formatting
338 field.setType(iter.value().type());
339 if (iter.value().isNull())
342 field.setValue(iter.value());
343 value = query.driver()->formatValue(field);
346 switch (iter.value().type()) {
347 case QVariant::Invalid:
351 value = iter.value().toString();
354 value = QString("'%1'").arg(iter.value().toString());
357 valueStrings << QString("%1=%2").arg(iter.key(), value);
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());
371 void AbstractSqlStorage::connectionDestroyed()
373 QMutexLocker locker(&_connectionPoolMutex);
374 _connectionPool.remove(sender()->thread());
378 // ========================================
379 // AbstractSqlStorage::Connection
380 // ========================================
381 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
383 _name(name.toLatin1())
388 AbstractSqlStorage::Connection::~Connection()
391 QSqlDatabase db = QSqlDatabase::database(name(), false);
397 QSqlDatabase::removeDatabase(name());
401 // ========================================
402 // AbstractSqlMigrator
403 // ========================================
404 AbstractSqlMigrator::AbstractSqlMigrator()
410 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
413 _query = new QSqlQuery(db);
414 _query->prepare(query);
418 void AbstractSqlMigrator::resetQuery()
425 bool AbstractSqlMigrator::exec()
429 return !_query->lastError().isValid();
433 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
437 return "QuasselUser";
443 return "IdentityNick";
453 return "UserSetting";
461 QVariantList AbstractSqlMigrator::boundValues()
467 int numValues = _query->boundValues().count();
468 for (int i = 0; i < numValues; i++) {
469 values << _query->boundValue(i);
475 void AbstractSqlMigrator::dumpStatus()
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();
488 // ========================================
489 // AbstractSqlMigrationReader
490 // ========================================
491 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
492 : AbstractSqlMigrator(),
498 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
500 if (!transaction()) {
501 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
504 if (!writer->transaction()) {
505 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
506 rollback(); // close the reader transaction;
512 // due to the incompatibility across Migration objects we can't run this in a loop... :/
513 QuasselUserMO quasselUserMo;
514 if (!transferMo(QuasselUser, quasselUserMo))
517 IdentityMO identityMo;
518 if (!transferMo(Identity, identityMo))
521 IdentityNickMO identityNickMo;
522 if (!transferMo(IdentityNick, identityNickMo))
526 if (!transferMo(Network, networkMo))
530 if (!transferMo(Buffer, bufferMo))
534 if (!transferMo(Sender, senderMo))
538 if (!transferMo(Backlog, backlogMo))
541 IrcServerMO ircServerMo;
542 if (!transferMo(IrcServer, ircServerMo))
545 UserSettingMO userSettingMo;
546 if (!transferMo(UserSetting, userSettingMo))
549 CoreStateMO coreStateMO;
550 if (!transferMo(CoreState, coreStateMO))
553 if (!_writer->postProcess())
555 return finalizeMigration();
559 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
561 qWarning() << "Migration Failed!";
562 if (!errorMsg.isNull()) {
563 qWarning() << qPrintable(errorMsg);
565 if (lastError().isValid()) {
566 qWarning() << "ReaderError:";
570 if (_writer->lastError().isValid()) {
571 qWarning() << "WriterError:";
572 _writer->dumpStatus();
581 bool AbstractSqlMigrationReader::finalizeMigration()
584 _writer->resetQuery();
587 if (!_writer->commit()) {
597 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
600 _writer->resetQuery();
602 if (!prepareQuery(moType)) {
603 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
606 if (!_writer->prepareQuery(moType)) {
607 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
611 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
614 file.open(stdout, QIODevice::WriteOnly);
617 if (!_writer->writeMo(mo)) {
618 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
636 uint qHash(const SenderData &key) {
637 return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
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;