+bool AbstractSqlStorage::upgradeDb()
+{
+ if (schemaVersion() <= installedSchemaVersion())
+ return true;
+
+ QSqlDatabase db = logDb();
+
+ // TODO: For databases that support it (e.g. almost only PostgreSQL), wrap upgrades in a
+ // transaction. This will need careful testing of potential additional space requirements and
+ // any database modifications that might not be allowed in a transaction.
+
+ // Check if we're resuming an interrupted multi-step upgrade: is an upgrade step stored?
+ const QString previousLaunchUpgradeStep = schemaVersionUpgradeStep();
+ bool resumingUpgrade = !previousLaunchUpgradeStep.isEmpty();
+
+ for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
+ foreach (auto queryResource, upgradeQueries(ver)) {
+ if (resumingUpgrade) {
+ // An upgrade was interrupted. Check if this matches the the last successful query.
+ if (previousLaunchUpgradeStep == queryResource.queryFilename) {
+ // Found the matching query!
+ qInfo() << qPrintable(QString("Resuming interrupted upgrade for schema version %1 (last step: %2)")
+ .arg(QString::number(ver), previousLaunchUpgradeStep));
+
+ // Stop searching for queries
+ resumingUpgrade = false;
+ // Continue past the previous query with the next not-yet-tried query
+ continue;
+ }
+ else {
+ // Not yet matched, keep looking
+ continue;
+ }
+ }
+
+ // Run the upgrade query
+ QSqlQuery query = db.exec(queryResource.queryString);
+ if (!watchQuery(query)) {
+ // Individual upgrade query failed, bail out
+ qCritical() << qPrintable(QString("Unable to upgrade Logging Backend! Upgrade query in schema version %1 failed (step: %2).")
+ .arg(QString::number(ver), queryResource.queryFilename));
+ return false;
+ }
+ else {
+ // Mark as successful
+ setSchemaVersionUpgradeStep(queryResource.queryFilename);
+ }
+ }
+
+ if (resumingUpgrade) {
+ // Something went wrong and the last successful SQL query to resume from couldn't be
+ // found.
+ // 1. The storage of successful query glitched, or the database was manually changed
+ // 2. Quassel changed the filenames of upgrade queries, and the local Quassel core
+ // version was replaced during an interrupted schema upgrade
+ //
+ // Both are unlikely, but it's a good idea to handle it anyways.
+
+ qCritical() << qPrintable(QString("Unable to resume interrupted upgrade in Logging "
+ "Backend! Missing upgrade step in schema version %1 "
+ "(expected step: %2)")
+ .arg(QString::number(ver), previousLaunchUpgradeStep));
+ return false;
+ }
+
+ // Update the schema version for each intermediate step and mark the step as done. This
+ // ensures that any interrupted upgrades have a greater chance of resuming correctly after
+ // core restart.
+ //
+ // Almost all databases make single queries atomic (fully works or fully fails, no partial),
+ // and with many of the longest migrations being a single query, this makes upgrade
+ // interruptions much more likely to leave the database in a valid intermediate schema
+ // version.
+ if (!updateSchemaVersion(ver, true)) {
+ // Updating the schema version failed, bail out
+ qCritical() << "Unable to upgrade Logging Backend! Setting schema version" << ver << "failed.";
+ return false;
+ }
+ }
+
+ // If we made it here, everything seems to have worked!
+ return true;
+}
+
+int AbstractSqlStorage::schemaVersion()
+{
+ // returns the newest Schema Version!
+ // not the currently used one! (though it can be the same)
+ if (_schemaVersion > 0)
+ return _schemaVersion;
+
+ int version;
+ bool ok;
+ // Schema versions are stored in the 'version/##' subfolders.
+ QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
+ foreach (QFileInfo fileInfo, dir.entryInfoList()) {
+ if (!fileInfo.isDir())
+ continue;
+
+ version = fileInfo.fileName().toInt(&ok);
+ if (!ok)
+ continue;
+
+ if (version > _schemaVersion)
+ _schemaVersion = version;
+ }
+ return _schemaVersion;
+}
+
+
+QString AbstractSqlStorage::schemaVersionUpgradeStep()
+{
+ // By default, assume there's no pending upgrade
+ return {};
+}
+
+
+bool AbstractSqlStorage::watchQuery(QSqlQuery& query)
+{
+ bool queryError = query.lastError().isValid();
+ if (queryError || _debug) {
+ if (queryError)
+ qCritical() << "unhandled Error in QSqlQuery!";
+ qCritical() << " last Query:\n" << qPrintable(query.lastQuery());
+ qCritical() << " executed Query:\n" << qPrintable(query.executedQuery());
+ QVariantMap boundValues = query.boundValues();
+ QStringList valueStrings;
+ QVariantMap::const_iterator iter;
+ for (iter = boundValues.constBegin(); iter != boundValues.constEnd(); ++iter) {
+ QString value;
+ QSqlField field;
+ if (query.driver()) {
+ // let the driver do the formatting
+ field.setType(iter.value().type());
+ if (iter.value().isNull())
+ field.clear();
+ else
+ field.setValue(iter.value());
+ value = query.driver()->formatValue(field);
+ }
+ else {
+ switch (iter.value().type()) {
+ case QVariant::Invalid:
+ value = "NULL";
+ break;
+ case QVariant::Int:
+ value = iter.value().toString();
+ break;
+ default:
+ value = QString("'%1'").arg(iter.value().toString());
+ }
+ }
+ valueStrings << QString("%1=%2").arg(iter.key(), value);
+ }
+ qCritical() << " bound Values:" << qPrintable(valueStrings.join(", "));
+ qCritical() << " Error Code:" << qPrintable(query.lastError().nativeErrorCode());
+ qCritical() << " Error Message:" << qPrintable(query.lastError().text());
+ qCritical() << " Driver Message:" << qPrintable(query.lastError().driverText());
+ qCritical() << " DB Message:" << qPrintable(query.lastError().databaseText());
+
+ return !queryError;
+ }
+ return true;
+}
+
+void AbstractSqlStorage::connectionDestroyed()
+{
+ QMutexLocker locker(&_connectionPoolMutex);
+ _connectionPool.remove(sender()->thread());
+}
+
+// ========================================
+// AbstractSqlStorage::Connection
+// ========================================
+AbstractSqlStorage::Connection::Connection(const QString& name, QObject* parent)
+ : QObject(parent)
+ , _name(name.toLatin1())
+{}
+
+AbstractSqlStorage::Connection::~Connection()
+{
+ {
+ QSqlDatabase db = QSqlDatabase::database(name(), false);
+ if (db.isOpen()) {
+ db.commit();
+ db.close();
+ }
+ }
+ QSqlDatabase::removeDatabase(name());