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 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 disconnect(conIter.value(), 0, this, 0);
44 QSqlDatabase AbstractSqlStorage::logDb() {
45 if(!_connectionPool.contains(QThread::currentThread()))
46 addConnectionToPool();
48 return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
51 void AbstractSqlStorage::addConnectionToPool() {
52 QMutexLocker locker(&_connectionPoolMutex);
53 // we have to recheck if the connection pool already contains a connection for
54 // this thread. Since now (after the lock) we can only tell for sure
55 if(_connectionPool.contains(QThread::currentThread()))
58 QThread *currentThread = QThread::currentThread();
60 int connectionId = _nextConnectionId++;
62 Connection *connection = new Connection(QLatin1String(QString("quassel_connection_%1").arg(connectionId).toLatin1()));
63 connection->moveToThread(currentThread);
64 connect(this, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
65 connect(currentThread, SIGNAL(destroyed()), connection, SLOT(deleteLater()));
66 connect(connection, SIGNAL(destroyed()), this, SLOT(connectionDestroyed()));
67 _connectionPool[currentThread] = connection;
69 QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
70 db.setDatabaseName(databaseName());
72 if(!hostName().isEmpty())
73 db.setHostName(hostName());
78 if(!userName().isEmpty()) {
79 db.setUserName(userName());
80 db.setPassword(password());
84 qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
85 qWarning() << "-" << db.lastError().text();
89 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
90 setConnectionProperties(settings);
92 QSqlDatabase db = logDb();
93 if(!db.isValid() || !db.isOpen())
96 if(installedSchemaVersion() == -1) {
97 qCritical() << "Storage Schema is missing!";
101 if(installedSchemaVersion() > schemaVersion()) {
102 qCritical() << "Installed Schema is newer then any known Version.";
106 if(installedSchemaVersion() < schemaVersion()) {
107 qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
109 qWarning() << qPrintable(tr("Upgrade failed..."));
114 quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
118 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
120 version = schemaVersion();
122 QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
123 if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
124 qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
128 QFile queryFile(queryInfo.filePath());
129 if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
131 QString query = QTextStream(&queryFile).readAll();
134 return query.trimmed();
137 QStringList AbstractSqlStorage::setupQueries() {
139 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
140 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
141 queries << queryString(fileInfo.baseName());
146 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
147 setConnectionProperties(settings);
148 QSqlDatabase db = logDb();
150 qCritical() << "Unable to setup Logging Backend!";
155 foreach(QString queryString, setupQueries()) {
156 QSqlQuery query = db.exec(queryString);
157 if(!watchQuery(query)) {
158 qCritical() << "Unable to setup Logging Backend!";
163 bool success = setupSchemaVersion(schemaVersion());
171 QStringList AbstractSqlStorage::upgradeQueries(int version) {
173 QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
174 foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
175 queries << queryString(fileInfo.baseName(), version);
180 bool AbstractSqlStorage::upgradeDb() {
181 if(schemaVersion() <= installedSchemaVersion())
184 QSqlDatabase db = logDb();
186 for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
187 foreach(QString queryString, upgradeQueries(ver)) {
188 QSqlQuery query = db.exec(queryString);
189 if(!watchQuery(query)) {
190 qCritical() << "Unable to upgrade Logging Backend!";
195 return updateSchemaVersion(schemaVersion());
199 int AbstractSqlStorage::schemaVersion() {
200 // returns the newest Schema Version!
201 // not the currently used one! (though it can be the same)
202 if(_schemaVersion > 0)
203 return _schemaVersion;
207 QDir dir = QDir(":/SQL/" + displayName());
208 foreach(QFileInfo fileInfo, dir.entryInfoList()) {
209 if(!fileInfo.isDir())
212 version = fileInfo.fileName().toInt(&ok);
216 if(version > _schemaVersion)
217 _schemaVersion = version;
219 return _schemaVersion;
222 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
223 if(query.lastError().isValid()) {
224 qCritical() << "unhandled Error in QSqlQuery!";
225 qCritical() << " last Query:\n" << query.lastQuery();
226 qCritical() << " executed Query:\n" << query.executedQuery();
227 qCritical() << " bound Values:";
228 QList<QVariant> list = query.boundValues().values();
229 for (int i = 0; i < list.size(); ++i)
230 qCritical() << i << ": " << list.at(i).toString().toAscii().data();
231 qCritical() << " Error Number:" << query.lastError().number();
232 qCritical() << " Error Message:" << query.lastError().text();
233 qCritical() << " Driver Message:" << query.lastError().driverText();
234 qCritical() << " DB Message:" << query.lastError().databaseText();
241 void AbstractSqlStorage::connectionDestroyed() {
242 QMutexLocker locker(&_connectionPoolMutex);
243 _connectionPool.remove(sender()->thread());
246 // ========================================
247 // AbstractSqlStorage::Connection
248 // ========================================
249 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
251 _name(name.toLatin1())
255 AbstractSqlStorage::Connection::~Connection() {
257 QSqlDatabase db = QSqlDatabase::database(name(), false);
263 QSqlDatabase::removeDatabase(name());