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 QList<AbstractSqlStorage::SqlQueryResource> AbstractSqlStorage::setupQueries()
195 QList<SqlQueryResource> queries;
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 << SqlQueryResource(queryString(fileInfo.baseName()), 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 (auto queryResource, setupQueries()) {
217 QSqlQuery query = db.exec(queryResource.queryString);
218 if (!watchQuery(query)) {
219 qCritical() << qPrintable(QString("Unable to setup Logging Backend! Setup query failed (step: %1).")
220 .arg(queryResource.queryFilename));
225 bool success = setupSchemaVersion(schemaVersion());
234 QList<AbstractSqlStorage::SqlQueryResource> AbstractSqlStorage::upgradeQueries(int version)
236 QList<SqlQueryResource> 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 << SqlQueryResource(queryString(fileInfo.baseName(), version), fileInfo.baseName());
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 // Check if we're resuming an interrupted multi-step upgrade: is an upgrade step stored?
258 const QString previousLaunchUpgradeStep = schemaVersionUpgradeStep();
259 bool resumingUpgrade = !previousLaunchUpgradeStep.isEmpty();
261 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
262 foreach (auto queryResource, upgradeQueries(ver)) {
263 if (resumingUpgrade) {
264 // An upgrade was interrupted. Check if this matches the the last successful query.
265 if (previousLaunchUpgradeStep == queryResource.queryFilename) {
266 // Found the matching query!
267 quInfo() << qPrintable(QString("Resuming interrupted upgrade for schema version %1 (last step: %2)")
268 .arg(QString::number(ver), previousLaunchUpgradeStep));
270 // Stop searching for queries
271 resumingUpgrade = false;
272 // Continue past the previous query with the next not-yet-tried query
276 // Not yet matched, keep looking
281 // Run the upgrade query
282 QSqlQuery query = db.exec(queryResource.queryString);
283 if (!watchQuery(query)) {
284 // Individual upgrade query failed, bail out
285 qCritical() << qPrintable(QString("Unable to upgrade Logging Backend! Upgrade query in schema version %1 failed (step: %2).")
286 .arg(QString::number(ver), queryResource.queryFilename));
290 // Mark as successful
291 setSchemaVersionUpgradeStep(queryResource.queryFilename);
295 if (resumingUpgrade) {
296 // Something went wrong and the last successful SQL query to resume from couldn't be
298 // 1. The storage of successful query glitched, or the database was manually changed
299 // 2. Quassel changed the filenames of upgrade queries, and the local Quassel core
300 // version was replaced during an interrupted schema upgrade
302 // Both are unlikely, but it's a good idea to handle it anyways.
304 qCritical() << qPrintable(QString("Unable to resume interrupted upgrade in Logging "
305 "Backend! Missing upgrade step in schema version %1 "
306 "(expected step: %2)")
307 .arg(QString::number(ver), previousLaunchUpgradeStep));
311 // Update the schema version for each intermediate step and mark the step as done. This
312 // ensures that any interrupted upgrades have a greater chance of resuming correctly after
315 // Almost all databases make single queries atomic (fully works or fully fails, no partial),
316 // and with many of the longest migrations being a single query, this makes upgrade
317 // interruptions much more likely to leave the database in a valid intermediate schema
319 if (!updateSchemaVersion(ver, true)) {
320 // Updating the schema version failed, bail out
321 qCritical() << "Unable to upgrade Logging Backend! Setting schema version"
327 // If we made it here, everything seems to have worked!
332 int AbstractSqlStorage::schemaVersion()
334 // returns the newest Schema Version!
335 // not the currently used one! (though it can be the same)
336 if (_schemaVersion > 0)
337 return _schemaVersion;
341 // Schema versions are stored in the 'version/##' subfolders.
342 QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
343 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
344 if (!fileInfo.isDir())
347 version = fileInfo.fileName().toInt(&ok);
351 if (version > _schemaVersion)
352 _schemaVersion = version;
354 return _schemaVersion;
358 QString AbstractSqlStorage::schemaVersionUpgradeStep()
360 // By default, assume there's no pending upgrade
365 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
367 bool queryError = query.lastError().isValid();
368 if (queryError || _debug) {
370 qCritical() << "unhandled Error in QSqlQuery!";
371 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
372 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
373 QVariantMap boundValues = query.boundValues();
374 QStringList valueStrings;
375 QVariantMap::const_iterator iter;
376 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
379 if (query.driver()) {
380 // let the driver do the formatting
381 field.setType(iter.value().type());
382 if (iter.value().isNull())
385 field.setValue(iter.value());
386 value = query.driver()->formatValue(field);
389 switch (iter.value().type()) {
390 case QVariant::Invalid:
394 value = iter.value().toString();
397 value = QString("'%1'").arg(iter.value().toString());
400 valueStrings << QString("%1=%2").arg(iter.key(), value);
402 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
403 qCritical() << " Error Number:" << query.lastError().number();
404 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
405 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
406 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
414 void AbstractSqlStorage::connectionDestroyed()
416 QMutexLocker locker(&_connectionPoolMutex);
417 _connectionPool.remove(sender()->thread());
421 // ========================================
422 // AbstractSqlStorage::Connection
423 // ========================================
424 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
426 _name(name.toLatin1())
431 AbstractSqlStorage::Connection::~Connection()
434 QSqlDatabase db = QSqlDatabase::database(name(), false);
440 QSqlDatabase::removeDatabase(name());
444 // ========================================
445 // AbstractSqlMigrator
446 // ========================================
447 AbstractSqlMigrator::AbstractSqlMigrator()
453 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
456 _query = new QSqlQuery(db);
457 _query->prepare(query);
461 void AbstractSqlMigrator::resetQuery()
468 bool AbstractSqlMigrator::exec()
472 return !_query->lastError().isValid();
476 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
480 return "QuasselUser";
486 return "IdentityNick";
496 return "UserSetting";
504 QVariantList AbstractSqlMigrator::boundValues()
510 int numValues = _query->boundValues().count();
511 for (int i = 0; i < numValues; i++) {
512 values << _query->boundValue(i);
518 void AbstractSqlMigrator::dumpStatus()
520 qWarning() << " executed Query:";
521 qWarning() << qPrintable(executedQuery());
522 qWarning() << " bound Values:";
523 QList<QVariant> list = boundValues();
524 for (int i = 0; i < list.size(); ++i)
525 qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
526 qWarning() << " Error Number:" << lastError().number();
527 qWarning() << " Error Message:" << lastError().text();
531 // ========================================
532 // AbstractSqlMigrationReader
533 // ========================================
534 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
535 : AbstractSqlMigrator(),
541 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
543 if (!transaction()) {
544 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
547 if (!writer->transaction()) {
548 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
549 rollback(); // close the reader transaction;
555 // due to the incompatibility across Migration objects we can't run this in a loop... :/
556 QuasselUserMO quasselUserMo;
557 if (!transferMo(QuasselUser, quasselUserMo))
560 IdentityMO identityMo;
561 if (!transferMo(Identity, identityMo))
564 IdentityNickMO identityNickMo;
565 if (!transferMo(IdentityNick, identityNickMo))
569 if (!transferMo(Network, networkMo))
573 if (!transferMo(Buffer, bufferMo))
577 if (!transferMo(Sender, senderMo))
581 if (!transferMo(Backlog, backlogMo))
584 IrcServerMO ircServerMo;
585 if (!transferMo(IrcServer, ircServerMo))
588 UserSettingMO userSettingMo;
589 if (!transferMo(UserSetting, userSettingMo))
592 CoreStateMO coreStateMO;
593 if (!transferMo(CoreState, coreStateMO))
596 if (!_writer->postProcess())
598 return finalizeMigration();
602 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
604 qWarning() << "Migration Failed!";
605 if (!errorMsg.isNull()) {
606 qWarning() << qPrintable(errorMsg);
608 if (lastError().isValid()) {
609 qWarning() << "ReaderError:";
613 if (_writer->lastError().isValid()) {
614 qWarning() << "WriterError:";
615 _writer->dumpStatus();
624 bool AbstractSqlMigrationReader::finalizeMigration()
627 _writer->resetQuery();
630 if (!_writer->commit()) {
640 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
643 _writer->resetQuery();
645 if (!prepareQuery(moType)) {
646 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
649 if (!_writer->prepareQuery(moType)) {
650 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
654 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
657 file.open(stdout, QIODevice::WriteOnly);
660 if (!_writer->writeMo(mo)) {
661 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
679 uint qHash(const SenderData &key) {
680 return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
683 bool operator==(const SenderData &a, const SenderData &b) {
684 return a.sender == b.sender &&
685 a.realname == b.realname &&
686 a.avatarurl == b.avatarurl;