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"
23 #include <QMutexLocker>
31 int AbstractSqlStorage::_nextConnectionId = 0;
32 AbstractSqlStorage::AbstractSqlStorage(QObject* parent)
36 AbstractSqlStorage::~AbstractSqlStorage()
38 // disconnect the connections, so their deletion is no longer interessting for us
39 QHash<QThread*, Connection*>::iterator conIter;
40 for (conIter = _connectionPool.begin(); conIter != _connectionPool.end(); ++conIter) {
41 QSqlDatabase::removeDatabase(conIter.value()->name());
42 disconnect(conIter.value(), nullptr, this, nullptr);
46 QSqlDatabase AbstractSqlStorage::logDb()
48 if (!_connectionPool.contains(QThread::currentThread()))
49 addConnectionToPool();
51 QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(), false);
54 qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread()
55 << "was lost, attempting to reconnect...";
62 void AbstractSqlStorage::addConnectionToPool()
64 QMutexLocker locker(&_connectionPoolMutex);
65 // we have to recheck if the connection pool already contains a connection for
66 // this thread. Since now (after the lock) we can only tell for sure
67 if (_connectionPool.contains(QThread::currentThread()))
70 QThread* currentThread = QThread::currentThread();
72 int connectionId = _nextConnectionId++;
74 Connection* connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
75 connection->moveToThread(currentThread);
76 connect(this, &QObject::destroyed, connection, &QObject::deleteLater);
77 connect(currentThread, &QObject::destroyed, connection, &QObject::deleteLater);
78 connect(connection, &QObject::destroyed, this, &AbstractSqlStorage::connectionDestroyed);
79 _connectionPool[currentThread] = connection;
81 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
82 db.setDatabaseName(databaseName());
84 if (!hostName().isEmpty())
85 db.setHostName(hostName());
90 if (!userName().isEmpty()) {
91 db.setUserName(userName());
92 db.setPassword(password());
98 void AbstractSqlStorage::dbConnect(QSqlDatabase& db)
101 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
102 qWarning() << "-" << db.lastError().text();
105 if (!initDbSession(db)) {
106 qWarning() << "Unable to initialize database" << displayName() << "for thread" << QThread::currentThread();
112 Storage::State AbstractSqlStorage::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
114 setConnectionProperties(settings, environment, loadFromEnvironment);
116 _debug = Quassel::isOptionSet("debug");
118 QSqlDatabase db = logDb();
119 if (!db.isValid() || !db.isOpen())
122 if (installedSchemaVersion() == -1) {
123 qCritical() << "Storage Schema is missing!";
127 if (installedSchemaVersion() > schemaVersion()) {
128 qCritical() << "Installed Schema is newer then any known Version.";
132 if (installedSchemaVersion() < schemaVersion()) {
133 qInfo() << qPrintable(tr("Installed database schema (version %1) is not up to date. Upgrading to "
134 "version %2... This may take a while for major upgrades.")
135 .arg(installedSchemaVersion())
136 .arg(schemaVersion()));
137 emit dbUpgradeInProgress(true);
138 auto upgradeResult = upgradeDb();
139 emit dbUpgradeInProgress(false);
140 if (!upgradeResult) {
141 qWarning() << qPrintable(tr("Upgrade failed..."));
144 // Add a message when migration succeeds to avoid confusing folks by implying the schema upgrade failed if
145 // later functionality does not work.
146 qInfo() << qPrintable(tr("Installed database schema successfully upgraded to version %1.").arg(schemaVersion()));
149 qInfo() << qPrintable(displayName()) << "storage backend is ready. Schema version:" << installedSchemaVersion();
153 QString AbstractSqlStorage::queryString(const QString& queryName, int version)
157 // The current schema is stored in the root folder, while upgrade queries are stored in the
158 // 'versions/##' subfolders.
160 // Use the current SQL schema, not a versioned request
161 queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName));
162 // If version is needed later, get it via version = schemaVersion();
165 // Use the specified schema version, not the general folder
166 queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
169 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
170 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
174 QFile queryFile(queryInfo.filePath());
175 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
177 QString query = QTextStream(&queryFile).readAll();
180 return query.trimmed();
183 QStringList AbstractSqlStorage::setupQueries()
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());
194 bool AbstractSqlStorage::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
196 setConnectionProperties(settings, environment, loadFromEnvironment);
197 QSqlDatabase db = logDb();
199 qCritical() << "Unable to setup Logging Backend!";
204 foreach (QString queryString, setupQueries()) {
205 QSqlQuery query = db.exec(queryString);
206 if (!watchQuery(query)) {
207 qCritical() << "Unable to setup Logging Backend!";
212 bool success = setupSchemaVersion(schemaVersion());
220 QStringList AbstractSqlStorage::upgradeQueries(int version)
223 // Upgrade queries are stored in the 'version/##' subfolders.
224 QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version));
225 foreach (QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
226 queries << queryString(fileInfo.baseName(), version);
231 bool AbstractSqlStorage::upgradeDb()
233 if (schemaVersion() <= installedSchemaVersion())
236 QSqlDatabase db = logDb();
238 // TODO: For databases that support it (e.g. almost only PostgreSQL), wrap upgrades in a
239 // transaction. This will need careful testing of potential additional space requirements and
240 // any database modifications that might not be allowed in a transaction.
242 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
243 foreach (QString queryString, upgradeQueries(ver)) {
244 QSqlQuery query = db.exec(queryString);
245 if (!watchQuery(query)) {
246 // Individual upgrade query failed, bail out
247 qCritical() << "Unable to upgrade Logging Backend! Upgrade query in schema version" << ver << "failed.";
252 // Update the schema version for each intermediate step. This ensures that any interrupted
253 // upgrades have a greater chance of resuming correctly after core restart.
255 // Almost all databases make single queries atomic (fully works or fully fails, no partial),
256 // and with many of the longest migrations being a single query, this makes upgrade
257 // interruptions much more likely to leave the database in a valid intermediate schema
259 if (!updateSchemaVersion(ver)) {
260 // Updating the schema version failed, bail out
261 qCritical() << "Unable to upgrade Logging Backend! Setting schema version" << ver << "failed.";
266 // Update the schema version for the final step. Split this out to offer more informative
267 // logging (though setting schema version really should not fail).
268 if (!updateSchemaVersion(schemaVersion())) {
269 // Updating the final schema version failed, bail out
270 qCritical() << "Unable to upgrade Logging Backend! Setting final schema version" << schemaVersion() << "failed.";
274 // If we made it here, everything seems to have worked!
278 int AbstractSqlStorage::schemaVersion()
280 // returns the newest Schema Version!
281 // not the currently used one! (though it can be the same)
282 if (_schemaVersion > 0)
283 return _schemaVersion;
287 // Schema versions are stored in the 'version/##' subfolders.
288 QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
289 foreach (QFileInfo fileInfo, dir.entryInfoList()) {
290 if (!fileInfo.isDir())
293 version = fileInfo.fileName().toInt(&ok);
297 if (version > _schemaVersion)
298 _schemaVersion = version;
300 return _schemaVersion;
303 bool AbstractSqlStorage::watchQuery(QSqlQuery& query)
305 bool queryError = query.lastError().isValid();
306 if (queryError || _debug) {
308 qCritical() << "unhandled Error in QSqlQuery!";
309 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
310 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
311 QVariantMap boundValues = query.boundValues();
312 QStringList valueStrings;
313 QVariantMap::const_iterator iter;
314 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
317 if (query.driver()) {
318 // let the driver do the formatting
319 field.setType(iter.value().type());
320 if (iter.value().isNull())
323 field.setValue(iter.value());
324 value = query.driver()->formatValue(field);
327 switch (iter.value().type()) {
328 case QVariant::Invalid:
332 value = iter.value().toString();
335 value = QString("'%1'").arg(iter.value().toString());
338 valueStrings << QString("%1=%2").arg(iter.key(), value);
340 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
341 qCritical() << " Error Number:" << query.lastError().number();
342 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
343 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
344 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
351 void AbstractSqlStorage::connectionDestroyed()
353 QMutexLocker locker(&_connectionPoolMutex);
354 _connectionPool.remove(sender()->thread());
357 // ========================================
358 // AbstractSqlStorage::Connection
359 // ========================================
360 AbstractSqlStorage::Connection::Connection(const QString& name, QObject* parent)
362 , _name(name.toLatin1())
365 AbstractSqlStorage::Connection::~Connection()
368 QSqlDatabase db = QSqlDatabase::database(name(), false);
374 QSqlDatabase::removeDatabase(name());
377 // ========================================
378 // AbstractSqlMigrator
379 // ========================================
381 void AbstractSqlMigrator::newQuery(const QString& query, QSqlDatabase db)
384 _query = new QSqlQuery(db);
385 _query->prepare(query);
388 void AbstractSqlMigrator::resetQuery()
394 bool AbstractSqlMigrator::exec()
398 return !_query->lastError().isValid();
401 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
405 return "QuasselUser";
411 return "IdentityNick";
421 return "UserSetting";
428 QVariantList AbstractSqlMigrator::boundValues()
434 int numValues = _query->boundValues().count();
435 for (int i = 0; i < numValues; i++) {
436 values << _query->boundValue(i);
441 void AbstractSqlMigrator::dumpStatus()
443 qWarning() << " executed Query:";
444 qWarning() << qPrintable(executedQuery());
445 qWarning() << " bound Values:";
446 QList<QVariant> list = boundValues();
447 for (int i = 0; i < list.size(); ++i)
448 qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
449 qWarning() << " Error Number:" << lastError().number();
450 qWarning() << " Error Message:" << lastError().text();
453 // ========================================
454 // AbstractSqlMigrationReader
455 // ========================================
456 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
457 : AbstractSqlMigrator()
460 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter* writer)
462 if (!transaction()) {
463 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
466 if (!writer->transaction()) {
467 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
468 rollback(); // close the reader transaction;
474 // due to the incompatibility across Migration objects we can't run this in a loop... :/
475 QuasselUserMO quasselUserMo;
476 if (!transferMo(QuasselUser, quasselUserMo))
479 IdentityMO identityMo;
480 if (!transferMo(Identity, identityMo))
483 IdentityNickMO identityNickMo;
484 if (!transferMo(IdentityNick, identityNickMo))
488 if (!transferMo(Network, networkMo))
492 if (!transferMo(Buffer, bufferMo))
496 if (!transferMo(Sender, senderMo))
500 if (!transferMo(Backlog, backlogMo))
503 IrcServerMO ircServerMo;
504 if (!transferMo(IrcServer, ircServerMo))
507 UserSettingMO userSettingMo;
508 if (!transferMo(UserSetting, userSettingMo))
511 CoreStateMO coreStateMO;
512 if (!transferMo(CoreState, coreStateMO))
515 if (!_writer->postProcess())
517 return finalizeMigration();
520 void AbstractSqlMigrationReader::abortMigration(const QString& errorMsg)
522 qWarning() << "Migration Failed!";
523 if (!errorMsg.isNull()) {
524 qWarning() << qPrintable(errorMsg);
526 if (lastError().isValid()) {
527 qWarning() << "ReaderError:";
531 if (_writer->lastError().isValid()) {
532 qWarning() << "WriterError:";
533 _writer->dumpStatus();
541 bool AbstractSqlMigrationReader::finalizeMigration()
544 _writer->resetQuery();
547 if (!_writer->commit()) {
556 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T& mo)
559 _writer->resetQuery();
561 if (!prepareQuery(moType)) {
562 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!")
563 .arg(AbstractSqlMigrator::migrationObject(moType)));
566 if (!_writer->prepareQuery(moType)) {
567 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!")
568 .arg(AbstractSqlMigrator::migrationObject(moType)));
572 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
575 file.open(stdout, QIODevice::WriteOnly);
578 if (!_writer->writeMo(mo)) {
579 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!")
580 .arg(AbstractSqlMigrator::migrationObject(moType)));
598 uint qHash(const SenderData& key)
600 return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
603 bool operator==(const SenderData& a, const SenderData& b)
605 return a.sender == b.sender && a.realname == b.realname && a.avatarurl == b.avatarurl;