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>
29 int AbstractSqlStorage::_nextConnectionId = 0;
30 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
36 AbstractSqlStorage::~AbstractSqlStorage() {
37 // disconnect the connections, so their deletion is no longer interessting for us
38 QHash<QThread *, Connection *>::iterator conIter;
39 for(conIter = _connectionPool.begin(); conIter != _connectionPool.end(); conIter++) {
40 QSqlDatabase::removeDatabase(conIter.value()->name());
41 disconnect(conIter.value(), 0, this, 0);
45 QSqlDatabase AbstractSqlStorage::logDb() {
46 if(!_connectionPool.contains(QThread::currentThread()))
47 addConnectionToPool();
49 return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
52 void AbstractSqlStorage::addConnectionToPool() {
53 QMutexLocker locker(&_connectionPoolMutex);
54 // we have to recheck if the connection pool already contains a connection for
55 // this thread. Since now (after the lock) we can only tell for sure
56 if(_connectionPool.contains(QThread::currentThread()))
59 QThread *currentThread = QThread::currentThread();
61 int connectionId = _nextConnectionId++;
63 Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
64 connection->moveToThread(currentThread);
65 connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
66 connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
67 connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
68 _connectionPool[currentThread] = connection;
70 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
71 db.setDatabaseName(databaseName());
73 if(!hostName().isEmpty())
74 db.setHostName(hostName());
79 if(!userName().isEmpty()) {
80 db.setUserName(userName());
81 db.setPassword(password());
85 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
86 qWarning() << "-" << db.lastError().text();
90 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
91 setConnectionProperties(settings);
93 QSqlDatabase db = logDb();
94 if(!db.isValid() || !db.isOpen())
97 if(installedSchemaVersion() == -1) {
98 qCritical() << "Storage Schema is missing!";
102 if(installedSchemaVersion() > schemaVersion()) {
103 qCritical() << "Installed Schema is newer then any known Version.";
107 if(installedSchemaVersion() < schemaVersion()) {
108 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
110 qWarning() << qPrintable(tr("Upgrade failed..."));
115 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
119 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
121 version = schemaVersion();
123 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
124 if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
125 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
129 QFile queryFile(queryInfo.filePath());
130 if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
132 QString query = QTextStream(&queryFile).readAll();
135 return query.trimmed();
138 QStringList AbstractSqlStorage::setupQueries() {
140 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
141 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
142 queries << queryString(fileInfo.baseName());
147 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
148 setConnectionProperties(settings);
149 QSqlDatabase db = logDb();
151 qCritical() << "Unable to setup Logging Backend!";
156 foreach(QString queryString, setupQueries()) {
157 QSqlQuery query = db.exec(queryString);
158 if(!watchQuery(query)) {
159 qCritical() << "Unable to setup Logging Backend!";
164 bool success = setupSchemaVersion(schemaVersion());
172 QStringList AbstractSqlStorage::upgradeQueries(int version) {
174 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
175 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
176 queries << queryString(fileInfo.baseName(), version);
181 bool AbstractSqlStorage::upgradeDb() {
182 if(schemaVersion() <= installedSchemaVersion())
185 QSqlDatabase db = logDb();
187 for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
188 foreach(QString queryString, upgradeQueries(ver)) {
189 QSqlQuery query = db.exec(queryString);
190 if(!watchQuery(query)) {
191 qCritical() << "Unable to upgrade Logging Backend!";
196 return updateSchemaVersion(schemaVersion());
200 int AbstractSqlStorage::schemaVersion() {
201 // returns the newest Schema Version!
202 // not the currently used one! (though it can be the same)
203 if(_schemaVersion > 0)
204 return _schemaVersion;
208 QDir dir = QDir(":/SQL/" + displayName());
209 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
210 if(!fileInfo.isDir())
213 version = fileInfo.fileName().toInt(&ok);
217 if(version > _schemaVersion)
218 _schemaVersion = version;
220 return _schemaVersion;
223 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
224 if(query.lastError().isValid()) {
225 qCritical() << "unhandled Error in QSqlQuery!";
226 qCritical() << " last Query:\n" << query.lastQuery();
227 qCritical() << " executed Query:\n" << query.executedQuery();
228 qCritical() << " bound Values:";
229 QList<QVariant> list = query.boundValues().values();
230 for (int i = 0; i < list.size(); ++i)
231 qCritical() << i << ": " << list.at(i).toString().toAscii().data();
232 qCritical() << " Error Number:" << query.lastError().number();
233 qCritical() << " Error Message:" << query.lastError().text();
234 qCritical() << " Driver Message:" << query.lastError().driverText();
235 qCritical() << " DB Message:" << query.lastError().databaseText();
242 void AbstractSqlStorage::connectionDestroyed() {
243 QMutexLocker locker(&_connectionPoolMutex);
244 _connectionPool.remove(sender()->thread());
247 // ========================================
248 // AbstractSqlStorage::Connection
249 // ========================================
250 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
252 _name(name.toLatin1())
256 AbstractSqlStorage::Connection::~Connection() {
258 QSqlDatabase db = QSqlDatabase::database(name(), false);
264 QSqlDatabase::removeDatabase(name());
270 // ========================================
271 // AbstractSqlMigrator
272 // ========================================
273 AbstractSqlMigrator::AbstractSqlMigrator()
278 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
280 _query = new QSqlQuery(db);
281 _query->prepare(query);
284 void AbstractSqlMigrator::resetQuery() {
289 bool AbstractSqlMigrator::exec() {
292 return !_query->lastError().isValid();
295 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
298 return "QuasselUser";
304 return "IdentityNick";
314 return "UserSetting";
319 QVariantList AbstractSqlMigrator::boundValues() {
324 int numValues = _query->boundValues().count();
325 for(int i = 0; i < numValues; i++) {
326 values << _query->boundValue(i);
331 void AbstractSqlMigrator::dumpStatus() {
332 qWarning() << " executed Query:";
333 qWarning() << qPrintable(executedQuery());
334 qWarning() << " bound Values:";
335 QList<QVariant> list = boundValues();
336 for (int i = 0; i < list.size(); ++i)
337 qWarning() << i << ": " << list.at(i).toString().toAscii().data();
338 qWarning() << " Error Number:" << lastError().number();
339 qWarning() << " Error Message:" << lastError().text();
343 // ========================================
344 // AbstractSqlMigrationReader
345 // ========================================
346 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
347 : AbstractSqlMigrator(),
352 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
354 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
357 if(!writer->transaction()) {
358 qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
359 rollback(); // close the reader transaction;
365 // due to the incompatibility across Migration objects we can't run this in a loop... :/
366 QuasselUserMO quasselUserMo;
367 if(!transferMo(QuasselUser, quasselUserMo))
370 IdentityMO identityMo;
371 if(!transferMo(Identity, identityMo))
374 IdentityNickMO identityNickMo;
375 if(!transferMo(IdentityNick, identityNickMo))
379 if(!transferMo(Network, networkMo))
383 if(!transferMo(Buffer, bufferMo))
387 if(!transferMo(Sender, senderMo))
391 if(!transferMo(Backlog, backlogMo))
394 IrcServerMO ircServerMo;
395 if(!transferMo(IrcServer, ircServerMo))
398 UserSettingMO userSettingMo;
399 if(!transferMo(UserSetting, userSettingMo))
402 if(!_writer->postProcess())
404 return finalizeMigration();
407 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
408 qWarning() << "Migration Failed!";
409 if(!errorMsg.isNull()) {
410 qWarning() << qPrintable(errorMsg);
412 if(lastError().isValid()) {
413 qWarning() << "ReaderError:";
418 if(_writer->lastError().isValid()) {
419 qWarning() << "WriterError:";
420 _writer->dumpStatus();
428 bool AbstractSqlMigrationReader::finalizeMigration() {
430 _writer->resetQuery();
433 if(!_writer->commit()) {
442 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
444 _writer->resetQuery();
446 if(!prepareQuery(moType)) {
447 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
450 if(!_writer->prepareQuery(moType)) {
451 abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
455 qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
458 file.open(stdout, QIODevice::WriteOnly);
461 if(!_writer->writeMo(mo)) {
462 abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));