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