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();
92 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
93 setConnectionProperties(settings);
95 QSqlDatabase db = logDb();
96 if(!db.isValid() || !db.isOpen())
99 if(installedSchemaVersion() == -1) {
100 qCritical() << "Storage Schema is missing!";
104 if(installedSchemaVersion() > schemaVersion()) {
105 qCritical() << "Installed Schema is newer then any known Version.";
109 if(installedSchemaVersion() < schemaVersion()) {
110 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
112 qWarning() << qPrintable(tr("Upgrade failed..."));
117 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
121 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
123 version = schemaVersion();
125 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
126 if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
127 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
131 QFile queryFile(queryInfo.filePath());
132 if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
134 QString query = QTextStream(&queryFile).readAll();
137 return query.trimmed();
140 QStringList AbstractSqlStorage::setupQueries() {
142 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
143 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
144 queries << queryString(fileInfo.baseName());
149 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
150 setConnectionProperties(settings);
151 QSqlDatabase db = logDb();
153 qCritical() << "Unable to setup Logging Backend!";
158 foreach(QString queryString, setupQueries()) {
159 QSqlQuery query = db.exec(queryString);
160 if(!watchQuery(query)) {
161 qCritical() << "Unable to setup Logging Backend!";
166 bool success = setupSchemaVersion(schemaVersion());
174 QStringList AbstractSqlStorage::upgradeQueries(int version) {
176 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
177 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
178 queries << queryString(fileInfo.baseName(), version);
183 bool AbstractSqlStorage::upgradeDb() {
184 if(schemaVersion() <= installedSchemaVersion())
187 QSqlDatabase db = logDb();
189 for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
190 foreach(QString queryString, upgradeQueries(ver)) {
191 QSqlQuery query = db.exec(queryString);
192 if(!watchQuery(query)) {
193 qCritical() << "Unable to upgrade Logging Backend!";
198 return updateSchemaVersion(schemaVersion());
202 int AbstractSqlStorage::schemaVersion() {
203 // returns the newest Schema Version!
204 // not the currently used one! (though it can be the same)
205 if(_schemaVersion > 0)
206 return _schemaVersion;
210 QDir dir = QDir(":/SQL/" + displayName());
211 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
212 if(!fileInfo.isDir())
215 version = fileInfo.fileName().toInt(&ok);
219 if(version > _schemaVersion)
220 _schemaVersion = version;
222 return _schemaVersion;
225 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
226 if(query.lastError().isValid()) {
227 qCritical() << "unhandled Error in QSqlQuery!";
228 qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
229 qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
230 QVariantMap boundValues = query.boundValues();
231 QStringList valueStrings;
232 QVariantMap::const_iterator iter;
233 for(iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
237 // let the driver do the formatting
238 field.setType(iter.value().type());
239 if(iter.value().isNull())
242 field.setValue(iter.value());
243 value = query.driver()->formatValue(field);
245 switch(iter.value().type()) {
246 case QVariant::Invalid:
250 value = iter.value().toString();
253 value = QString("'%1'").arg(iter.value().toString());
256 valueStrings << QString("%1=%2").arg(iter.key(), value);
258 qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
259 qCritical() << " Error Number:" << query.lastError().number();
260 qCritical() << " Error Message:" << qPrintable(query.lastError().text());
261 qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
262 qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
269 void AbstractSqlStorage::connectionDestroyed() {
270 QMutexLocker locker(&_connectionPoolMutex);
271 _connectionPool.remove(sender()->thread());
274 // ========================================
275 // AbstractSqlStorage::Connection
276 // ========================================
277 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
279 _name(name.toLatin1())
283 AbstractSqlStorage::Connection::~Connection() {
285 QSqlDatabase db = QSqlDatabase::database(name(), false);
291 QSqlDatabase::removeDatabase(name());
297 // ========================================
298 // AbstractSqlMigrator
299 // ========================================
300 AbstractSqlMigrator::AbstractSqlMigrator()
305 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
307 _query = new QSqlQuery(db);
308 _query->prepare(query);
311 void AbstractSqlMigrator::resetQuery() {
316 bool AbstractSqlMigrator::exec() {
319 return !_query->lastError().isValid();
322 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
325 return "QuasselUser";
331 return "IdentityNick";
341 return "UserSetting";
346 QVariantList AbstractSqlMigrator::boundValues() {
351 int numValues = _query->boundValues().count();
352 for(int i = 0; i < numValues; i++) {
353 values << _query->boundValue(i);
358 void AbstractSqlMigrator::dumpStatus() {
359 qWarning() << " executed Query:";
360 qWarning() << qPrintable(executedQuery());
361 qWarning() << " bound Values:";
362 QList<QVariant> list = boundValues();
363 for (int i = 0; i < list.size(); ++i)
364 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
365 qWarning() << " Error Number:" << lastError().number();
366 qWarning() << " Error Message:" << lastError().text();
370 // ========================================
371 // AbstractSqlMigrationReader
372 // ========================================
373 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
374 : AbstractSqlMigrator(),
379 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
381 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
384 if(!writer->transaction()) {
385 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
386 rollback(); // close the reader transaction;
392 // due to the incompatibility across Migration objects we can't run this in a loop... :/
393 QuasselUserMO quasselUserMo;
394 if(!transferMo(QuasselUser, quasselUserMo))
397 IdentityMO identityMo;
398 if(!transferMo(Identity, identityMo))
401 IdentityNickMO identityNickMo;
402 if(!transferMo(IdentityNick, identityNickMo))
406 if(!transferMo(Network, networkMo))
410 if(!transferMo(Buffer, bufferMo))
414 if(!transferMo(Sender, senderMo))
418 if(!transferMo(Backlog, backlogMo))
421 IrcServerMO ircServerMo;
422 if(!transferMo(IrcServer, ircServerMo))
425 UserSettingMO userSettingMo;
426 if(!transferMo(UserSetting, userSettingMo))
429 if(!_writer->postProcess())
431 return finalizeMigration();
434 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
435 qWarning() << "Migration Failed!";
436 if(!errorMsg.isNull()) {
437 qWarning() << qPrintable(errorMsg);
439 if(lastError().isValid()) {
440 qWarning() << "ReaderError:";
445 if(_writer->lastError().isValid()) {
446 qWarning() << "WriterError:";
447 _writer->dumpStatus();
455 bool AbstractSqlMigrationReader::finalizeMigration() {
457 _writer->resetQuery();
460 if(!_writer->commit()) {
469 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
471 _writer->resetQuery();
473 if(!prepareQuery(moType)) {
474 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
477 if(!_writer->prepareQuery(moType)) {
478 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
482 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
485 file.open(stdout, QIODevice::WriteOnly);
488 if(!_writer->writeMo(mo)) {
489 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));