1 /***************************************************************************
2 * Copyright (C) 2005-2013 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 return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
60 void AbstractSqlStorage::addConnectionToPool()
62 QMutexLocker locker(&_connectionPoolMutex);
63 // we have to recheck if the connection pool already contains a connection for
64 // this thread. Since now (after the lock) we can only tell for sure
65 if (_connectionPool.contains(QThread::currentThread()))
68 QThread *currentThread = QThread::currentThread();
70 int connectionId = _nextConnectionId++;
72 Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
73 connection->moveToThread(currentThread);
74 connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
75 connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
76 connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
77 _connectionPool[currentThread] = connection;
79 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
80 db.setDatabaseName(databaseName());
82 if (!hostName().isEmpty())
83 db.setHostName(hostName());
88 if (!userName().isEmpty()) {
89 db.setUserName(userName());
90 db.setPassword(password());
94 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
95 qWarning() << "-" << db.lastError().text();
103 Storage::State AbstractSqlStorage::init(const QVariantMap &settings)
105 setConnectionProperties(settings);
107 _debug = Quassel::isOptionSet("debug");
109 QSqlDatabase db = logDb();
110 if (!db.isValid() || !db.isOpen())
113 if (installedSchemaVersion() == -1) {
114 qCritical() << "Storage Schema is missing!";
118 if (installedSchemaVersion() > schemaVersion()) {
119 qCritical() << "Installed Schema is newer then any known Version.";
123 if (installedSchemaVersion() < schemaVersion()) {
124 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
126 qWarning() << qPrintable(tr("Upgrade failed..."));
131 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
136 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
139 version = schemaVersion();
141 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
142 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
143 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
147 QFile queryFile(queryInfo.filePath());
148 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
150 QString query = QTextStream(&queryFile).readAll();
153 return query.trimmed();
157 QStringList AbstractSqlStorage::setupQueries()
160 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
161 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
162 queries << queryString(fileInfo.baseName());
168 bool AbstractSqlStorage::setup(const QVariantMap &settings)
170 setConnectionProperties(settings);
171 QSqlDatabase db = logDb();
173 qCritical() << "Unable to setup Logging Backend!";
178 foreach(QString queryString, setupQueries()) {
179 QSqlQuery query = db.exec(queryString);
180 if (!watchQuery(query)) {
181 qCritical() << "Unable to setup Logging Backend!";
186 bool success = setupSchemaVersion(schemaVersion());
195 QStringList AbstractSqlStorage::upgradeQueries(int version)
198 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
199 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
200 queries << queryString(fileInfo.baseName(), version);
206 bool AbstractSqlStorage::upgradeDb()
208 if (schemaVersion() <= installedSchemaVersion())
211 QSqlDatabase db = logDb();
213 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
214 foreach(QString queryString, upgradeQueries(ver)) {
215 QSqlQuery query = db.exec(queryString);
216 if (!watchQuery(query)) {
217 qCritical() << "Unable to upgrade Logging Backend!";
222 return updateSchemaVersion(schemaVersion());
226 int AbstractSqlStorage::schemaVersion()
228 // returns the newest Schema Version!
229 // not the currently used one! (though it can be the same)
230 if (_schemaVersion > 0)
231 return _schemaVersion;
235 QDir dir = QDir(":/SQL/" + displayName());
236 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
237 if (!fileInfo.isDir())
240 version = fileInfo.fileName().toInt(&ok);
244 if (version > _schemaVersion)
245 _schemaVersion = version;
247 return _schemaVersion;
251 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
253 bool queryError = query.lastError().isValid();
254 if (queryError || _debug) {
256 qCritical() << "unhandled Error in QSqlQuery!";
257 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
258 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
259 QVariantMap boundValues = query.boundValues();
260 QStringList valueStrings;
261 QVariantMap::const_iterator iter;
262 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
265 if (query.driver()) {
266 // let the driver do the formatting
267 field.setType(iter.value().type());
268 if (iter.value().isNull())
271 field.setValue(iter.value());
272 value = query.driver()->formatValue(field);
275 switch (iter.value().type()) {
276 case QVariant::Invalid:
280 value = iter.value().toString();
283 value = QString("'%1'").arg(iter.value().toString());
286 valueStrings << QString("%1=%2").arg(iter.key(), value);
288 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
289 qCritical() << " Error Number:" << query.lastError().number();
290 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
291 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
292 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
300 void AbstractSqlStorage::connectionDestroyed()
302 QMutexLocker locker(&_connectionPoolMutex);
303 _connectionPool.remove(sender()->thread());
307 // ========================================
308 // AbstractSqlStorage::Connection
309 // ========================================
310 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
312 _name(name.toLatin1())
317 AbstractSqlStorage::Connection::~Connection()
320 QSqlDatabase db = QSqlDatabase::database(name(), false);
326 QSqlDatabase::removeDatabase(name());
330 // ========================================
331 // AbstractSqlMigrator
332 // ========================================
333 AbstractSqlMigrator::AbstractSqlMigrator()
339 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
342 _query = new QSqlQuery(db);
343 _query->prepare(query);
347 void AbstractSqlMigrator::resetQuery()
354 bool AbstractSqlMigrator::exec()
358 return !_query->lastError().isValid();
362 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
366 return "QuasselUser";
372 return "IdentityNick";
382 return "UserSetting";
388 QVariantList AbstractSqlMigrator::boundValues()
394 int numValues = _query->boundValues().count();
395 for (int i = 0; i < numValues; i++) {
396 values << _query->boundValue(i);
402 void AbstractSqlMigrator::dumpStatus()
404 qWarning() << " executed Query:";
405 qWarning() << qPrintable(executedQuery());
406 qWarning() << " bound Values:";
407 QList<QVariant> list = boundValues();
408 for (int i = 0; i < list.size(); ++i)
409 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
410 qWarning() << " Error Number:" << lastError().number();
411 qWarning() << " Error Message:" << lastError().text();
415 // ========================================
416 // AbstractSqlMigrationReader
417 // ========================================
418 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
419 : AbstractSqlMigrator(),
425 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
427 if (!transaction()) {
428 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
431 if (!writer->transaction()) {
432 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
433 rollback(); // close the reader transaction;
439 // due to the incompatibility across Migration objects we can't run this in a loop... :/
440 QuasselUserMO quasselUserMo;
441 if (!transferMo(QuasselUser, quasselUserMo))
444 IdentityMO identityMo;
445 if (!transferMo(Identity, identityMo))
448 IdentityNickMO identityNickMo;
449 if (!transferMo(IdentityNick, identityNickMo))
453 if (!transferMo(Network, networkMo))
457 if (!transferMo(Buffer, bufferMo))
461 if (!transferMo(Sender, senderMo))
465 if (!transferMo(Backlog, backlogMo))
468 IrcServerMO ircServerMo;
469 if (!transferMo(IrcServer, ircServerMo))
472 UserSettingMO userSettingMo;
473 if (!transferMo(UserSetting, userSettingMo))
476 if (!_writer->postProcess())
478 return finalizeMigration();
482 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
484 qWarning() << "Migration Failed!";
485 if (!errorMsg.isNull()) {
486 qWarning() << qPrintable(errorMsg);
488 if (lastError().isValid()) {
489 qWarning() << "ReaderError:";
493 if (_writer->lastError().isValid()) {
494 qWarning() << "WriterError:";
495 _writer->dumpStatus();
504 bool AbstractSqlMigrationReader::finalizeMigration()
507 _writer->resetQuery();
510 if (!_writer->commit()) {
520 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
523 _writer->resetQuery();
525 if (!prepareQuery(moType)) {
526 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
529 if (!_writer->prepareQuery(moType)) {
530 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
534 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
537 file.open(stdout, QIODevice::WriteOnly);
540 if (!_writer->writeMo(mo)) {
541 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));