1 /***************************************************************************
2 * Copyright (C) 2005-2016 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)
121 setConnectionProperties(settings);
123 _debug = Quassel::isOptionSet("debug");
125 QSqlDatabase db = logDb();
126 if (!db.isValid() || !db.isOpen())
129 if (installedSchemaVersion() == -1) {
130 qCritical() << "Storage Schema is missing!";
134 if (installedSchemaVersion() > schemaVersion()) {
135 qCritical() << "Installed Schema is newer then any known Version.";
139 if (installedSchemaVersion() < schemaVersion()) {
140 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
142 qWarning() << qPrintable(tr("Upgrade failed..."));
147 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
152 QString AbstractSqlStorage::queryString(const QString &queryName, int version)
155 version = schemaVersion();
157 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
158 if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
159 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
163 QFile queryFile(queryInfo.filePath());
164 if (!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
166 QString query = QTextStream(&queryFile).readAll();
169 return query.trimmed();
173 QStringList AbstractSqlStorage::setupQueries()
176 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
177 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
178 queries << queryString(fileInfo.baseName());
184 bool AbstractSqlStorage::setup(const QVariantMap &settings)
186 setConnectionProperties(settings);
187 QSqlDatabase db = logDb();
189 qCritical() << "Unable to setup Logging Backend!";
194 foreach(QString queryString, setupQueries()) {
195 QSqlQuery query = db.exec(queryString);
196 if (!watchQuery(query)) {
197 qCritical() << "Unable to setup Logging Backend!";
202 bool success = setupSchemaVersion(schemaVersion());
211 QStringList AbstractSqlStorage::upgradeQueries(int version)
214 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
215 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
216 queries << queryString(fileInfo.baseName(), version);
222 bool AbstractSqlStorage::upgradeDb()
224 if (schemaVersion() <= installedSchemaVersion())
227 QSqlDatabase db = logDb();
229 for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
230 foreach(QString queryString, upgradeQueries(ver)) {
231 QSqlQuery query = db.exec(queryString);
232 if (!watchQuery(query)) {
233 qCritical() << "Unable to upgrade Logging Backend!";
238 return updateSchemaVersion(schemaVersion());
242 int AbstractSqlStorage::schemaVersion()
244 // returns the newest Schema Version!
245 // not the currently used one! (though it can be the same)
246 if (_schemaVersion > 0)
247 return _schemaVersion;
251 QDir dir = QDir(":/SQL/" + displayName());
252 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
253 if (!fileInfo.isDir())
256 version = fileInfo.fileName().toInt(&ok);
260 if (version > _schemaVersion)
261 _schemaVersion = version;
263 return _schemaVersion;
267 bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
269 bool queryError = query.lastError().isValid();
270 if (queryError || _debug) {
272 qCritical() << "unhandled Error in QSqlQuery!";
273 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
274 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
275 QVariantMap boundValues = query.boundValues();
276 QStringList valueStrings;
277 QVariantMap::const_iterator iter;
278 for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
281 if (query.driver()) {
282 // let the driver do the formatting
283 field.setType(iter.value().type());
284 if (iter.value().isNull())
287 field.setValue(iter.value());
288 value = query.driver()->formatValue(field);
291 switch (iter.value().type()) {
292 case QVariant::Invalid:
296 value = iter.value().toString();
299 value = QString("'%1'").arg(iter.value().toString());
302 valueStrings << QString("%1=%2").arg(iter.key(), value);
304 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
305 qCritical() << " Error Number:" << query.lastError().number();
306 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
307 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
308 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
316 void AbstractSqlStorage::connectionDestroyed()
318 QMutexLocker locker(&_connectionPoolMutex);
319 _connectionPool.remove(sender()->thread());
323 // ========================================
324 // AbstractSqlStorage::Connection
325 // ========================================
326 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
328 _name(name.toLatin1())
333 AbstractSqlStorage::Connection::~Connection()
336 QSqlDatabase db = QSqlDatabase::database(name(), false);
342 QSqlDatabase::removeDatabase(name());
346 // ========================================
347 // AbstractSqlMigrator
348 // ========================================
349 AbstractSqlMigrator::AbstractSqlMigrator()
355 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
358 _query = new QSqlQuery(db);
359 _query->prepare(query);
363 void AbstractSqlMigrator::resetQuery()
370 bool AbstractSqlMigrator::exec()
374 return !_query->lastError().isValid();
378 QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
382 return "QuasselUser";
388 return "IdentityNick";
398 return "UserSetting";
404 QVariantList AbstractSqlMigrator::boundValues()
410 int numValues = _query->boundValues().count();
411 for (int i = 0; i < numValues; i++) {
412 values << _query->boundValue(i);
418 void AbstractSqlMigrator::dumpStatus()
420 qWarning() << " executed Query:";
421 qWarning() << qPrintable(executedQuery());
422 qWarning() << " bound Values:";
423 QList<QVariant> list = boundValues();
424 for (int i = 0; i < list.size(); ++i)
425 qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
426 qWarning() << " Error Number:" << lastError().number();
427 qWarning() << " Error Message:" << lastError().text();
431 // ========================================
432 // AbstractSqlMigrationReader
433 // ========================================
434 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
435 : AbstractSqlMigrator(),
441 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
443 if (!transaction()) {
444 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
447 if (!writer->transaction()) {
448 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
449 rollback(); // close the reader transaction;
455 // due to the incompatibility across Migration objects we can't run this in a loop... :/
456 QuasselUserMO quasselUserMo;
457 if (!transferMo(QuasselUser, quasselUserMo))
460 IdentityMO identityMo;
461 if (!transferMo(Identity, identityMo))
464 IdentityNickMO identityNickMo;
465 if (!transferMo(IdentityNick, identityNickMo))
469 if (!transferMo(Network, networkMo))
473 if (!transferMo(Buffer, bufferMo))
477 if (!transferMo(Sender, senderMo))
481 if (!transferMo(Backlog, backlogMo))
484 IrcServerMO ircServerMo;
485 if (!transferMo(IrcServer, ircServerMo))
488 UserSettingMO userSettingMo;
489 if (!transferMo(UserSetting, userSettingMo))
492 if (!_writer->postProcess())
494 return finalizeMigration();
498 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
500 qWarning() << "Migration Failed!";
501 if (!errorMsg.isNull()) {
502 qWarning() << qPrintable(errorMsg);
504 if (lastError().isValid()) {
505 qWarning() << "ReaderError:";
509 if (_writer->lastError().isValid()) {
510 qWarning() << "WriterError:";
511 _writer->dumpStatus();
520 bool AbstractSqlMigrationReader::finalizeMigration()
523 _writer->resetQuery();
526 if (!_writer->commit()) {
536 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
539 _writer->resetQuery();
541 if (!prepareQuery(moType)) {
542 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
545 if (!_writer->prepareQuery(moType)) {
546 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
550 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
553 file.open(stdout, QIODevice::WriteOnly);
556 if (!_writer->writeMo(mo)) {
557 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));