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 quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
95 quWarning() << "-" << db.lastError().text();
98 if (!initDbSession(db)) {
99 quWarning() << "Unable to initialize database" << displayName() << "for thread" << QThread::currentThread();
106 Storage::State AbstractSqlStorage::init(const QVariantMap &settings)
108 setConnectionProperties(settings);
110 _debug = Quassel::isOptionSet("debug");
112 QSqlDatabase db = logDb();
113 if (!db.isValid() || !db.isOpen())
116 if (installedSchemaVersion() == -1) {
117 qCritical() << "Storage Schema is missing!";
121 if (installedSchemaVersion() > schemaVersion()) {
122 qCritical() << "Installed Schema is newer then any known Version.";
126 if (installedSchemaVersion() < schemaVersion()) {
127 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
129 qWarning() << qPrintable(tr("Upgrade failed..."));
134 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
139 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
142 version = schemaVersion();
144 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
145 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
146 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
150 QFile queryFile(queryInfo.filePath());
151 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
153 QString query = QTextStream(&queryFile).readAll();
156 return query.trimmed();
160 QStringList AbstractSqlStorage::setupQueries()
163 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
164 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
165 queries << queryString(fileInfo.baseName());
171 bool AbstractSqlStorage::setup(const QVariantMap &settings)
173 setConnectionProperties(settings);
174 QSqlDatabase db = logDb();
176 qCritical() << "Unable to setup Logging Backend!";
181 foreach(QString queryString, setupQueries()) {
182 QSqlQuery query = db.exec(queryString);
183 if (!watchQuery(query)) {
184 qCritical() << "Unable to setup Logging Backend!";
189 bool success = setupSchemaVersion(schemaVersion());
198 QStringList AbstractSqlStorage::upgradeQueries(int version)
201 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
202 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
203 queries << queryString(fileInfo.baseName(), version);
209 bool AbstractSqlStorage::upgradeDb()
211 if (schemaVersion() <= installedSchemaVersion())
214 QSqlDatabase db = logDb();
216 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
217 foreach(QString queryString, upgradeQueries(ver)) {
218 QSqlQuery query = db.exec(queryString);
219 if (!watchQuery(query)) {
220 qCritical() << "Unable to upgrade Logging Backend!";
225 return updateSchemaVersion(schemaVersion());
229 int AbstractSqlStorage::schemaVersion()
231 // returns the newest Schema Version!
232 // not the currently used one! (though it can be the same)
233 if (_schemaVersion > 0)
234 return _schemaVersion;
238 QDir dir = QDir(":/SQL/" + displayName());
239 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
240 if (!fileInfo.isDir())
243 version = fileInfo.fileName().toInt(&ok);
247 if (version > _schemaVersion)
248 _schemaVersion = version;
250 return _schemaVersion;
254 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
256 bool queryError = query.lastError().isValid();
257 if (queryError || _debug) {
259 qCritical() << "unhandled Error in QSqlQuery!";
260 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
261 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
262 QVariantMap boundValues = query.boundValues();
263 QStringList valueStrings;
264 QVariantMap::const_iterator iter;
265 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
268 if (query.driver()) {
269 // let the driver do the formatting
270 field.setType(iter.value().type());
271 if (iter.value().isNull())
274 field.setValue(iter.value());
275 value = query.driver()->formatValue(field);
278 switch (iter.value().type()) {
279 case QVariant::Invalid:
283 value = iter.value().toString();
286 value = QString("'%1'").arg(iter.value().toString());
289 valueStrings << QString("%1=%2").arg(iter.key(), value);
291 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
292 qCritical() << " Error Number:" << query.lastError().number();
293 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
294 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
295 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
303 void AbstractSqlStorage::connectionDestroyed()
305 QMutexLocker locker(&_connectionPoolMutex);
306 _connectionPool.remove(sender()->thread());
310 // ========================================
311 // AbstractSqlStorage::Connection
312 // ========================================
313 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
315 _name(name.toLatin1())
320 AbstractSqlStorage::Connection::~Connection()
323 QSqlDatabase db = QSqlDatabase::database(name(), false);
329 QSqlDatabase::removeDatabase(name());
333 // ========================================
334 // AbstractSqlMigrator
335 // ========================================
336 AbstractSqlMigrator::AbstractSqlMigrator()
342 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
345 _query = new QSqlQuery(db);
346 _query->prepare(query);
350 void AbstractSqlMigrator::resetQuery()
357 bool AbstractSqlMigrator::exec()
361 return !_query->lastError().isValid();
365 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
369 return "QuasselUser";
375 return "IdentityNick";
385 return "UserSetting";
391 QVariantList AbstractSqlMigrator::boundValues()
397 int numValues = _query->boundValues().count();
398 for (int i = 0; i < numValues; i++) {
399 values << _query->boundValue(i);
405 void AbstractSqlMigrator::dumpStatus()
407 qWarning() << " executed Query:";
408 qWarning() << qPrintable(executedQuery());
409 qWarning() << " bound Values:";
410 QList<QVariant> list = boundValues();
411 for (int i = 0; i < list.size(); ++i)
412 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
413 qWarning() << " Error Number:" << lastError().number();
414 qWarning() << " Error Message:" << lastError().text();
418 // ========================================
419 // AbstractSqlMigrationReader
420 // ========================================
421 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
422 : AbstractSqlMigrator(),
428 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
430 if (!transaction()) {
431 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
434 if (!writer->transaction()) {
435 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
436 rollback(); // close the reader transaction;
442 // due to the incompatibility across Migration objects we can't run this in a loop... :/
443 QuasselUserMO quasselUserMo;
444 if (!transferMo(QuasselUser, quasselUserMo))
447 IdentityMO identityMo;
448 if (!transferMo(Identity, identityMo))
451 IdentityNickMO identityNickMo;
452 if (!transferMo(IdentityNick, identityNickMo))
456 if (!transferMo(Network, networkMo))
460 if (!transferMo(Buffer, bufferMo))
464 if (!transferMo(Sender, senderMo))
468 if (!transferMo(Backlog, backlogMo))
471 IrcServerMO ircServerMo;
472 if (!transferMo(IrcServer, ircServerMo))
475 UserSettingMO userSettingMo;
476 if (!transferMo(UserSetting, userSettingMo))
479 if (!_writer->postProcess())
481 return finalizeMigration();
485 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
487 qWarning() << "Migration Failed!";
488 if (!errorMsg.isNull()) {
489 qWarning() << qPrintable(errorMsg);
491 if (lastError().isValid()) {
492 qWarning() << "ReaderError:";
496 if (_writer->lastError().isValid()) {
497 qWarning() << "WriterError:";
498 _writer->dumpStatus();
507 bool AbstractSqlMigrationReader::finalizeMigration()
510 _writer->resetQuery();
513 if (!_writer->commit()) {
523 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
526 _writer->resetQuery();
528 if (!prepareQuery(moType)) {
529 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
532 if (!_writer->prepareQuery(moType)) {
533 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
537 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
540 file.open(stdout, QIODevice::WriteOnly);
543 if (!_writer->writeMo(mo)) {
544 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));