3d339ec23beea9751c804fff3032b5912c03b612
[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_%1_con_%2").arg(driverName()).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(port() != -1)
76     db.setPort(port());
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 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
90   setConnectionProperties(settings);
91
92   QSqlDatabase db = logDb();
93   if(!db.isValid() || !db.isOpen())
94     return NotAvailable;
95
96   if(installedSchemaVersion() == -1) {
97     qCritical() << "Storage Schema is missing!";
98     return NeedsSetup;
99   }
100
101   if(installedSchemaVersion() > schemaVersion()) {
102     qCritical() << "Installed Schema is newer then any known Version.";
103     return NotAvailable;
104   }
105
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()));
108     if(!upgradeDb()) {
109       qWarning() << qPrintable(tr("Upgrade failed..."));
110       return NotAvailable;
111     }
112   }
113
114   quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
115   return IsReady;
116 }
117
118 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
119   if(version == 0)
120     version = schemaVersion();
121
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();
125     return QString();
126   }
127
128   QFile queryFile(queryInfo.filePath());
129   if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
130     return QString();
131   QString query = QTextStream(&queryFile).readAll();
132   queryFile.close();
133
134   return query.trimmed();
135 }
136
137 QStringList AbstractSqlStorage::setupQueries() {
138   QStringList queries;
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());
142   }
143   return queries;
144 }
145
146 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
147   setConnectionProperties(settings);
148   QSqlDatabase db = logDb();
149   if(!db.isOpen()) {
150     qCritical() << "Unable to setup Logging Backend!";
151     return false;
152   }
153
154   db.transaction();
155   foreach(QString queryString, setupQueries()) {
156     QSqlQuery query = db.exec(queryString);
157     if(!watchQuery(query)) {
158       qCritical() << "Unable to setup Logging Backend!";
159       db.rollback();
160       return false;
161     }
162   }
163   bool success = setupSchemaVersion(schemaVersion());
164   if(success)
165     db.commit();
166   else
167     db.rollback();
168   return success;
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 updateSchemaVersion(schemaVersion());
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, QObject *parent)
250   : QObject(parent),
251     _name(name.toLatin1())
252 {
253 }
254
255 AbstractSqlStorage::Connection::~Connection() {
256   {
257     QSqlDatabase db = QSqlDatabase::database(name(), false);
258     if(db.isOpen()) {
259       db.commit();
260       db.close();
261     }
262   }
263   QSqlDatabase::removeDatabase(name());
264 }
265
266
267
268
269 // ========================================
270 //  AbstractSqlMigrator
271 // ========================================
272 AbstractSqlMigrator::AbstractSqlMigrator()
273   : _query(0)
274 {
275 }
276
277 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
278   Q_ASSERT(!_query);
279   _query = new QSqlQuery(db);
280   _query->prepare(query);
281 }
282
283 void AbstractSqlMigrator::resetQuery() {
284   delete _query;
285   _query = 0;
286 }
287
288 bool AbstractSqlMigrator::exec() {
289   Q_ASSERT(_query);
290   _query->exec();
291   return !_query->lastError().isValid();
292 }
293
294 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
295   switch(moType) {
296   case QuasselUser:
297     return "QuasselUser";
298   case Sender:
299     return "Sender";
300   case Identity:
301     return "Identity";
302   case IdentityNick:
303     return "IdentityNick";
304   case Network:
305     return "Network";
306   case Buffer:
307     return "Buffer";
308   case Backlog:
309     return "Backlog";
310   case IrcServer:
311     return "IrcServer";
312   case UserSetting:
313     return "UserSetting";
314   };
315   return QString();
316 }
317
318 QVariantList AbstractSqlMigrator::boundValues() {
319   QVariantList values;
320   if(!_query)
321     return values;
322
323   int numValues = _query->boundValues().count();
324   for(int i = 0; i < numValues; i++) {
325     values << _query->boundValue(i);
326   }
327   return values;
328 }
329
330 void AbstractSqlMigrator::dumpStatus() {
331   qWarning() << "  executed Query:";
332   qWarning() << qPrintable(executedQuery());
333   qWarning() << "  bound Values:";
334   QList<QVariant> list = boundValues();
335   for (int i = 0; i < list.size(); ++i)
336     qWarning() << i << ": " << list.at(i).toString().toAscii().data();
337   qWarning() << "  Error Number:"   << lastError().number();
338   qWarning() << "  Error Message:"   << lastError().text();
339 }
340
341
342 // ========================================
343 //  AbstractSqlMigrationReader
344 // ========================================
345 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
346   : AbstractSqlMigrator(),
347     _writer(0)
348 {
349 }
350
351 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
352   if(!transaction()) {
353     qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader stransaction!";
354     return false;
355   }
356   if(!writer->transaction()) {
357     qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer stransaction!";
358     rollback(); // close the reader transaction;
359     return false;
360   }
361
362   _writer = writer;
363
364   // due to the incompatibility across Migration objects we can't run this in a loop... :/
365   QuasselUserMO quasselUserMo;
366   if(!transferMo(QuasselUser, quasselUserMo))
367      return false;
368
369   SenderMO senderMo;
370   if(!transferMo(Sender, senderMo))
371     return false;
372
373   IdentityMO identityMo;
374   if(!transferMo(Identity, identityMo))
375     return false;
376
377   IdentityNickMO identityNickMo;
378   if(!transferMo(IdentityNick, identityNickMo))
379     return false;
380
381   NetworkMO networkMo;
382   if(!transferMo(Network, networkMo))
383     return false;
384
385   BufferMO bufferMo;
386   if(!transferMo(Buffer, bufferMo))
387     return false;
388
389   BacklogMO backlogMo;
390   if(!transferMo(Backlog, backlogMo))
391     return false;
392
393   IrcServerMO ircServerMo;
394   if(!transferMo(IrcServer, ircServerMo))
395     return false;
396
397   UserSettingMO userSettingMo;
398   if(!transferMo(UserSetting, userSettingMo))
399     return false;
400
401   return finalizeMigration();
402 }
403
404 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
405   qWarning() << "Migration Failed!";
406   if(!errorMsg.isNull()) {
407     qWarning() << qPrintable(errorMsg);
408   }
409   if(lastError().isValid()) {
410     qWarning() << "ReaderError:";
411     dumpStatus();
412   }
413
414
415   if(_writer->lastError().isValid()) {
416     qWarning() << "WriterError:";
417     _writer->dumpStatus();
418   }
419
420   rollback();
421   _writer->rollback();
422   _writer = 0;
423 }
424
425 bool AbstractSqlMigrationReader::finalizeMigration() {
426   resetQuery();
427   _writer->resetQuery();
428
429   commit();
430   if(!_writer->commit()) {
431     _writer = 0;
432     return false;
433   }
434   _writer = 0;
435   return true;
436 }
437
438 template<typename T>
439 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
440   resetQuery();
441   _writer->resetQuery();
442
443   if(!prepareQuery(moType)) {
444     abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
445     return false;
446   }
447   if(!_writer->prepareQuery(moType)) {
448     abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
449     return false;
450   }
451
452   qDebug() << qPrintable(QString("Transfering %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
453   int i = 0;
454   QFile file;
455   file.open(stdout, QIODevice::WriteOnly);
456   while(readMo(mo)) {
457     if(!_writer->writeMo(mo)) {
458       abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
459       return false;
460     }
461     i++;
462     if(i % 1000 == 0) {
463       file.write("*");
464       file.flush();
465     }
466   }
467   if(i > 1000) {
468     file.write("\n");
469     file.flush();
470   }
471   qDebug() << "Done.";
472   return true;
473 }
474