Skip to content

armgit / krita

Public Imported from GitHub
0

Krita is a free and open source cross-platform application that offers an end-to-end solution for creating digital art files from scratch built on the KDE and Qt frameworks.

C++

Finish TestResourceLocator::testLoadResourceMetadataFromStorage

Dmitry Kazakov48f995a07b77
diff --git a/libs/global/kis_debug.cpp b/libs/global/kis_debug.cpp
index c83ec0457a..6ce46158ce 100644
--- a/libs/global/kis_debug.cpp
+++ b/libs/global/kis_debug.cpp
@@ -71,6 +71,7 @@ QString kisBacktrace()
}
Q_LOGGING_CATEGORY(_30009, "krita.lib.resources", QtInfoMsg)
+Q_LOGGING_CATEGORY(_30010, "krita.db.migration", QtInfoMsg)
Q_LOGGING_CATEGORY(_41000, "krita.general", QtInfoMsg)
Q_LOGGING_CATEGORY(_41001, "krita.core", QtInfoMsg)
Q_LOGGING_CATEGORY(_41002, "krita.registry", QtInfoMsg)
diff --git a/libs/global/kis_debug.h b/libs/global/kis_debug.h
index 2a52b78e23..d9038760e5 100644
--- a/libs/global/kis_debug.h
+++ b/libs/global/kis_debug.h
@@ -19,6 +19,7 @@
*/
extern const KRITAGLOBAL_EXPORT QLoggingCategory &_30009();
+extern const KRITAGLOBAL_EXPORT QLoggingCategory &_30010();
extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41000();
extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41001();
extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41002();
@@ -40,6 +41,7 @@ extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41017();
extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41018();
#define dbgResources qCDebug(_30009)
+#define dbgDbMigration qCDebug(_30010)
#define dbgKrita qCDebug(_41000)
#define dbgImage qCDebug(_41001)
#define dbgRegistry qCDebug(_41002)
@@ -61,6 +63,7 @@ extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41018();
#define dbgLocale qCDebug(_41018)
#define infoResources qCInfo(_30009)
+#define infoDbMigration qCInfo(_30010)
#define infoKrita qCInfo(_41000)
#define infoImage qCInfo(_41001)
#define infoRegistry qCInfo(_41002)
@@ -80,6 +83,7 @@ extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41018();
#define infoMetaData qCDebug(_41016)
#define warnResources qCWarning(_30009)
+#define warnDbMigration qCWarning(_30010)
#define warnKrita qCWarning(_41000)
#define warnImage qCWarning(_41001)
#define warnRegistry qCWarning(_41002)
@@ -99,6 +103,7 @@ extern const KRITAGLOBAL_EXPORT QLoggingCategory &_41018();
#define warnMetaData qCDebug(_41016)
#define errResources qCCritical(_30009)
+#define errDbMigration qCCritical(_30010)
#define errKrita qCCritical(_41000)
#define errImage qCCritical(_41001)
#define errRegistry qCCritical(_41002)
diff --git a/libs/resources/CMakeLists.txt b/libs/resources/CMakeLists.txt
index ba8886423a..a1e1f243ae 100644
--- a/libs/resources/CMakeLists.txt
+++ b/libs/resources/CMakeLists.txt
@@ -55,6 +55,7 @@ set(kritaresources_LIB_SRCS
KisResourceThumbnailCache.cpp
KisResourceMetaDataModel.cpp
KisSqlQueryLoader.cpp
+ KisDatabaseTransactionLock.cpp
)
qt_add_resources(kritaresources_LIB_SRCS sql.qrc)
diff --git a/libs/resources/KisDatabaseTransactionLock.cpp b/libs/resources/KisDatabaseTransactionLock.cpp
new file mode 100644
index 0000000000..3fe82438c8
--- /dev/null
+++ b/libs/resources/KisDatabaseTransactionLock.cpp
@@ -0,0 +1,57 @@
+/*
+ * SPDX-FileCopyrightText: 2025 Dmitry Kazakov <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "KisDatabaseTransactionLock.h"
+
+#include <QDebug>
+#include <QSqlError>
+
+#include <kis_assert.h>
+
+
+namespace detail
+{
+
+KisDatabaseTransactionLockAdapter::KisDatabaseTransactionLockAdapter(QSqlDatabase database)
+ : m_database(database)
+{
+}
+
+void KisDatabaseTransactionLockAdapter::lock()
+{
+ KIS_SAFE_ASSERT_RECOVER_RETURN(!m_transactionStarted);
+ if (!m_database.transaction()) {
+ qWarning() << "WARNING: Failed to start a transaction:" << m_database.lastError().text();
+ } else {
+ m_transactionStarted = true;
+ }
+}
+
+void KisDatabaseTransactionLockAdapter::unlock()
+{
+ if (!m_transactionStarted)
+ return;
+
+ if (!m_database.rollback()) {
+ qWarning() << "WARNING: Failed to rollback a transaction:" << m_database.lastError().text();
+ }
+
+ m_transactionStarted = false;
+}
+
+void KisDatabaseTransactionLockAdapter::commit()
+{
+ if (!m_transactionStarted)
+ return;
+
+ if (!m_database.commit()) {
+ qWarning() << "WARNING: Failed to commit a transaction:" << m_database.lastError().text();
+ }
+
+ m_transactionStarted = false;
+}
+
+} // namespace detail
diff --git a/libs/resources/KisDatabaseTransactionLock.h b/libs/resources/KisDatabaseTransactionLock.h
new file mode 100644
index 0000000000..960f59152d
--- /dev/null
+++ b/libs/resources/KisDatabaseTransactionLock.h
@@ -0,0 +1,91 @@
+/*
+ * SPDX-FileCopyrightText: 2025 Dmitry Kazakov <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef KISDATABASETRANSACTIONLOCK_H
+#define KISDATABASETRANSACTIONLOCK_H
+
+#include <QSqlDatabase>
+
+#include <kritaresources_export.h>
+
+#include <KisAdaptedLock.h>
+
+
+namespace detail
+{
+struct KRITARESOURCES_EXPORT KisDatabaseTransactionLockAdapter {
+
+ KisDatabaseTransactionLockAdapter(QSqlDatabase database);
+
+ void lock();
+ void unlock();
+ void commit();
+
+private:
+ QSqlDatabase m_database;
+ bool m_transactionStarted{false};
+};
+} // namespace detail
+
+
+/**
+ * A RAII-style class for managing transactions over a database.
+ *
+ * When the lock is created (and locked) a transacion is started. If the
+ * lock is destroyed before the commit() is explicitly called, then the
+ * transaction is **rolled back**.
+ *
+ * To successfully finish the transaction the user should explicitly
+ * defuse the lock by calling commit() method.
+ *
+ * Usage:
+ *
+ * \code{.cpp}
+ *
+ * /// Start the transaction
+ *
+ * KisDatabaseTransactionLock transactionLock(database);
+ *
+ * QSqlQuery q(sql);
+ * if (!q.exec()) {
+ *
+ * /// on leaving the scope transactionLock will automatically
+ * /// rollback the transaction
+ *
+ * return false;
+ * }
+ *
+ * /// explicitly commit the transaction when we know
+ * /// everything is fine
+ *
+ * transactionLock.commit();
+ *
+ * \endcode
+ *
+ * NOTE:
+ *
+ * As a rule of thumb, always wrap the actions performing mutliple
+ * database-modifying steps into a transaction. It will perform
+ * much (~10 times) faster in SQLite, because otherwise SQLite will
+ * implicitly wrap every single action into its own transaction and
+ * it will be slow.
+ *
+ */
+class KRITARESOURCES_EXPORT KisDatabaseTransactionLock
+ : public KisAdaptedLock<detail::KisDatabaseTransactionLockAdapter>
+{
+public:
+ using BaseClass = KisAdaptedLock<detail::KisDatabaseTransactionLockAdapter>;
+ using BaseClass::BaseClass;
+ using BaseClass::commit;
+
+ inline void rollback() {
+ unlock();
+ }
+};
+
+
+#endif /* KISDATABASETRANSACTIONLOCK_H */
diff --git a/libs/resources/KisResourceCacheDb.cpp b/libs/resources/KisResourceCacheDb.cpp
index e55eafa8ae..fb0337ae5a 100644
--- a/libs/resources/KisResourceCacheDb.cpp
+++ b/libs/resources/KisResourceCacheDb.cpp
@@ -29,6 +29,7 @@
#include <KisUsageLogger.h>
#include <KisSqlQueryLoader.h>
+#include <KisDatabaseTransactionLock.h>
#include "KisResourceLocator.h"
#include "KisResourceLoaderRegistry.h"
@@ -75,17 +76,18 @@ bool updateSchemaVersion()
QString sql = f.readAll();
QSqlQuery q;
if (!q.prepare(sql)) {
- qWarning() << "Could not prepare the schema information query" << q.lastError() << q.boundValues();
+ warnDbMigration << "Could not prepare the schema information query" << q.lastError() << q.boundValues();
return false;
}
q.addBindValue(KisResourceCacheDb::databaseVersion);
q.addBindValue(KritaVersionWrapper::versionString());
q.addBindValue(QDateTime::currentDateTimeUtc().toSecsSinceEpoch());
if (!q.exec()) {
- qWarning() << "Could not insert the current version" << q.lastError() << q.boundValues();
+ warnDbMigration << "Could not insert the current version" << q.lastError() << q.boundValues();
return false;
}
- infoResources << "Filled version table";
+
+ infoDbMigration << "Filled version table";
}
return true;
}
@@ -98,24 +100,24 @@ QSqlError runUpdateScriptFile(const QString &path, const QString &message)
loader.exec();
} catch (const KisSqlQueryLoader::FileException &e) {
- qWarning().noquote() << "ERROR: Could not execute DB update step:" << message;
- qWarning().noquote() << " error" << e.message;
- qWarning().noquote() << " file:" << e.filePath;
- qWarning().noquote() << " file-error:" << e.fileErrorString;
+ warnDbMigration.noquote() << "ERROR: Could not execute DB update step:" << message;
+ warnDbMigration.noquote() << " error" << e.message;
+ warnDbMigration.noquote() << " file:" << e.filePath;
+ warnDbMigration.noquote() << " file-error:" << e.fileErrorString;
return
QSqlError("Error executing SQL",
QString("Could not find SQL file %1").arg(e.filePath),
QSqlError::StatementError);
} catch (const KisSqlQueryLoader::SQLException &e) {
- qWarning().noquote() << "ERROR: Could not execute DB update step:" << message;
- qWarning().noquote() << " error" << e.message;
- qWarning().noquote() << " file:" << e.filePath;
- qWarning().noquote() << " statement:" << e.statementIndex;
- qWarning().noquote() << " sql-error:" << e.sqlError.text();
+ warnDbMigration.noquote() << "ERROR: Could not execute DB update step:" << message;
+ warnDbMigration.noquote() << " error" << e.message;
+ warnDbMigration.noquote() << " file:" << e.filePath;
+ warnDbMigration.noquote() << " statement:" << e.statementIndex;
+ warnDbMigration.noquote() << " sql-error:" << e.sqlError.text();
return e.sqlError;
}
- infoResources << "Completed DB update step:" << message;
+ infoDbMigration << "Completed DB update step:" << message;
return QSqlError();
}
@@ -127,13 +129,13 @@ QSqlError runUpdateScript(const QString &script, const QString &message)
loader.exec();
} catch (const KisSqlQueryLoader::SQLException &e) {
- qWarning().noquote() << "ERROR: Could execute DB update step:" << message;
- qWarning().noquote() << " error" << e.message;
- qWarning().noquote() << " sql-error:" << e.sqlError.text();
+ warnDbMigration.noquote() << "ERROR: Could execute DB update step:" << message;
+ warnDbMigration.noquote() << " error" << e.message;
+ warnDbMigration.noquote() << " sql-error:" << e.sqlError.text();
return e.sqlError;
}
- infoResources << "Completed DB update step:" << message;
+ infoDbMigration << "Completed DB update step:" << message;
return QSqlError();
}
@@ -142,29 +144,44 @@ QSqlError createDatabase(const QString &location)
// NOTE: if the id's of Unknown and Memory in the database
// will change, and that will break the queries that
// remove Unknown and Memory storages on start-up.
- KisResourceCacheDb::storageTypes << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(1))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(2))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(3))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(4))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(5))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(6))
- << KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(7));
-
- if (!QSqlDatabase::connectionNames().isEmpty()) {
- return QSqlError();
- }
+ KisResourceCacheDb::storageTypes = QStringList {
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(1)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(2)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(3)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(4)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(5)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(6)),
+ KisResourceStorage::storageTypeToUntranslatedString(KisResourceStorage::StorageType(7))};
QDir dbLocation(location);
if (!dbLocation.exists()) {
dbLocation.mkpath(dbLocation.path());
}
- QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);
- db.setDatabaseName(location + "/" + KisResourceCacheDb::resourceCacheDbFilename);
+ std::optional<QSqlDatabase> existingDatabase =
+ QSqlDatabase::database(QSqlDatabase::defaultConnection, false);
+
+ const bool databaseConnectionExists = !QSqlDatabase::connectionNames().isEmpty()
+ && existingDatabase->isValid() && existingDatabase->isOpen();
+
+ if (databaseConnectionExists && existingDatabase->tables().contains("version_information")) {
+ return QSqlError();
+ }
+
+ existingDatabase = std::nullopt;
+
+ QSqlDatabase db;
+
+ if (!databaseConnectionExists) {
+ db = QSqlDatabase::addDatabase(dbDriver);
+ db.setDatabaseName(location + "/" + KisResourceCacheDb::resourceCacheDbFilename);
- if (!db.open()) {
- qWarning() << "Could not connect to resource cache database";
- return db.lastError();
+ if (!db.open()) {
+ warnDbMigration << "Could not connect to resource cache database";
+ return db.lastError();
+ }
+ } else {
+ db = QSqlDatabase::database();
}
// will be filled correctly later
@@ -215,7 +232,7 @@ QSqlError createDatabase(const QString &location)
"LIMIT 1;\n");
if (!q.exec()) {
- qWarning() << "Could not retrieve version information from the database." << q.lastError();
+ warnDbMigration << "Could not retrieve version information from the database." << q.lastError();
abort();
}
q.first();
@@ -229,7 +246,7 @@ QSqlError createDatabase(const QString &location)
if (QVersionNumber::compare(oldSchemaVersionNumber, newSchemaVersionNumber) != 0) {
- qWarning() << "Old schema:" << schemaVersion << "New schema:" << newSchemaVersionNumber;
+ infoDbMigration << "Old schema:" << schemaVersion << "New schema:" << newSchemaVersionNumber;
schemaIsOutDated = true;
KisBackup::numberedBackupFile(location + "/" + KisResourceCacheDb::resourceCacheDbFilename);
@@ -252,6 +269,8 @@ QSqlError createDatabase(const QString &location)
|| oldSchemaVersionNumber == QVersionNumber::fromString("0.0.16")
|| oldSchemaVersionNumber == QVersionNumber::fromString("0.0.17");
+ KisDatabaseTransactionLock transactionLock(QSqlDatabase::database());
+
bool success = true;
if (from14to15) {
QSqlError error = runUpdateScript(
@@ -263,7 +282,7 @@ QSqlError createDatabase(const QString &location)
}
}
if (success && from15to16) {
- qWarning() << "Going to update indices";
+ infoDbMigration << "Going to update indices";
QStringList indexes = QStringList() << "tags" << "resources" << "tag_translations" << "resource_tags";
@@ -313,6 +332,8 @@ QSqlError createDatabase(const QString &location)
success = false;
}
+ transactionLock.commit();
+
if (success) {
QSqlError error = runUpdateScript("VACUUM",
"Vacuum database after updating schema");
@@ -320,6 +341,8 @@ QSqlError createDatabase(const QString &location)
success = false;
}
}
+ } else {
+ transactionLock.rollback();
}
schemaIsOutDated = !success;
@@ -352,6 +375,8 @@ QSqlError createDatabase(const QString &location)
.arg(oldSchemaVersionNumber.toString().isEmpty() ? QString("database didn't exist") : ("old schema version: " + oldSchemaVersionNumber.toString()))
.arg("new schema version: " + newSchemaVersionNumber.toString()));
+ KisDatabaseTransactionLock transactionLock(QSqlDatabase::database());
+
// Create tables
Q_FOREACH(const QString &table, tables) {
QSqlError error =
@@ -401,11 +426,11 @@ QSqlError createDatabase(const QString &location)
QSqlQuery q(sql);
q.addBindValue(originType);
if (!q.exec()) {
- qWarning() << "Could execute DB update step:" << updateStep << q.lastError();
- qWarning() << " faulty statement:" << sql;
+ warnDbMigration << "Could execute DB update step:" << updateStep << q.lastError();
+ warnDbMigration << " faulty statement:" << sql;
return db.lastError();
}
- infoResources << "Completed DB update step:" << updateStep;
+ infoDbMigration << "Completed DB update step:" << updateStep;
}
}
else {
@@ -422,11 +447,11 @@ QSqlError createDatabase(const QString &location)
QSqlQuery q(sql);
q.addBindValue(resourceType);
if (!q.exec()) {
- qWarning() << "Could execute DB update step:" << updateStep << q.lastError();
- qWarning() << " faulty statement:" << sql;
+ warnDbMigration << "Could execute DB update step:" << updateStep << q.lastError();
+ warnDbMigration << " faulty statement:" << sql;
return db.lastError();
}
- infoResources << "Completed DB update step:" << updateStep;
+ infoDbMigration << "Completed DB update step:" << updateStep;
}
}
else {
@@ -438,6 +463,8 @@ QSqlError createDatabase(const QString &location)
return QSqlError("Error executing SQL", QString("Could not update schema version."), QSqlError::StatementError);
}
+ transactionLock.commit();
+
return QSqlError();
}
diff --git a/libs/resources/KisResourceModel.cpp b/libs/resources/KisResourceModel.cpp
index a651636d59..23eade9d76 100644
--- a/libs/resources/KisResourceModel.cpp
+++ b/libs/resources/KisResourceModel.cpp
@@ -51,32 +51,7 @@ KisAllResourcesModel::KisAllResourcesModel(const QString &resourceType, QObject
d->resourceType = resourceType;
- bool r = d->resourcesQuery.prepare("SELECT resources.id\n"
- ", resources.storage_id\n"
- ", resources.name\n"
- ", resources.filename\n"
- ", resources.tooltip\n"
- ", resources.status\n"
- ", resources.md5sum\n"
- ", storages.location\n"
- ", resource_types.name as resource_type\n"
- ", resources.status as resource_active\n"
- ", storages.active as storage_active\n"
- "FROM resources\n"
- ", resource_types\n"
- ", storages\n"
- "WHERE resources.resource_type_id = resource_types.id\n"
- "AND resources.storage_id = storages.id\n"
- "AND resource_types.name = :resource_type\n"
- "GROUP BY resources.name\n"
- ", resources.filename\n"
- ", resources.md5sum\n"
- "ORDER BY resources.id");
- if (!r) {
- qWarning() << "Could not prepare KisAllResourcesModel query" << d->resourcesQuery.lastError();
- }
- d->resourcesQuery.bindValue(":resource_type", d->resourceType);
-
+ prepareQuery();
resetQuery();
}
@@ -573,8 +548,56 @@ bool KisAllResourcesModel::setResourceMetaData(KoResourceSP resource, QMap<QStri
return KisResourceLocator::instance()->setMetaDataForResource(resource->resourceId(), metadata);
}
+bool KisAllResourcesModel::prepareQuery()
+{
+ bool r = d->resourcesQuery.prepare(
+ "SELECT resources.id\n"
+ ", resources.storage_id\n"
+ ", resources.name\n"
+ ", resources.filename\n"
+ ", resources.tooltip\n"
+ ", resources.status\n"
+ ", resources.md5sum\n"
+ ", storages.location\n"
+ ", resource_types.name as resource_type\n"
+ ", resources.status as resource_active\n"
+ ", storages.active as storage_active\n"
+ "FROM resources\n"
+ ", resource_types\n"
+ ", storages\n"
+ "WHERE resources.resource_type_id = resource_types.id\n"
+ "AND resources.storage_id = storages.id\n"
+ "AND resource_types.name = :resource_type\n"
+ "GROUP BY resources.name\n"
+ ", resources.filename\n"
+ ", resources.md5sum\n"
+ "ORDER BY resources.id");
+
+ if (!r) {
+ qWarning() << "Could not prepare KisAllResourcesModel query" << d->resourcesQuery.lastError();
+ return false;
+ }
+
+ d->resourcesQuery.bindValue(":resource_type", d->resourceType);
+ return true;
+}
+
+void KisAllResourcesModel::closeQuery()
+{
+ d->resourcesQuery.clear();
+}
+
bool KisAllResourcesModel::resetQuery()
{
+ /**
+ * In case the query has been previously closed, try to restart it
+ * (used in unittests mostly)
+ */
+ if (!d->resourcesQuery.isValid()) {
+ d->resourcesQuery.clear();
+ prepareQuery();
+ }
+
bool r = d->resourcesQuery.exec();
if (!r) {
qWarning() << "Could not select" << d->resourceType << "resources" << d->resourcesQuery.lastError() << d->resourcesQuery.boundValues();
diff --git a/libs/resources/KisResourceModel.h b/libs/resources/KisResourceModel.h
index e47f762572..3e4eaf6147 100644
--- a/libs/resources/KisResourceModel.h
+++ b/libs/resources/KisResourceModel.h
@@ -351,7 +351,9 @@ public:
private:
+ bool prepareQuery();
bool resetQuery();
+ void closeQuery();
struct Private;
Private *const d;
diff --git a/libs/resources/KisResourceModelProvider.cpp b/libs/resources/KisResourceModelProvider.cpp
index 56cd0b19fb..a4da6034b2 100644
--- a/libs/resources/KisResourceModelProvider.cpp
+++ b/libs/resources/KisResourceModelProvider.cpp
@@ -43,7 +43,7 @@ KisResourceModelProvider::~KisResourceModelProvider()
KisAllResourcesModel *KisResourceModelProvider::resourceModel(const QString &resourceType)
{
if (!s_instance->d->resourceModels.contains(resourceType)) {
- s_instance->d->resourceModels[resourceType] = new KisAllResourcesModel(resourceType);
+ s_instance->d->resourceModels[resourceType] = new KisAllResourcesModel(resourceType);
}
return s_instance->d->resourceModels[resourceType];
}
@@ -76,6 +76,29 @@ void KisResourceModelProvider::testingResetAllModels()
for (auto it = s_instance->d->tagResourceModels.begin(); it != s_instance->d->tagResourceModels.end(); ++it) {
it.value()->resetQuery();
}
+
+ /// NOTE: we just remove the entire metadata model when we want to reset it,
+ /// please refactor it when the metadata model becomes a QObject and will get
+ /// any kind of connection to outer world.
+ s_instance->d->metaDataModel = std::nullopt;
+}
+
+void KisResourceModelProvider::testingCloseAllQueries()
+{
+ for (auto it = s_instance->d->tagModels.begin(); it != s_instance->d->tagModels.end(); ++it) {
+ it.value()->closeQuery();
+ }
+ for (auto it = s_instance->d->resourceModels.begin(); it != s_instance->d->resourceModels.end(); ++it) {
+ it.value()->closeQuery();
+ }
+ for (auto it = s_instance->d->tagResourceModels.begin(); it != s_instance->d->tagResourceModels.end(); ++it) {
+ it.value()->closeQuery();
+ }
+
+ /// NOTE: we just remove the entire metadata model when we want to reset it,
+ /// please refactor it when the metadata model becomes a QObject and will get
+ /// any kind of connection to outer world.
+ s_instance->d->metaDataModel = std::nullopt;
}
KisResourceMetaDataModel* KisResourceModelProvider::resourceMetadataModel()
diff --git a/libs/resources/KisResourceModelProvider.h b/libs/resources/KisResourceModelProvider.h
index f7874e3e3a..160cee94ab 100644
--- a/libs/resources/KisResourceModelProvider.h
+++ b/libs/resources/KisResourceModelProvider.h
@@ -31,6 +31,7 @@ public:
static KisAllTagResourceModel *tagResourceModel(const QString& resourceType);
static void testingResetAllModels();
+ static void testingCloseAllQueries();
static KisResourceMetaDataModel *resourceMetadataModel();
private:
diff --git a/libs/resources/KisTagModel.cpp b/libs/resources/KisTagModel.cpp
index ac9c0efa8f..cea5ef506d 100644
--- a/libs/resources/KisTagModel.cpp
+++ b/libs/resources/KisTagModel.cpp
@@ -515,6 +515,11 @@ bool KisAllTagsModel::resetQuery()
return r;
}
+void KisAllTagsModel::closeQuery()
+{
+ d->query.clear();
+}
+
void KisAllTagsModel::addStorage(const QString &location)
{
Q_UNUSED(location)
diff --git a/libs/resources/KisTagModel.h b/libs/resources/KisTagModel.h
index 99775ba5bf..c2111351b6 100644
--- a/libs/resources/KisTagModel.h
+++ b/libs/resources/KisTagModel.h
@@ -111,6 +111,7 @@ private:
void untagAllResources(KisTagSP tag);
bool resetQuery();
+ void closeQuery();
struct Private;
Private* const d;
diff --git a/libs/resources/KisTagResourceModel.cpp b/libs/resources/KisTagResourceModel.cpp
index 91fdf3fa03..152451425f 100644
--- a/libs/resources/KisTagResourceModel.cpp
+++ b/libs/resources/KisTagResourceModel.cpp
@@ -688,6 +688,11 @@ QVariant KisAllTagResourceModel::headerData(int section, Qt::Orientation orienta
return {};
}
+void KisAllTagResourceModel::closeQuery()
+{
+ d->query.clear();
+}
+
bool KisAllTagResourceModel::resetQuery()
{
bool r = d->query.prepare(createQuery(true));
diff --git a/libs/resources/KisTagResourceModel.h b/libs/resources/KisTagResourceModel.h
index f0689f35ff..24d4b77bc3 100644
--- a/libs/resources/KisTagResourceModel.h
+++ b/libs/resources/KisTagResourceModel.h
@@ -89,6 +89,7 @@ private:
QString createQuery(bool onlyAchieve = true, bool returnADbIndexToo = false);
bool resetQuery();
+ void closeQuery();
struct Private;
diff --git a/libs/resources/tests/ResourceTestHelper.h b/libs/resources/tests/ResourceTestHelper.h
index d91e784938..37daed69f1 100644
--- a/libs/resources/tests/ResourceTestHelper.h
+++ b/libs/resources/tests/ResourceTestHelper.h
@@ -14,12 +14,16 @@
#include <KisMimeDatabase.h>
#include <KisResourceLoaderRegistry.h>
+#include <KisResourceLocator.h>
#include <KisResourceCacheDb.h>
#include "KisResourceTypes.h"
#include <DummyResource.h>
#include <KisStoragePlugin.h>
#include <simpletest.h>
#include "kis_debug.h"
+#include <KisSqlQueryLoader.h>
+#include <KisDatabaseTransactionLock.h>
+#include <KisResourceModelProvider.h>
#ifndef FILES_DATA_DIR
#error "FILES_DATA_DIR not set. A directory with the data used for testing installing resources"
@@ -241,6 +245,88 @@ void testVersionedStorageIterator(KisStoragePlugin &storage, const QString &reso
QCOMPARE(numVersions, 4);
};
+bool recreateDatabaseForATest(KisResourceLocator *locator, const QString &srcLocation, const QString &dstLocation)
+{
+ auto listDbResources = [](const QString &dbResourceType) {
+ KisSqlQueryLoader loader("inline://list_all_db_tables",
+ "SELECT name FROM sqlite_master WHERE sql IS NOT NULL and name != \"sqlite_sequence\" "
+ "and type = :db_resource_type",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":db_resource_type", dbResourceType);
+ loader.exec();
+
+ QVector<QString> dbResources;
+ while (loader.query().next()) {
+ dbResources.append(loader.query().value(0).toString());
+ }
+ return dbResources;
+ };
+
+ auto dropDbResource = [](const QString &dbResourceType, const QString &dbResourceName) {
+ KisSqlQueryLoader loader("inline://drop_db_resource_" + dbResourceType,
+ QString("DROP %1 %2").arg(dbResourceType.toUpper(), dbResourceName));
+ loader.exec();
+
+ QVector<QString> dbResources;
+ while (loader.query().next()) {
+ dbResources.append(loader.query().value(0).toString());
+ }
+ return dbResources;
+ };
+
+ auto enableForeignKeys = [](bool isEnabled) {
+ KisSqlQueryLoader loader("inline://enable_foreign_keys",
+ QString("PRAGMA foreign_keys = %1").arg(isEnabled ? "on" : "off"));
+ loader.exec();
+ };
+
+ if (QSqlDatabase::database(QSqlDatabase::defaultConnection, false).isOpen()) {
+ try {
+ KisResourceModelProvider::testingCloseAllQueries();
+
+ KisDatabaseTransactionLock transactionLock(QSqlDatabase::database());
+
+ enableForeignKeys(false);
+
+ Q_FOREACH (const QString &dbResourceType, QStringList({"table", "index", "trigger", "view"})) {
+ auto resources = listDbResources(dbResourceType);
+ Q_FOREACH (const auto &resource, resources) {
+ // qDebug() << "dropping" << ppVar(dbResourceType) << ppVar(resource);
+ dropDbResource(dbResourceType, resource);
+ }
+ }
+ enableForeignKeys(true);
+
+ // defuse the lock and save the results
+ transactionLock.commit();
+
+ } catch (const KisSqlQueryLoader::SQLException &e) {
+ qWarning().noquote() << "ERROR: failed to execute query:" << e.message;
+ qWarning().noquote() << " file:" << e.filePath;
+ qWarning().noquote() << " statement:" << e.statementIndex;
+ qWarning().noquote() << " error:" << e.sqlError.text();
+
+ return false;
+ }
+ }
+
+ ResourceTestHelper::cleanDstLocation(dstLocation);
+
+ // Reinitialize the database from scratch
+ KisResourceCacheDb::initialize(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
+
+ KisResourceLocator::LocatorError r = locator->initialize(srcLocation);
+
+ if (!locator->errorMessages().isEmpty()) {
+ qDebug() << locator->errorMessages();
+ }
+ if (r != KisResourceLocator::LocatorError::Ok) {
+ return false;
+ }
+
+ return true;
+}
+
}
#endif // RESOURCETESTHELPER_H
diff --git a/libs/resources/tests/TestResourceLocator.cpp b/libs/resources/tests/TestResourceLocator.cpp
index d87c43b6d9..e24b9a00bb 100644
--- a/libs/resources/tests/TestResourceLocator.cpp
+++ b/libs/resources/tests/TestResourceLocator.cpp
@@ -34,6 +34,9 @@
#include <KisResourceModelProvider.h>
#include <KoMD5Generator.h>
+#include <KisResourceMetaDataModel.h>
+#include <KisResourceModelProvider.h>
+#include <KisSqlQueryLoader.h>
#ifndef FILES_DATA_DIR
#error "FILES_DATA_DIR not set. A directory with the data used for testing installing resources"
@@ -41,6 +44,10 @@
void TestResourceLocator::initTestCase()
{
+ // disable database migration debug messages to avoid bloating the output
+ const_cast<QLoggingCategory&>(_30010()).setEnabled(QtDebugMsg, false);
+ const_cast<QLoggingCategory&>(_30010()).setEnabled(QtInfoMsg, false);
+
ResourceTestHelper::initTestDb();
m_srcLocation = QString(FILES_DATA_DIR);
@@ -57,12 +64,13 @@ void TestResourceLocator::initTestCase()
ResourceTestHelper::createDummyLoaderRegistry();
}
+void TestResourceLocator::init()
+{
+ QVERIFY(ResourceTestHelper::recreateDatabaseForATest(m_locator, m_srcLocation, m_dstLocation));
+}
+
void TestResourceLocator::testLocatorInitialization()
{
- KisResourceCacheDb::initialize(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
- KisResourceLocator::LocatorError r = m_locator->initialize(m_srcLocation);
- if (!m_locator->errorMessages().isEmpty()) qDebug() << m_locator->errorMessages();
- QVERIFY(r == KisResourceLocator::LocatorError::Ok);
QVERIFY(QDir(m_dstLocation).exists());
Q_FOREACH(const QString &folder, KisResourceLoaderRegistry::instance()->resourceTypes()) {
QDir dstDir(m_dstLocation + '/' + folder + '/');
@@ -78,24 +86,15 @@ void TestResourceLocator::testLocatorInitialization()
QVersionNumber version = QVersionNumber::fromString(QString::fromUtf8(f.readAll()));
QVERIFY(version == QVersionNumber::fromString(KritaVersionWrapper::versionString()));
-}
-
-void TestResourceLocator::testStorageInitialization()
-{
- Q_FOREACH(KisResourceStorageSP storage, m_locator->storages()) {
- QVERIFY(KisResourceCacheDb::addStorage(storage, true));
+ {
+ QSqlQuery query;
+ bool r = query.exec("SELECT COUNT(*) FROM storages");
+ QVERIFY(r);
+ QVERIFY(query.lastError() == QSqlError());
+ query.first();
+ QCOMPARE(query.value(0).toInt(), 4);
}
- QSqlQuery query;
- bool r = query.exec("SELECT COUNT(*) FROM storages");
- QVERIFY(r);
- QVERIFY(query.lastError() == QSqlError());
- query.first();
- QCOMPARE(query.value(0).toInt(), m_locator->storages().count());
-}
-void TestResourceLocator::testLocatorSynchronization()
-{
- QVERIFY(m_locator->synchronizeDb());
{
QSqlQuery query;
bool r = query.exec("SELECT COUNT(*) FROM resources");
@@ -158,10 +157,6 @@ void TestResourceLocator::testDocumentStorage()
QVERIFY(model.rowCount() == rowcount);
}
-#include <KisResourceMetaDataModel.h>
-#include <KisResourceModelProvider.h>
-#include <KisSqlQueryLoader.h>
-
int countMetaDataForResource(int resourceId)
{
try {
@@ -225,21 +220,50 @@ int countVersionedResourcesForResourceId(int resourceId)
}
}
-void TestResourceLocator::testLoadResourceMetadataFromStorage()
+enum MetaDataTestFlag
+{
+ None = 0x0,
+ NewVersionViaLocator = 0x1,
+ NewVersionViaStorageSync = 0x2,
+ RemoveNewVersionViaStorageSync = 0x4,
+ DeleteStorageNormally = 0x8,
+ DeleteAllTemporaryStorages = 0x10
+};
+
+Q_DECLARE_FLAGS(MetaDataTestFlags, MetaDataTestFlag)
+Q_DECLARE_OPERATORS_FOR_FLAGS(MetaDataTestFlags)
+Q_DECLARE_METATYPE(MetaDataTestFlags)
+
+void TestResourceLocator::testLoadResourceMetadataFromStorage_data()
{
- KisResourceCacheDb::initialize(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
- KisResourceLocator::LocatorError r = m_locator->initialize(m_srcLocation);
- if (!m_locator->errorMessages().isEmpty()) qDebug() << m_locator->errorMessages();
- QVERIFY(r == KisResourceLocator::LocatorError::Ok);
+ QTest::addColumn<MetaDataTestFlags>("flags");
+
+ QTest::newRow("no_modifications") << MetaDataTestFlags(None);
+ QTest::newRow("locator+delete_storage") <<
+ MetaDataTestFlags(NewVersionViaLocator | DeleteStorageNormally);
+ QTest::newRow("locator+delete_temporary") <<
+ MetaDataTestFlags(NewVersionViaLocator | DeleteAllTemporaryStorages);
+ QTest::newRow("storage+delete_storage") <<
+ MetaDataTestFlags(NewVersionViaStorageSync | DeleteStorageNormally);
+ QTest::newRow("storage+delete_temporary") <<
+ MetaDataTestFlags(NewVersionViaStorageSync | DeleteAllTemporaryStorages);
+ QTest::newRow("storage+remove+delete_storage") <<
+ MetaDataTestFlags(NewVersionViaStorageSync | RemoveNewVersionViaStorageSync | DeleteStorageNormally);
+ QTest::newRow("storage+remove+delete_temporary") <<
+ MetaDataTestFlags(NewVersionViaStorageSync | RemoveNewVersionViaStorageSync | DeleteAllTemporaryStorages);
+}
+void TestResourceLocator::testLoadResourceMetadataFromStorage()
+{
+ QFETCH(MetaDataTestFlags, flags);
+
const QString &documentName("document");
KisResourceMetaDataModel *metadataModel = KisResourceModelProvider::resourceMetadataModel();
KisResourceModel model(ResourceType::PaintOpPresets);
const int initialRowCount = model.rowCount();
- ENTER_FUNCTION() << ppVar(initialRowCount);
KisResourceStorageSP documentStorage = QSharedPointer<KisResourceStorage>::create(documentName);
QVERIFY(documentStorage->valid());
@@ -271,12 +295,10 @@ void TestResourceLocator::testLoadResourceMetadataFromStorage()
QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 1);
}
- const bool addNewVersionsToLocator = false;
- const bool addNewVersionsToStorageAndSync = true;
- const bool deleteStorageNormally = false;
- const bool deleteAllTemporaryStorages = true;
+ KIS_ASSERT(!flags.testFlag(RemoveNewVersionViaStorageSync) ||
+ flags.testFlag(NewVersionViaStorageSync));
- if (addNewVersionsToLocator) {
+ if (flags.testFlag(NewVersionViaLocator)) {
loadedResource->setSomething("098765432109876543210987654321");
model.updateResource(loadedResource);
@@ -293,7 +315,7 @@ void TestResourceLocator::testLoadResourceMetadataFromStorage()
QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 3);
}
- if (addNewVersionsToStorageAndSync) {
+ if (flags.testFlag(NewVersionViaStorageSync)) {
const QString resourceType = loadedResource->resourceType().first;
/**
@@ -340,34 +362,36 @@ void TestResourceLocator::testLoadResourceMetadataFromStorage()
QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 3);
- /**
- * Now remove the last version from the storage and try
- * to sync it to the database
- */
+ if (flags.testFlag(RemoveNewVersionViaStorageSync)) {
+ /**
+ * Now remove the last version from the storage and try
+ * to sync it to the database
+ */
- KisMemoryStorage *memoryStorageBackend =
- dynamic_cast<KisMemoryStorage*>(documentStorage->testingGetStoragePlugin());
+ KisMemoryStorage *memoryStorageBackend =
+ dynamic_cast<KisMemoryStorage *>(documentStorage->testingGetStoragePlugin());
- memoryStorageBackend->testingRemoveResource(resourceType + "/" + resource->filename());
+ memoryStorageBackend->testingRemoveResource(resourceType + "/" + resource->filename());
- KisResourceCacheDb::synchronizeStorage(documentStorage);
- Q_EMIT m_locator->storageResynchronized(documentStorage->location(), false);
+ KisResourceCacheDb::synchronizeStorage(documentStorage);
+ Q_EMIT m_locator->storageResynchronized(documentStorage->location(), false);
- QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "09876543");
- QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
- QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
- QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 2);
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "09876543");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 2);
+ }
}
- if (deleteStorageNormally) {
+ if (flags.testFlag(DeleteStorageNormally)) {
m_locator->removeStorage(documentName);
}
- if (deleteAllTemporaryStorages) {
+ if (flags.testFlag(DeleteAllTemporaryStorages)) {
KisResourceCacheDb::deleteTemporaryResources();
}
- if (loadedResourceId >= 0) {
+ if (loadedResourceId >= 0 && flags & (DeleteStorageNormally | DeleteAllTemporaryStorages)) {
QVERIFY(!metadataModel->metaDataValue(loadedResourceId, "test_metadata").isValid());
QCOMPARE(countMetaDataForResource(loadedResourceId), 0);
@@ -375,7 +399,14 @@ void TestResourceLocator::testLoadResourceMetadataFromStorage()
QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 0);
}
- QCOMPARE(model.rowCount(), initialRowCount);
+ /**
+ * We don't test the number of resources in the model after deleteTemporaryResources(),
+ * because this call doesn't actually removes the resources, it only clears them up from
+ * the database.
+ */
+ if (flags.testFlag(DeleteStorageNormally)) {
+ QCOMPARE(model.rowCount(), initialRowCount);
+ }
}
void TestResourceLocator::testSyncVersions()
diff --git a/libs/resources/tests/TestResourceLocator.h b/libs/resources/tests/TestResourceLocator.h
index 6366828282..ebf97f60ec 100644
--- a/libs/resources/tests/TestResourceLocator.h
+++ b/libs/resources/tests/TestResourceLocator.h
@@ -17,15 +17,15 @@ class TestResourceLocator : public QObject
Q_OBJECT
private Q_SLOTS:
void initTestCase();
+ void init();
void testLocatorInitialization();
- void testStorageInitialization();
- void testLocatorSynchronization();
void testResourceLocationBase();
void testResource();
void testResourceForId();
void testDocumentStorage();
void testLoadResourceMetadataFromStorage();
+ void testLoadResourceMetadataFromStorage_data();
void cleanupTestCase();