first version of lockless storage backend (WIP with lots of debug output)
[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   qDebug() << "using logDb" << _connectionPool[QThread::currentThread()]->name() << QThread::currentThread();
49   return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
50 }
51
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()))
57     return;
58
59   QThread *currentThread = QThread::currentThread();
60
61   int connectionId = _nextConnectionId++;
62
63   Connection *connection = new Connection(QLatin1String(QString("quassel_connection_%1").arg(connectionId).toLatin1()), this);
64   qDebug() << "new connection" << connection->name() << currentThread << QLatin1String(QString("quassel_connection_%1").arg(connectionId).toLatin1());
65   connection->moveToThread(currentThread);
66   connect(this, SIGNAL(syncCachedQueries()), connection, SLOT(syncCachedQueries()));
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;
71
72   QSqlDatabase db = QSqlDatabase::addDatabase(driverName(), connection->name());
73   db.setDatabaseName(databaseName());
74
75   if(!hostName().isEmpty())
76     db.setHostName(hostName());
77
78   if(!userName().isEmpty()) {
79     db.setUserName(userName());
80     db.setPassword(password());
81   }
82
83   if(!db.open()) {
84     qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
85     qWarning() << "-" << db.lastError().text();
86   }
87 }
88
89 bool AbstractSqlStorage::init(const QVariantMap &settings) {
90   Q_UNUSED(settings)
91   QSqlDatabase db = logDb();
92   if(!db.isValid() || !db.isOpen())
93     return false;
94
95   if(installedSchemaVersion() == -1) {
96     qCritical() << "Storage Schema is missing!";
97     return false;
98   }
99
100   if(installedSchemaVersion() > schemaVersion()) {
101     qCritical() << "Installed Schema is newer then any known Version.";
102     return false;
103   }
104   
105   if(installedSchemaVersion() < schemaVersion()) {
106     qWarning() << "Installed Schema is not up to date. Upgrading...";
107     if(!upgradeDb())
108       return false;
109   }
110   
111   quInfo() << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
112   return true;
113 }
114
115 void AbstractSqlStorage::sync() {
116   emit syncCachedQueries();
117 }
118
119 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
120   if(version == 0)
121     version = schemaVersion();
122     
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();
126     return QString();
127   }
128
129   QFile queryFile(queryInfo.filePath());
130   if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
131     return QString();
132   QString query = QTextStream(&queryFile).readAll();
133   queryFile.close();
134   
135   return query.trimmed();
136 }
137
138 QSqlQuery &AbstractSqlStorage::cachedQuery(const QString &queryName, int version) {
139   Q_ASSERT(_connectionPool.contains(QThread::currentThread()));
140   qDebug() << "cached query" << queryName << "using" << _connectionPool[QThread::currentThread()]->name() << QThread::currentThread();
141   return _connectionPool[QThread::currentThread()]->cachedQuery(queryName, version);
142 }
143
144 QStringList AbstractSqlStorage::setupQueries() {
145   QStringList queries;
146   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
147   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
148     queries << queryString(fileInfo.baseName());
149   }
150   return queries;
151 }
152
153 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
154   Q_UNUSED(settings)
155   QSqlDatabase db = logDb();
156   if(!db.isOpen()) {
157     qCritical() << "Unable to setup Logging Backend!";
158     return false;
159   }
160
161   foreach(QString queryString, setupQueries()) {
162     QSqlQuery query = db.exec(queryString);
163     if(!watchQuery(query)) {
164       qCritical() << "Unable to setup Logging Backend!";
165       return false;
166     }
167   }
168   return true;
169 }
170
171 QStringList AbstractSqlStorage::upgradeQueries(int version) {
172   QStringList queries;
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);
176   }
177   return queries;
178 }
179
180 bool AbstractSqlStorage::upgradeDb() {
181   if(schemaVersion() <= installedSchemaVersion())
182     return true;
183
184   QSqlDatabase db = logDb();
185
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!";
191         return false;
192       }
193     }
194   }
195   return true;
196 }
197
198
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;
204
205   int version;
206   bool ok;
207   QDir dir = QDir(":/SQL/" + displayName());
208   foreach(QFileInfo fileInfo, dir.entryInfoList()) {
209     if(!fileInfo.isDir())
210       continue;
211
212     version = fileInfo.fileName().toInt(&ok);
213     if(!ok)
214       continue;
215
216     if(version > _schemaVersion)
217       _schemaVersion = version;
218   }
219   return _schemaVersion;
220 }
221
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();
235     
236     return false;
237   }
238   return true;
239 }
240
241 void AbstractSqlStorage::connectionDestroyed() {
242   QMutexLocker locker(&_connectionPoolMutex);
243   _connectionPool.remove(sender()->thread());
244 }
245
246 // ========================================
247 //  AbstractSqlStorage::Connection
248 // ========================================
249 AbstractSqlStorage::Connection::Connection(const QString &name, AbstractSqlStorage *storage, QObject *parent)
250   : QObject(parent),
251     _name(name.toLatin1()),
252     _storageEngine(storage)
253 {
254 }
255
256 AbstractSqlStorage::Connection::~Connection() {
257   QHash<QPair<QString, int>, QSqlQuery *>::iterator iter = _queryCache.begin();
258   while(iter != _queryCache.end()) {
259     delete *iter;
260     iter = _queryCache.erase(iter);
261   }
262   {
263     QSqlDatabase db = QSqlDatabase::database(name(), false);
264     if(db.isOpen()) {
265       db.commit();
266       db.close();
267     }
268   }
269   QSqlDatabase::removeDatabase(name());
270 }
271
272 QSqlQuery &AbstractSqlStorage::Connection::cachedQuery(const QString &queryName, int version) {
273   QPair<QString, int> queryId = qMakePair(queryName, version);
274   if(_queryCache.contains(queryId)) {
275     return *(_queryCache[queryId]);
276   }
277
278   QSqlQuery *query = new QSqlQuery(QSqlDatabase::database(name()));
279   query->prepare(_storageEngine->queryString(queryName, version));
280   _queryCache[queryId] = query;
281   return *query;
282 }
283
284 void AbstractSqlStorage::Connection::syncCachedQueries() {
285   QHash<QPair<QString, int>, QSqlQuery *>::iterator iter = _queryCache.begin();
286   while(iter != _queryCache.end()) {
287     delete *iter;
288     iter = _queryCache.erase(iter);
289   }
290   QSqlDatabase db = QSqlDatabase::database(name(), false);
291   if(db.isOpen())
292     db.commit();
293 }