1 /***************************************************************************
2 * Copyright (C) 2005-07 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include "abstractsqlstorage.h"
25 #include <QMutexLocker>
31 int AbstractSqlStorage::_nextConnectionId = 0;
32 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
38 AbstractSqlStorage::~AbstractSqlStorage() {
39 // disconnect the connections, so their deletion is no longer interessting for us
40 QHash<QThread *, Connection *>::iterator conIter;
41 for(conIter = _connectionPool.begin(); conIter != _connectionPool.end(); conIter++) {
42 QSqlDatabase::removeDatabase(conIter.value()->name());
43 disconnect(conIter.value(), 0, this, 0);
47 QSqlDatabase AbstractSqlStorage::logDb() {
48 if(!_connectionPool.contains(QThread::currentThread()))
49 addConnectionToPool();
51 return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
54 void AbstractSqlStorage::addConnectionToPool() {
55 QMutexLocker locker(&_connectionPoolMutex);
56 // we have to recheck if the connection pool already contains a connection for
57 // this thread. Since now (after the lock) we can only tell for sure
58 if(_connectionPool.contains(QThread::currentThread()))
61 QThread *currentThread = QThread::currentThread();
63 int connectionId = _nextConnectionId++;
65 Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
66 connection->moveToThread(currentThread);
67 connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
68 connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
69 connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
70 _connectionPool[currentThread] = connection;
72 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
73 db.setDatabaseName(databaseName());
75 if(!hostName().isEmpty())
76 db.setHostName(hostName());
81 if(!userName().isEmpty()) {
82 db.setUserName(userName());
83 db.setPassword(password());
87 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
88 qWarning() << "-" << db.lastError().text();
94 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
95 setConnectionProperties(settings);
97 QSqlDatabase db = logDb();
98 if(!db.isValid() || !db.isOpen())
101 if(installedSchemaVersion() == -1) {
102 qCritical() << "Storage Schema is missing!";
106 if(installedSchemaVersion() > schemaVersion()) {
107 qCritical() << "Installed Schema is newer then any known Version.";
111 if(installedSchemaVersion() < schemaVersion()) {
112 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
114 qWarning() << qPrintable(tr("Upgrade failed..."));
119 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
123 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
125 version = schemaVersion();
127 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
128 if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
129 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
133 QFile queryFile(queryInfo.filePath());
134 if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
136 QString query = QTextStream(&queryFile).readAll();
139 return query.trimmed();
142 QStringList AbstractSqlStorage::setupQueries() {
144 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
145 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
146 queries << queryString(fileInfo.baseName());
151 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
152 setConnectionProperties(settings);
153 QSqlDatabase db = logDb();
155 qCritical() << "Unable to setup Logging Backend!";
160 foreach(QString queryString, setupQueries()) {
161 QSqlQuery query = db.exec(queryString);
162 if(!watchQuery(query)) {
163 qCritical() << "Unable to setup Logging Backend!";
168 bool success = setupSchemaVersion(schemaVersion());
176 QStringList AbstractSqlStorage::upgradeQueries(int version) {
178 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
179 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
180 queries << queryString(fileInfo.baseName(), version);
185 bool AbstractSqlStorage::upgradeDb() {
186 if(schemaVersion() <= installedSchemaVersion())
189 QSqlDatabase db = logDb();
191 for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
192 foreach(QString queryString, upgradeQueries(ver)) {
193 QSqlQuery query = db.exec(queryString);
194 if(!watchQuery(query)) {
195 qCritical() << "Unable to upgrade Logging Backend!";
200 return updateSchemaVersion(schemaVersion());
204 int AbstractSqlStorage::schemaVersion() {
205 // returns the newest Schema Version!
206 // not the currently used one! (though it can be the same)
207 if(_schemaVersion > 0)
208 return _schemaVersion;
212 QDir dir = QDir(":/SQL/" + displayName());
213 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
214 if(!fileInfo.isDir())
217 version = fileInfo.fileName().toInt(&ok);
221 if(version > _schemaVersion)
222 _schemaVersion = version;
224 return _schemaVersion;
227 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
228 if(query.lastError().isValid()) {
229 qCritical() << "unhandled Error in QSqlQuery!";
230 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
231 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
232 QVariantMap boundValues = query.boundValues();
233 QStringList valueStrings;
234 QVariantMap::const_iterator iter;
235 for(iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
239 // let the driver do the formatting
240 field.setType(iter.value().type());
241 if(iter.value().isNull())
244 field.setValue(iter.value());
245 value = query.driver()->formatValue(field);
247 switch(iter.value().type()) {
248 case QVariant::Invalid:
252 value = iter.value().toString();
255 value = QString("'%1'").arg(iter.value().toString());
258 valueStrings << QString("%1=%2").arg(iter.key(), value);
260 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
261 qCritical() << " Error Number:" << query.lastError().number();
262 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
263 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
264 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
271 void AbstractSqlStorage::connectionDestroyed() {
272 QMutexLocker locker(&_connectionPoolMutex);
273 _connectionPool.remove(sender()->thread());
276 // ========================================
277 // AbstractSqlStorage::Connection
278 // ========================================
279 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
281 _name(name.toLatin1())
285 AbstractSqlStorage::Connection::~Connection() {
287 QSqlDatabase db = QSqlDatabase::database(name(), false);
293 QSqlDatabase::removeDatabase(name());
299 // ========================================
300 // AbstractSqlMigrator
301 // ========================================
302 AbstractSqlMigrator::AbstractSqlMigrator()
307 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
309 _query = new QSqlQuery(db);
310 _query->prepare(query);
313 void AbstractSqlMigrator::resetQuery() {
318 bool AbstractSqlMigrator::exec() {
321 return !_query->lastError().isValid();
324 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
327 return "QuasselUser";
333 return "IdentityNick";
343 return "UserSetting";
348 QVariantList AbstractSqlMigrator::boundValues() {
353 int numValues = _query->boundValues().count();
354 for(int i = 0; i < numValues; i++) {
355 values << _query->boundValue(i);
360 void AbstractSqlMigrator::dumpStatus() {
361 qWarning() << " executed Query:";
362 qWarning() << qPrintable(executedQuery());
363 qWarning() << " bound Values:";
364 QList<QVariant> list = boundValues();
365 for (int i = 0; i < list.size(); ++i)
366 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
367 qWarning() << " Error Number:" << lastError().number();
368 qWarning() << " Error Message:" << lastError().text();
372 // ========================================
373 // AbstractSqlMigrationReader
374 // ========================================
375 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
376 : AbstractSqlMigrator(),
381 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
383 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
386 if(!writer->transaction()) {
387 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
388 rollback(); // close the reader transaction;
394 // due to the incompatibility across Migration objects we can't run this in a loop... :/
395 QuasselUserMO quasselUserMo;
396 if(!transferMo(QuasselUser, quasselUserMo))
399 IdentityMO identityMo;
400 if(!transferMo(Identity, identityMo))
403 IdentityNickMO identityNickMo;
404 if(!transferMo(IdentityNick, identityNickMo))
408 if(!transferMo(Network, networkMo))
412 if(!transferMo(Buffer, bufferMo))
416 if(!transferMo(Sender, senderMo))
420 if(!transferMo(Backlog, backlogMo))
423 IrcServerMO ircServerMo;
424 if(!transferMo(IrcServer, ircServerMo))
427 UserSettingMO userSettingMo;
428 if(!transferMo(UserSetting, userSettingMo))
431 if(!_writer->postProcess())
433 return finalizeMigration();
436 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
437 qWarning() << "Migration Failed!";
438 if(!errorMsg.isNull()) {
439 qWarning() << qPrintable(errorMsg);
441 if(lastError().isValid()) {
442 qWarning() << "ReaderError:";
447 if(_writer->lastError().isValid()) {
448 qWarning() << "WriterError:";
449 _writer->dumpStatus();
457 bool AbstractSqlMigrationReader::finalizeMigration() {
459 _writer->resetQuery();
462 if(!_writer->commit()) {
471 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
473 _writer->resetQuery();
475 if(!prepareQuery(moType)) {
476 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
479 if(!_writer->prepareQuery(moType)) {
480 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
484 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
487 file.open(stdout, QIODevice::WriteOnly);
490 if(!_writer->writeMo(mo)) {
491 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));