The BufferSyncer cache is now purged when an unknown bufferId is encountered.
[quassel.git] / src / core / abstractsqlstorage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by the Quassel Project                          *
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 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
87   Q_UNUSED(settings)
88
89   QSqlDatabase db = logDb();
90   if(!db.isValid() || !db.isOpen())
91     return NotAvailable;
92
93   if(installedSchemaVersion() == -1) {
94     qCritical() << "Storage Schema is missing!";
95     return NeedsSetup;
96   }
97
98   if(installedSchemaVersion() > schemaVersion()) {
99     qCritical() << "Installed Schema is newer then any known Version.";
100     return NotAvailable;
101   }
102
103   if(installedSchemaVersion() < schemaVersion()) {
104     qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
105     if(!upgradeDb()) {
106       qWarning() << qPrintable(tr("Upgrade failed..."));
107       return NotAvailable;
108     }
109   }
110
111   quInfo() << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
112   return IsReady;
113 }
114
115 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
116   if(version == 0)
117     version = schemaVersion();
118
119   QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
120   if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
121     qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
122     return QString();
123   }
124
125   QFile queryFile(queryInfo.filePath());
126   if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
127     return QString();
128   QString query = QTextStream(&queryFile).readAll();
129   queryFile.close();
130
131   return query.trimmed();
132 }
133
134 QStringList AbstractSqlStorage::setupQueries() {
135   QStringList queries;
136   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
137   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
138     queries << queryString(fileInfo.baseName());
139   }
140   return queries;
141 }
142
143 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
144   Q_UNUSED(settings)
145   QSqlDatabase db = logDb();
146   if(!db.isOpen()) {
147     qCritical() << "Unable to setup Logging Backend!";
148     return false;
149   }
150
151   foreach(QString queryString, setupQueries()) {
152     QSqlQuery query = db.exec(queryString);
153     if(!watchQuery(query)) {
154       qCritical() << "Unable to setup Logging Backend!";
155       return false;
156     }
157   }
158   return setupSchemaVersion(schemaVersion());
159 }
160
161 QStringList AbstractSqlStorage::upgradeQueries(int version) {
162   QStringList queries;
163   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
164   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
165     queries << queryString(fileInfo.baseName(), version);
166   }
167   return queries;
168 }
169
170 bool AbstractSqlStorage::upgradeDb() {
171   if(schemaVersion() <= installedSchemaVersion())
172     return true;
173
174   QSqlDatabase db = logDb();
175
176   for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
177     foreach(QString queryString, upgradeQueries(ver)) {
178       QSqlQuery query = db.exec(queryString);
179       if(!watchQuery(query)) {
180         qCritical() << "Unable to upgrade Logging Backend!";
181         return false;
182       }
183     }
184   }
185   return updateSchemaVersion(schemaVersion());
186 }
187
188
189 int AbstractSqlStorage::schemaVersion() {
190   // returns the newest Schema Version!
191   // not the currently used one! (though it can be the same)
192   if(_schemaVersion > 0)
193     return _schemaVersion;
194
195   int version;
196   bool ok;
197   QDir dir = QDir(":/SQL/" + displayName());
198   foreach(QFileInfo fileInfo, dir.entryInfoList()) {
199     if(!fileInfo.isDir())
200       continue;
201
202     version = fileInfo.fileName().toInt(&ok);
203     if(!ok)
204       continue;
205
206     if(version > _schemaVersion)
207       _schemaVersion = version;
208   }
209   return _schemaVersion;
210 }
211
212 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
213   if(query.lastError().isValid()) {
214     qCritical() << "unhandled Error in QSqlQuery!";
215     qCritical() << "                  last Query:\n" << query.lastQuery();
216     qCritical() << "              executed Query:\n" << query.executedQuery();
217     qCritical() << "                bound Values:";
218     QList<QVariant> list = query.boundValues().values();
219     for (int i = 0; i < list.size(); ++i)
220       qCritical() << i << ": " << list.at(i).toString().toAscii().data();
221     qCritical() << "                Error Number:"   << query.lastError().number();
222     qCritical() << "               Error Message:"   << query.lastError().text();
223     qCritical() << "              Driver Message:"   << query.lastError().driverText();
224     qCritical() << "                  DB Message:"   << query.lastError().databaseText();
225
226     return false;
227   }
228   return true;
229 }
230
231 void AbstractSqlStorage::connectionDestroyed() {
232   QMutexLocker locker(&_connectionPoolMutex);
233   _connectionPool.remove(sender()->thread());
234 }
235
236 // ========================================
237 //  AbstractSqlStorage::Connection
238 // ========================================
239 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
240   : QObject(parent),
241     _name(name.toLatin1())
242 {
243 }
244
245 AbstractSqlStorage::Connection::~Connection() {
246   {
247     QSqlDatabase db = QSqlDatabase::database(name(), false);
248     if(db.isOpen()) {
249       db.commit();
250       db.close();
251     }
252   }
253   QSqlDatabase::removeDatabase(name());
254 }