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"
26 #include <QMutexLocker>
32 int AbstractSqlStorage::_nextConnectionId = 0;
33 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
39 AbstractSqlStorage::~AbstractSqlStorage() {
40 // disconnect the connections, so their deletion is no longer interessting for us
41 QHash<QThread *, Connection *>::iterator conIter;
42 for(conIter = _connectionPool.begin(); conIter != _connectionPool.end(); conIter++) {
43 QSqlDatabase::removeDatabase(conIter.value()->name());
44 disconnect(conIter.value(), 0, this, 0);
48 QSqlDatabase AbstractSqlStorage::logDb() {
49 if(!_connectionPool.contains(QThread::currentThread()))
50 addConnectionToPool();
52 return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
55 void AbstractSqlStorage::addConnectionToPool() {
56 QMutexLocker locker(&_connectionPoolMutex);
57 // we have to recheck if the connection pool already contains a connection for
58 // this thread. Since now (after the lock) we can only tell for sure
59 if(_connectionPool.contains(QThread::currentThread()))
62 QThread *currentThread = QThread::currentThread();
64 int connectionId = _nextConnectionId++;
66 Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
67 connection->moveToThread(currentThread);
68 connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
69 connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
70 connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
71 _connectionPool[currentThread] = connection;
73 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
74 db.setDatabaseName(databaseName());
76 if(!hostName().isEmpty())
77 db.setHostName(hostName());
82 if(!userName().isEmpty()) {
83 db.setUserName(userName());
84 db.setPassword(password());
88 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
89 qWarning() << "-" << db.lastError().text();
95 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
96 setConnectionProperties(settings);
98 _debug = Quassel::isOptionSet("debug");
100 QSqlDatabase db = logDb();
101 if(!db.isValid() || !db.isOpen())
104 if(installedSchemaVersion() == -1) {
105 qCritical() << "Storage Schema is missing!";
109 if(installedSchemaVersion() > schemaVersion()) {
110 qCritical() << "Installed Schema is newer then any known Version.";
114 if(installedSchemaVersion() < schemaVersion()) {
115 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
117 qWarning() << qPrintable(tr("Upgrade failed..."));
122 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
126 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
128 version = schemaVersion();
130 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
131 if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
132 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
136 QFile queryFile(queryInfo.filePath());
137 if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
139 QString query = QTextStream(&queryFile).readAll();
142 return query.trimmed();
145 QStringList AbstractSqlStorage::setupQueries() {
147 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
148 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
149 queries << queryString(fileInfo.baseName());
154 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
155 setConnectionProperties(settings);
156 QSqlDatabase db = logDb();
158 qCritical() << "Unable to setup Logging Backend!";
163 foreach(QString queryString, setupQueries()) {
164 QSqlQuery query = db.exec(queryString);
165 if(!watchQuery(query)) {
166 qCritical() << "Unable to setup Logging Backend!";
171 bool success = setupSchemaVersion(schemaVersion());
179 QStringList AbstractSqlStorage::upgradeQueries(int version) {
181 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
182 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
183 queries << queryString(fileInfo.baseName(), version);
188 bool AbstractSqlStorage::upgradeDb() {
189 if(schemaVersion() <= installedSchemaVersion())
192 QSqlDatabase db = logDb();
194 for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
195 foreach(QString queryString, upgradeQueries(ver)) {
196 QSqlQuery query = db.exec(queryString);
197 if(!watchQuery(query)) {
198 qCritical() << "Unable to upgrade Logging Backend!";
203 return updateSchemaVersion(schemaVersion());
207 int AbstractSqlStorage::schemaVersion() {
208 // returns the newest Schema Version!
209 // not the currently used one! (though it can be the same)
210 if(_schemaVersion > 0)
211 return _schemaVersion;
215 QDir dir = QDir(":/SQL/" + displayName());
216 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
217 if(!fileInfo.isDir())
220 version = fileInfo.fileName().toInt(&ok);
224 if(version > _schemaVersion)
225 _schemaVersion = version;
227 return _schemaVersion;
230 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
231 bool queryError = query.lastError().isValid();
232 if(queryError || _debug) {
234 qCritical() << "unhandled Error in QSqlQuery!";
235 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
236 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
237 QVariantMap boundValues = query.boundValues();
238 QStringList valueStrings;
239 QVariantMap::const_iterator iter;
240 for(iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
244 // let the driver do the formatting
245 field.setType(iter.value().type());
246 if(iter.value().isNull())
249 field.setValue(iter.value());
250 value = query.driver()->formatValue(field);
252 switch(iter.value().type()) {
253 case QVariant::Invalid:
257 value = iter.value().toString();
260 value = QString("'%1'").arg(iter.value().toString());
263 valueStrings << QString("%1=%2").arg(iter.key(), value);
265 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
266 qCritical() << " Error Number:" << query.lastError().number();
267 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
268 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
269 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
276 void AbstractSqlStorage::connectionDestroyed() {
277 QMutexLocker locker(&_connectionPoolMutex);
278 _connectionPool.remove(sender()->thread());
281 // ========================================
282 // AbstractSqlStorage::Connection
283 // ========================================
284 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
286 _name(name.toLatin1())
290 AbstractSqlStorage::Connection::~Connection() {
292 QSqlDatabase db = QSqlDatabase::database(name(), false);
298 QSqlDatabase::removeDatabase(name());
304 // ========================================
305 // AbstractSqlMigrator
306 // ========================================
307 AbstractSqlMigrator::AbstractSqlMigrator()
312 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
314 _query = new QSqlQuery(db);
315 _query->prepare(query);
318 void AbstractSqlMigrator::resetQuery() {
323 bool AbstractSqlMigrator::exec() {
326 return !_query->lastError().isValid();
329 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
332 return "QuasselUser";
338 return "IdentityNick";
348 return "UserSetting";
353 QVariantList AbstractSqlMigrator::boundValues() {
358 int numValues = _query->boundValues().count();
359 for(int i = 0; i < numValues; i++) {
360 values << _query->boundValue(i);
365 void AbstractSqlMigrator::dumpStatus() {
366 qWarning() << " executed Query:";
367 qWarning() << qPrintable(executedQuery());
368 qWarning() << " bound Values:";
369 QList<QVariant> list = boundValues();
370 for (int i = 0; i < list.size(); ++i)
371 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
372 qWarning() << " Error Number:" << lastError().number();
373 qWarning() << " Error Message:" << lastError().text();
377 // ========================================
378 // AbstractSqlMigrationReader
379 // ========================================
380 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
381 : AbstractSqlMigrator(),
386 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
388 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
391 if(!writer->transaction()) {
392 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
393 rollback(); // close the reader transaction;
399 // due to the incompatibility across Migration objects we can't run this in a loop... :/
400 QuasselUserMO quasselUserMo;
401 if(!transferMo(QuasselUser, quasselUserMo))
404 IdentityMO identityMo;
405 if(!transferMo(Identity, identityMo))
408 IdentityNickMO identityNickMo;
409 if(!transferMo(IdentityNick, identityNickMo))
413 if(!transferMo(Network, networkMo))
417 if(!transferMo(Buffer, bufferMo))
421 if(!transferMo(Sender, senderMo))
425 if(!transferMo(Backlog, backlogMo))
428 IrcServerMO ircServerMo;
429 if(!transferMo(IrcServer, ircServerMo))
432 UserSettingMO userSettingMo;
433 if(!transferMo(UserSetting, userSettingMo))
436 if(!_writer->postProcess())
438 return finalizeMigration();
441 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
442 qWarning() << "Migration Failed!";
443 if(!errorMsg.isNull()) {
444 qWarning() << qPrintable(errorMsg);
446 if(lastError().isValid()) {
447 qWarning() << "ReaderError:";
452 if(_writer->lastError().isValid()) {
453 qWarning() << "WriterError:";
454 _writer->dumpStatus();
462 bool AbstractSqlMigrationReader::finalizeMigration() {
464 _writer->resetQuery();
467 if(!_writer->commit()) {
476 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
478 _writer->resetQuery();
480 if(!prepareQuery(moType)) {
481 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
484 if(!_writer->prepareQuery(moType)) {
485 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
489 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
492 file.open(stdout, QIODevice::WriteOnly);
495 if(!_writer->writeMo(mo)) {
496 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));