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 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
254 foreach(QString queryString, upgradeQueries(ver)) {
255 QSqlQuery query = db.exec(queryString);
256 if (!watchQuery(query)) {
257 qCritical() << "Unable to upgrade Logging Backend!";
262 return updateSchemaVersion(schemaVersion());
266 int AbstractSqlStorage::schemaVersion()
268 // returns the newest Schema Version!
269 // not the currently used one! (though it can be the same)
270 if (_schemaVersion > 0)
271 return _schemaVersion;
275 // Schema versions are stored in the 'version/##' subfolders.
276 QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
277 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
278 if (!fileInfo.isDir())
281 version = fileInfo.fileName().toInt(&ok);
285 if (version > _schemaVersion)
286 _schemaVersion = version;
288 return _schemaVersion;
292 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
294 bool queryError = query.lastError().isValid();
295 if (queryError || _debug) {
297 qCritical() << "unhandled Error in QSqlQuery!";
298 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
299 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
300 QVariantMap boundValues = query.boundValues();
301 QStringList valueStrings;
302 QVariantMap::const_iterator iter;
303 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
306 if (query.driver()) {
307 // let the driver do the formatting
308 field.setType(iter.value().type());
309 if (iter.value().isNull())
312 field.setValue(iter.value());
313 value = query.driver()->formatValue(field);
316 switch (iter.value().type()) {
317 case QVariant::Invalid:
321 value = iter.value().toString();
324 value = QString("'%1'").arg(iter.value().toString());
327 valueStrings << QString("%1=%2").arg(iter.key(), value);
329 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
330 qCritical() << " Error Number:" << query.lastError().number();
331 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
332 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
333 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
341 void AbstractSqlStorage::connectionDestroyed()
343 QMutexLocker locker(&_connectionPoolMutex);
344 _connectionPool.remove(sender()->thread());
348 // ========================================
349 // AbstractSqlStorage::Connection
350 // ========================================
351 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
353 _name(name.toLatin1())
358 AbstractSqlStorage::Connection::~Connection()
361 QSqlDatabase db = QSqlDatabase::database(name(), false);
367 QSqlDatabase::removeDatabase(name());
371 // ========================================
372 // AbstractSqlMigrator
373 // ========================================
374 AbstractSqlMigrator::AbstractSqlMigrator()
380 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
383 _query = new QSqlQuery(db);
384 _query->prepare(query);
388 void AbstractSqlMigrator::resetQuery()
395 bool AbstractSqlMigrator::exec()
399 return !_query->lastError().isValid();
403 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
407 return "QuasselUser";
413 return "IdentityNick";
423 return "UserSetting";
431 QVariantList AbstractSqlMigrator::boundValues()
437 int numValues = _query->boundValues().count();
438 for (int i = 0; i < numValues; i++) {
439 values << _query->boundValue(i);
445 void AbstractSqlMigrator::dumpStatus()
447 qWarning() << " executed Query:";
448 qWarning() << qPrintable(executedQuery());
449 qWarning() << " bound Values:";
450 QList<QVariant> list = boundValues();
451 for (int i = 0; i < list.size(); ++i)
452 qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
453 qWarning() << " Error Number:" << lastError().number();
454 qWarning() << " Error Message:" << lastError().text();
458 // ========================================
459 // AbstractSqlMigrationReader
460 // ========================================
461 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
462 : AbstractSqlMigrator(),
468 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
470 if (!transaction()) {
471 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
474 if (!writer->transaction()) {
475 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
476 rollback(); // close the reader transaction;
482 // due to the incompatibility across Migration objects we can't run this in a loop... :/
483 QuasselUserMO quasselUserMo;
484 if (!transferMo(QuasselUser, quasselUserMo))
487 IdentityMO identityMo;
488 if (!transferMo(Identity, identityMo))
491 IdentityNickMO identityNickMo;
492 if (!transferMo(IdentityNick, identityNickMo))
496 if (!transferMo(Network, networkMo))
500 if (!transferMo(Buffer, bufferMo))
504 if (!transferMo(Sender, senderMo))
508 if (!transferMo(Backlog, backlogMo))
511 IrcServerMO ircServerMo;
512 if (!transferMo(IrcServer, ircServerMo))
515 UserSettingMO userSettingMo;
516 if (!transferMo(UserSetting, userSettingMo))
519 CoreStateMO coreStateMO;
520 if (!transferMo(CoreState, coreStateMO))
523 if (!_writer->postProcess())
525 return finalizeMigration();
529 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
531 qWarning() << "Migration Failed!";
532 if (!errorMsg.isNull()) {
533 qWarning() << qPrintable(errorMsg);
535 if (lastError().isValid()) {
536 qWarning() << "ReaderError:";
540 if (_writer->lastError().isValid()) {
541 qWarning() << "WriterError:";
542 _writer->dumpStatus();
551 bool AbstractSqlMigrationReader::finalizeMigration()
554 _writer->resetQuery();
557 if (!_writer->commit()) {
567 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
570 _writer->resetQuery();
572 if (!prepareQuery(moType)) {
573 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
576 if (!_writer->prepareQuery(moType)) {
577 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
581 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
584 file.open(stdout, QIODevice::WriteOnly);
587 if (!_writer->writeMo(mo)) {
588 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
606 uint qHash(const SenderData &key) {
607 return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
610 bool operator==(const SenderData &a, const SenderData &b) {
611 return a.sender == b.sender &&
612 a.realname == b.realname &&
613 a.avatarurl == b.avatarurl;