adding new backlog requesters
[quassel.git] / src / core / abstractsqlstorage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by the Quassel IRC Team                         *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "abstractsqlstorage.h"
22
23 #include "logger.h"
24
25 #include <QMutexLocker>
26 #include <QSqlError>
27 #include <QSqlQuery>
28
29 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
30   : Storage(parent),
31     _schemaVersion(0),
32     _nextConnectionId(0)
33 {
34 }
35
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);
41   }
42 }
43
44 QSqlDatabase AbstractSqlStorage::logDb() {
45   if(!_connectionPool.contains(QThread::currentThread()))
46     addConnectionToPool();
47
48   return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
49 }
50
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()))
56     return;
57
58   QThread *currentThread = QThread::currentThread();
59
60   int connectionId = _nextConnectionId++;
61
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;
68
69   QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
70   db.setDatabaseName(databaseName());
71
72   if(!hostName().isEmpty())
73     db.setHostName(hostName());
74
75   if(!userName().isEmpty()) {
76     db.setUserName(userName());
77     db.setPassword(password());
78   }
79
80   if(!db.open()) {
81     qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
82     qWarning() << "-" << db.lastError().text();
83   }
84 }
85
86 bool AbstractSqlStorage::init(const QVariantMap &settings) {
87   Q_UNUSED(settings)
88   QSqlDatabase db = logDb();
89   if(!db.isValid() || !db.isOpen())
90     return false;
91
92   if(installedSchemaVersion() == -1) {
93     qCritical() << "Storage Schema is missing!";
94     return false;
95   }
96
97   if(installedSchemaVersion() > schemaVersion()) {
98     qCritical() << "Installed Schema is newer then any known Version.";
99     return false;
100   }
101   
102   if(installedSchemaVersion() < schemaVersion()) {
103     qWarning() << "Installed Schema is not up to date. Upgrading...";
104     if(!upgradeDb())
105       return false;
106   }
107   
108   quInfo() << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
109   return true;
110 }
111
112 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
113   if(version == 0)
114     version = schemaVersion();
115     
116   QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
117   if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
118     qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
119     return QString();
120   }
121
122   QFile queryFile(queryInfo.filePath());
123   if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
124     return QString();
125   QString query = QTextStream(&queryFile).readAll();
126   queryFile.close();
127   
128   return query.trimmed();
129 }
130
131 QStringList AbstractSqlStorage::setupQueries() {
132   QStringList queries;
133   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
134   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
135     queries << queryString(fileInfo.baseName());
136   }
137   return queries;
138 }
139
140 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
141   Q_UNUSED(settings)
142   QSqlDatabase db = logDb();
143   if(!db.isOpen()) {
144     qCritical() << "Unable to setup Logging Backend!";
145     return false;
146   }
147
148   foreach(QString queryString, setupQueries()) {
149     QSqlQuery query = db.exec(queryString);
150     if(!watchQuery(query)) {
151       qCritical() << "Unable to setup Logging Backend!";
152       return false;
153     }
154   }
155   return true;
156 }
157
158 QStringList AbstractSqlStorage::upgradeQueries(int version) {
159   QStringList queries;
160   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
161   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
162     queries << queryString(fileInfo.baseName(), version);
163   }
164   return queries;
165 }
166
167 bool AbstractSqlStorage::upgradeDb() {
168   if(schemaVersion() <= installedSchemaVersion())
169     return true;
170
171   QSqlDatabase db = logDb();
172
173   for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
174     foreach(QString queryString, upgradeQueries(ver)) {
175       QSqlQuery query = db.exec(queryString);
176       if(!watchQuery(query)) {
177         qCritical() << "Unable to upgrade Logging Backend!";
178         return false;
179       }
180     }
181   }
182   return true;
183 }
184
185
186 int AbstractSqlStorage::schemaVersion() {
187   // returns the newest Schema Version!
188   // not the currently used one! (though it can be the same)
189   if(_schemaVersion > 0)
190     return _schemaVersion;
191
192   int version;
193   bool ok;
194   QDir dir = QDir(":/SQL/" + displayName());
195   foreach(QFileInfo fileInfo, dir.entryInfoList()) {
196     if(!fileInfo.isDir())
197       continue;
198
199     version = fileInfo.fileName().toInt(&ok);
200     if(!ok)
201       continue;
202
203     if(version > _schemaVersion)
204       _schemaVersion = version;
205   }
206   return _schemaVersion;
207 }
208
209 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
210   if(query.lastError().isValid()) {
211     qCritical() << "unhandled Error in QSqlQuery!";
212     qCritical() << "                  last Query:\n" << query.lastQuery();
213     qCritical() << "              executed Query:\n" << query.executedQuery();
214     qCritical() << "                bound Values:";
215     QList<QVariant> list = query.boundValues().values();
216     for (int i = 0; i < list.size(); ++i)
217       qCritical() << i << ": " << list.at(i).toString().toAscii().data();
218     qCritical() << "                Error Number:"   << query.lastError().number();
219     qCritical() << "               Error Message:"   << query.lastError().text();
220     qCritical() << "              Driver Message:"   << query.lastError().driverText();
221     qCritical() << "                  DB Message:"   << query.lastError().databaseText();
222     
223     return false;
224   }
225   return true;
226 }
227
228 void AbstractSqlStorage::connectionDestroyed() {
229   QMutexLocker locker(&_connectionPoolMutex);
230   _connectionPool.remove(sender()->thread());
231 }
232
233 // ========================================
234 //  AbstractSqlStorage::Connection
235 // ========================================
236 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
237   : QObject(parent),
238     _name(name.toLatin1())
239 {
240 }
241
242 AbstractSqlStorage::Connection::~Connection() {
243   {
244     QSqlDatabase db = QSqlDatabase::database(name(), false);
245     if(db.isOpen()) {
246       db.commit();
247       db.close();
248     }
249   }
250   QSqlDatabase::removeDatabase(name());
251 }