added missing macros
[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 <QSqlDriver>
27 #include <QSqlError>
28 #include <QSqlField>
29 #include <QSqlQuery>
30
31 int AbstractSqlStorage::_nextConnectionId = 0;
32 AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
33   : Storage(parent),
34     _schemaVersion(0)
35 {
36 }
37
38 AbstractSqlStorage::~AbstractSqlStorage() {
39   // disconnect the connections, so their deletion is no longer interessting for us
40   QHash<QThread *, Connection *>::iterator conIter;
41   for(conIter = _connectionPool.begin(); conIter != _connectionPool.end(); conIter++) {
42     QSqlDatabase::removeDatabase(conIter.value()->name());
43     disconnect(conIter.value(), 0, this, 0);
44   }
45 }
46
47 QSqlDatabase AbstractSqlStorage::logDb() {
48   if(!_connectionPool.contains(QThread::currentThread()))
49     addConnectionToPool();
50
51   return QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name());
52 }
53
54 void AbstractSqlStorage::addConnectionToPool() {
55   QMutexLocker locker(&_connectionPoolMutex);
56   // we have to recheck if the connection pool already contains a connection for
57   // this thread. Since now (after the lock) we can only tell for sure
58   if(_connectionPool.contains(QThread::currentThread()))
59     return;
60
61   QThread *currentThread = QThread::currentThread();
62
63   int connectionId = _nextConnectionId++;
64
65   Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
66   connection->moveToThread(currentThread);
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(port() != -1)
79     db.setPort(port());
80
81   if(!userName().isEmpty()) {
82     db.setUserName(userName());
83     db.setPassword(password());
84   }
85
86   if(!db.open()) {
87     qWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
88     qWarning() << "-" << db.lastError().text();
89   } else {
90     initDbSession(db);
91   }
92 }
93
94 Storage::State AbstractSqlStorage::init(const QVariantMap &settings) {
95   setConnectionProperties(settings);
96
97   QSqlDatabase db = logDb();
98   if(!db.isValid() || !db.isOpen())
99     return NotAvailable;
100
101   if(installedSchemaVersion() == -1) {
102     qCritical() << "Storage Schema is missing!";
103     return NeedsSetup;
104   }
105
106   if(installedSchemaVersion() > schemaVersion()) {
107     qCritical() << "Installed Schema is newer then any known Version.";
108     return NotAvailable;
109   }
110
111   if(installedSchemaVersion() < schemaVersion()) {
112     qWarning() << qPrintable(tr("Installed Schema (version %1) is not up to date. Upgrading to version %2...").arg(installedSchemaVersion()).arg(schemaVersion()));
113     if(!upgradeDb()) {
114       qWarning() << qPrintable(tr("Upgrade failed..."));
115       return NotAvailable;
116     }
117   }
118
119   quInfo() << qPrintable(displayName()) << "Storage Backend is ready. Quassel Schema Version:" << installedSchemaVersion();
120   return IsReady;
121 }
122
123 QString AbstractSqlStorage::queryString(const QString &queryName, int version) {
124   if(version == 0)
125     version = schemaVersion();
126
127   QFileInfo queryInfo(QString(":/SQL/%1/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
128   if(!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
129     qCritical() << "Unable to read SQL-Query" << queryName << "for engine" << displayName();
130     return QString();
131   }
132
133   QFile queryFile(queryInfo.filePath());
134   if(!queryFile.open(QIODevice::ReadOnly | QIODevice::Text))
135     return QString();
136   QString query = QTextStream(&queryFile).readAll();
137   queryFile.close();
138
139   return query.trimmed();
140 }
141
142 QStringList AbstractSqlStorage::setupQueries() {
143   QStringList queries;
144   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(schemaVersion()));
145   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
146     queries << queryString(fileInfo.baseName());
147   }
148   return queries;
149 }
150
151 bool AbstractSqlStorage::setup(const QVariantMap &settings) {
152   setConnectionProperties(settings);
153   QSqlDatabase db = logDb();
154   if(!db.isOpen()) {
155     qCritical() << "Unable to setup Logging Backend!";
156     return false;
157   }
158
159   db.transaction();
160   foreach(QString queryString, setupQueries()) {
161     QSqlQuery query = db.exec(queryString);
162     if(!watchQuery(query)) {
163       qCritical() << "Unable to setup Logging Backend!";
164       db.rollback();
165       return false;
166     }
167   }
168   bool success = setupSchemaVersion(schemaVersion());
169   if(success)
170     db.commit();
171   else
172     db.rollback();
173   return success;
174 }
175
176 QStringList AbstractSqlStorage::upgradeQueries(int version) {
177   QStringList queries;
178   QDir dir = QDir(QString(":/SQL/%1/%2/").arg(displayName()).arg(version));
179   foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
180     queries << queryString(fileInfo.baseName(), version);
181   }
182   return queries;
183 }
184
185 bool AbstractSqlStorage::upgradeDb() {
186   if(schemaVersion() <= installedSchemaVersion())
187     return true;
188
189   QSqlDatabase db = logDb();
190
191   for(int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
192     foreach(QString queryString, upgradeQueries(ver)) {
193       QSqlQuery query = db.exec(queryString);
194       if(!watchQuery(query)) {
195         qCritical() << "Unable to upgrade Logging Backend!";
196         return false;
197       }
198     }
199   }
200   return updateSchemaVersion(schemaVersion());
201 }
202
203
204 int AbstractSqlStorage::schemaVersion() {
205   // returns the newest Schema Version!
206   // not the currently used one! (though it can be the same)
207   if(_schemaVersion > 0)
208     return _schemaVersion;
209
210   int version;
211   bool ok;
212   QDir dir = QDir(":/SQL/" + displayName());
213   foreach(QFileInfo fileInfo, dir.entryInfoList()) {
214     if(!fileInfo.isDir())
215       continue;
216
217     version = fileInfo.fileName().toInt(&ok);
218     if(!ok)
219       continue;
220
221     if(version > _schemaVersion)
222       _schemaVersion = version;
223   }
224   return _schemaVersion;
225 }
226
227 bool AbstractSqlStorage::watchQuery(QSqlQuery &query) {
228   if(query.lastError().isValid()) {
229     qCritical() << "unhandled Error in QSqlQuery!";
230     qCritical() << "                  last Query:\n" << qPrintable(query.lastQuery());
231     qCritical() << "              executed Query:\n" << qPrintable(query.executedQuery());
232     QVariantMap boundValues = query.boundValues();
233     QStringList valueStrings;
234     QVariantMap::const_iterator iter;
235     for(iter = boundValues.constBegin(); iter != boundValues.constEnd(); iter++) {
236       QString value;
237       QSqlField field;
238       if(query.driver()) {
239         // let the driver do the formatting
240         field.setType(iter.value().type());
241         if(iter.value().isNull())
242           field.clear();
243         else
244           field.setValue(iter.value());
245         value =  query.driver()->formatValue(field);
246       } else {
247         switch(iter.value().type()) {
248         case QVariant::Invalid:
249           value = "NULL";
250           break;
251         case QVariant::Int:
252           value = iter.value().toString();
253           break;
254         default:
255           value = QString("'%1'").arg(iter.value().toString());
256         }
257       }
258       valueStrings << QString("%1=%2").arg(iter.key(), value);
259     }
260     qCritical() << "                bound Values:" << qPrintable(valueStrings.join(", "));
261     qCritical() << "                Error Number:" << query.lastError().number();
262     qCritical() << "               Error Message:" << qPrintable(query.lastError().text());
263     qCritical() << "              Driver Message:" << qPrintable(query.lastError().driverText());
264     qCritical() << "                  DB Message:" << qPrintable(query.lastError().databaseText());
265
266     return false;
267   }
268   return true;
269 }
270
271 void AbstractSqlStorage::connectionDestroyed() {
272   QMutexLocker locker(&_connectionPoolMutex);
273   _connectionPool.remove(sender()->thread());
274 }
275
276 // ========================================
277 //  AbstractSqlStorage::Connection
278 // ========================================
279 AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
280   : QObject(parent),
281     _name(name.toLatin1())
282 {
283 }
284
285 AbstractSqlStorage::Connection::~Connection() {
286   {
287     QSqlDatabase db = QSqlDatabase::database(name(), false);
288     if(db.isOpen()) {
289       db.commit();
290       db.close();
291     }
292   }
293   QSqlDatabase::removeDatabase(name());
294 }
295
296
297
298
299 // ========================================
300 //  AbstractSqlMigrator
301 // ========================================
302 AbstractSqlMigrator::AbstractSqlMigrator()
303   : _query(0)
304 {
305 }
306
307 void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db) {
308   Q_ASSERT(!_query);
309   _query = new QSqlQuery(db);
310   _query->prepare(query);
311 }
312
313 void AbstractSqlMigrator::resetQuery() {
314   delete _query;
315   _query = 0;
316 }
317
318 bool AbstractSqlMigrator::exec() {
319   Q_ASSERT(_query);
320   _query->exec();
321   return !_query->lastError().isValid();
322 }
323
324 QString AbstractSqlMigrator::migrationObject(MigrationObject moType) {
325   switch(moType) {
326   case QuasselUser:
327     return "QuasselUser";
328   case Sender:
329     return "Sender";
330   case Identity:
331     return "Identity";
332   case IdentityNick:
333     return "IdentityNick";
334   case Network:
335     return "Network";
336   case Buffer:
337     return "Buffer";
338   case Backlog:
339     return "Backlog";
340   case IrcServer:
341     return "IrcServer";
342   case UserSetting:
343     return "UserSetting";
344   };
345   return QString();
346 }
347
348 QVariantList AbstractSqlMigrator::boundValues() {
349   QVariantList values;
350   if(!_query)
351     return values;
352
353   int numValues = _query->boundValues().count();
354   for(int i = 0; i < numValues; i++) {
355     values << _query->boundValue(i);
356   }
357   return values;
358 }
359
360 void AbstractSqlMigrator::dumpStatus() {
361   qWarning() << "  executed Query:";
362   qWarning() << qPrintable(executedQuery());
363   qWarning() << "  bound Values:";
364   QList<QVariant> list = boundValues();
365   for (int i = 0; i < list.size(); ++i)
366     qWarning() << i << ": " << list.at(i).toString().toAscii().data();
367   qWarning() << "  Error Number:"   << lastError().number();
368   qWarning() << "  Error Message:"   << lastError().text();
369 }
370
371
372 // ========================================
373 //  AbstractSqlMigrationReader
374 // ========================================
375 AbstractSqlMigrationReader::AbstractSqlMigrationReader()
376   : AbstractSqlMigrator(),
377     _writer(0)
378 {
379 }
380
381 bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer) {
382   if(!transaction()) {
383     qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
384     return false;
385   }
386   if(!writer->transaction()) {
387     qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
388     rollback(); // close the reader transaction;
389     return false;
390   }
391
392   _writer = writer;
393
394   // due to the incompatibility across Migration objects we can't run this in a loop... :/
395   QuasselUserMO quasselUserMo;
396   if(!transferMo(QuasselUser, quasselUserMo))
397      return false;
398
399   IdentityMO identityMo;
400   if(!transferMo(Identity, identityMo))
401     return false;
402
403   IdentityNickMO identityNickMo;
404   if(!transferMo(IdentityNick, identityNickMo))
405     return false;
406
407   NetworkMO networkMo;
408   if(!transferMo(Network, networkMo))
409     return false;
410
411   BufferMO bufferMo;
412   if(!transferMo(Buffer, bufferMo))
413     return false;
414
415   SenderMO senderMo;
416   if(!transferMo(Sender, senderMo))
417     return false;
418
419   BacklogMO backlogMo;
420   if(!transferMo(Backlog, backlogMo))
421     return false;
422
423   IrcServerMO ircServerMo;
424   if(!transferMo(IrcServer, ircServerMo))
425     return false;
426
427   UserSettingMO userSettingMo;
428   if(!transferMo(UserSetting, userSettingMo))
429     return false;
430
431   if(!_writer->postProcess())
432     abortMigration();
433   return finalizeMigration();
434 }
435
436 void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg) {
437   qWarning() << "Migration Failed!";
438   if(!errorMsg.isNull()) {
439     qWarning() << qPrintable(errorMsg);
440   }
441   if(lastError().isValid()) {
442     qWarning() << "ReaderError:";
443     dumpStatus();
444   }
445
446
447   if(_writer->lastError().isValid()) {
448     qWarning() << "WriterError:";
449     _writer->dumpStatus();
450   }
451
452   rollback();
453   _writer->rollback();
454   _writer = 0;
455 }
456
457 bool AbstractSqlMigrationReader::finalizeMigration() {
458   resetQuery();
459   _writer->resetQuery();
460
461   commit();
462   if(!_writer->commit()) {
463     _writer = 0;
464     return false;
465   }
466   _writer = 0;
467   return true;
468 }
469
470 template<typename T>
471 bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo) {
472   resetQuery();
473   _writer->resetQuery();
474
475   if(!prepareQuery(moType)) {
476     abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
477     return false;
478   }
479   if(!_writer->prepareQuery(moType)) {
480     abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
481     return false;
482   }
483
484   qDebug() << qPrintable(QString("Transferring %1...").arg(AbstractSqlMigrator::migrationObject(moType)));
485   int i = 0;
486   QFile file;
487   file.open(stdout, QIODevice::WriteOnly);
488
489   while(readMo(mo)) {
490     if(!_writer->writeMo(mo)) {
491       abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
492       return false;
493     }
494     i++;
495     if(i % 1000 == 0) {
496       file.write("*");
497       file.flush();
498     }
499   }
500   if(i > 1000) {
501     file.write("\n");
502     file.flush();
503   }
504
505   qDebug() << "Done.";
506   return true;
507 }
508