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++

draft: temporary commit with the current state of the metadata removal unittest

Dmitry Kazakovfdc37e856db2
diff --git a/libs/resources/CMakeLists.txt b/libs/resources/CMakeLists.txt
index 3f670bec7d..ba8886423a 100644
--- a/libs/resources/CMakeLists.txt
+++ b/libs/resources/CMakeLists.txt
@@ -54,6 +54,7 @@ set(kritaresources_LIB_SRCS
KisResourceThumbnailCache.cpp
KisResourceMetaDataModel.cpp
+ KisSqlQueryLoader.cpp
)
qt_add_resources(kritaresources_LIB_SRCS sql.qrc)
diff --git a/libs/resources/KisMemoryStorage.cpp b/libs/resources/KisMemoryStorage.cpp
index ba1d173733..fbbb04f485 100644
--- a/libs/resources/KisMemoryStorage.cpp
+++ b/libs/resources/KisMemoryStorage.cpp
@@ -255,6 +255,22 @@ bool KisMemoryStorage::addResource(const QString &resourceType, KoResourceSP re
return true;
}
+bool KisMemoryStorage::testingRemoveResource(const QString &url)
+{
+ QStringList parts = url.split('/', Qt::SkipEmptyParts);
+
+ Q_ASSERT(parts.size() == 2);
+
+ const QString resourceType = parts[0];
+ const QString resourceFilename = parts[1];
+
+ if (d->resourcesNew.contains(resourceType)) {
+ return d->resourcesNew[resourceType].remove(resourceFilename) > 0;
+ }
+
+ return false;
+}
+
QString KisMemoryStorage::resourceMd5(const QString &url)
{
QStringList parts = url.split('/', Qt::SkipEmptyParts);
diff --git a/libs/resources/KisMemoryStorage.h b/libs/resources/KisMemoryStorage.h
index 2625712cf2..257106f41d 100644
--- a/libs/resources/KisMemoryStorage.h
+++ b/libs/resources/KisMemoryStorage.h
@@ -45,6 +45,10 @@ public:
QStringList metaDataKeys() const override;
QVariant metaData(const QString &key) const override;
+private:
+ friend class TestResourceLocator;
+ bool testingRemoveResource(const QString &url);
+
private:
class Private;
QScopedPointer<Private> d;
diff --git a/libs/resources/KisResourceCacheDb.cpp b/libs/resources/KisResourceCacheDb.cpp
index 976cb8d398..e55eafa8ae 100644
--- a/libs/resources/KisResourceCacheDb.cpp
+++ b/libs/resources/KisResourceCacheDb.cpp
@@ -28,6 +28,7 @@
#include <kis_debug.h>
#include <KisUsageLogger.h>
+#include <KisSqlQueryLoader.h>
#include "KisResourceLocator.h"
#include "KisResourceLoaderRegistry.h"
@@ -89,68 +90,50 @@ bool updateSchemaVersion()
return true;
}
-namespace kismpl {
-template<typename Class, typename MemType, typename MemTypeNoRef = std::remove_reference_t<MemType>>
-inline auto mem_equal_to(MemTypeNoRef (Class::*ptr)() const noexcept, MemType &&value) {
- return detail::mem_checker<std::equal_to<>, Class, MemTypeNoRef, decltype(ptr)>{ptr, std::forward<MemType>(value)};
-}
-}
-
QSqlError runUpdateScriptFile(const QString &path, const QString &message)
{
- QFile f(path);
- if (f.open(QFile::ReadOnly)) {
- QString entireScript = f.readAll();
- QTextStream stream(&entireScript);
-
- QStringList statements;
-
- // remove comments by splitting into lines
- QRegularExpression regexp("^--.*$");
- while (!stream.atEnd()) {
- const QString statement = stream.readLine().trimmed();
- if (!regexp.match(statement).hasMatch()) {
- statements.append(statement);
- }
- }
-
- // split lines into actual statements
- statements = statements.join(' ').split(';');
-
- // trim the statements
- std::transform(statements.begin(), statements.end(),
- statements.begin(), [] (const QString &x) { return x.trimmed(); });
-
- // remove empty statements
- statements.erase(std::remove_if(statements.begin(), statements.end(),
- kismpl::mem_equal_to(&QString::isEmpty, true)));
-
- Q_FOREACH (const QString &statement, statements) {
- QSqlQuery q;
- if (!q.exec(statement)) {
- qWarning() << "Could execute DB update step:" << message << q.lastError();
- qWarning() << " faulty statement:" << statement;
- return q.lastError();
- }
- }
- infoResources << "Completed DB update step:" << message;
- } else {
- return QSqlError("Error executing SQL",
- QString("Could not find SQL file %1").arg(path),
- QSqlError::StatementError);
+ try {
+
+ KisSqlQueryLoader loader(path);
+ 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;
+ 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();
+ return e.sqlError;
}
+
+ infoResources << "Completed DB update step:" << message;
return QSqlError();
}
QSqlError runUpdateScript(const QString &script, const QString &message)
{
- QSqlQuery q;
- if (!q.exec(script)) {
- qWarning() << "Could execute DB update step:" << message << q.lastError();
- return q.lastError();
+ try {
+
+ KisSqlQueryLoader loader("", script);
+ 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();
+ return e.sqlError;
}
- infoResources << "Completed DB update step:" << message;
+ infoResources << "Completed DB update step:" << message;
return QSqlError();
}
@@ -809,6 +792,7 @@ bool KisResourceCacheDb::updateResourceTableForResourceIfNeeded(int resourceId,
KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(resource, false);
resource->setVersion(maxVersion);
resource->setMD5Sum(storage->resourceMd5(url));
+ resource->setStorageLocation(storage->location());
r = makeResourceTheCurrentVersion(resourceId, resource);
}
@@ -1670,109 +1654,110 @@ bool KisResourceCacheDb::addStorageTags(KisResourceStorageSP storage)
bool KisResourceCacheDb::deleteStorage(QString location)
{
// location is already relative
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM resources\n"
- "WHERE id IN (SELECT versioned_resources.resource_id\n"
- " FROM versioned_resources\n"
- " WHERE versioned_resources.storage_id = (SELECT storages.id\n"
- " FROM storages\n"
- " WHERE storages.location = :location)\n"
- " );")) {
- qWarning() << "Could not prepare delete resources query in deleteStorage" << q.lastError();
- return false;
- }
- q.bindValue(":location", changeToEmptyIfNull(location));
- if (!q.exec()) {
- qWarning() << "Could not execute delete resources query in deleteStorage" << q.lastError();
- return false;
- }
- }
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM tags \n"
- "WHERE id IN (SELECT tags_storages.tag_id \n "
- " FROM tags_storages \n"
- " WHERE tags_storages.storage_id = \n"
- " (SELECT storages.id\n"
- " FROM storages\n"
- " WHERE storages.location = :location)\n"
- " );")) {
- qWarning() << "Could not prepare delete tag query" << q.lastError();
- return false;
- }
- q.bindValue(":location", location);
- if (!q.exec()) {
- qWarning() << "Could not execute delete tag query" << q.lastError();
- return false;
- }
- }
+ // TODO: implement transaction handling
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM tags_storages \n"
- " WHERE tags_storages.storage_id = \n"
- " (SELECT storages.id\n"
- " FROM storages\n"
- " WHERE storages.location = :location);")) {
- qWarning() << "Could not prepare delete tag storage query" << q.lastError();
- return false;
- }
- q.bindValue(":location", location);
- if (!q.exec()) {
- qWarning() << "Could not execute delete tag storage query" << q.lastError();
- return false;
+ try {
+ {
+ KisSqlQueryLoader loader(":/sql/delete_versioned_resources_for_storage_indirect.sql",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
}
- }
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM versioned_resources\n"
- "WHERE storage_id = (SELECT storages.id\n"
- " FROM storages\n"
- " WHERE storages.location = :location);")) {
- qWarning() << "Could not prepare delete versioned_resources query" << q.lastError();
- return false;
+ {
+ KisSqlQueryLoader loader(":/sql/delete_versioned_resources_for_storage_direct.sql",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
+ if (loader.query().numRowsAffected() > 0) {
+ qWarning() << "WARNING: deleteStorage: versioned_resurces table contained resource versions not being "
+ "present in the main table. Deleted: "
+ << loader.query().numRowsAffected();
+ }
}
- q.bindValue(":location", changeToEmptyIfNull(location));
- if (!q.exec()) {
- qWarning() << "Could not execute delete versioned_resources query" << q.lastError();
- return false;
+
+ {
+ KisSqlQueryLoader loader(":/sql/delete_resource_metadata_for_storage.sql",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.query().bindValue(":table", METADATA_RESOURCES);
+ loader.exec();
}
- }
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM metadata\n"
- "WHERE foreign_id = (SELECT storages.id\n"
- " FROM storages\n"
- " WHERE storages.location = :location)"
- "AND table_name = :table;")) {
- qWarning() << "Could not prepare delete metadata query" << q.lastError();
- return false;
+ {
+ KisSqlQueryLoader loader("inline://delete_current_resources_for_storage",
+ "DELETE FROM resources\n"
+ "WHERE storage_id = (SELECT storages.id\n"
+ " FROM storages\n"
+ " WHERE storages.location = :location)\n",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
}
- q.bindValue(":location", changeToEmptyIfNull(location));
- q.bindValue(":table", METADATA_STORAGES);
- if (!q.exec()) {
- qWarning() << "Could not execute delete metadata query" << q.lastError();
- return false;
+
+ {
+ KisSqlQueryLoader loader("inline://delete_tags_for_storage",
+ "DELETE FROM tags \n"
+ "WHERE id IN (SELECT tags_storages.tag_id \n "
+ " FROM tags_storages \n"
+ " WHERE tags_storages.storage_id = \n"
+ " (SELECT storages.id\n"
+ " FROM storages\n"
+ " WHERE storages.location = :location)\n"
+ " )",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
}
- }
- {
- QSqlQuery q;
- if (!q.prepare("DELETE FROM storages\n"
- "WHERE location = :location;")) {
- qWarning() << "Could not prepare delete storages query" << q.lastError();
- return false;
+ {
+ KisSqlQueryLoader loader("inline://delete_tags_storage_links_for_storage",
+ "DELETE FROM tags_storages \n"
+ "WHERE tags_storages.storage_id = \n"
+ " (SELECT storages.id\n"
+ " FROM storages\n"
+ " WHERE storages.location = :location)",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
}
- q.bindValue(":location", changeToEmptyIfNull(location));
- if (!q.exec()) {
- qWarning() << "Could not execute delete storages query" << q.lastError();
- return false;
+
+ {
+ KisSqlQueryLoader loader("inline://delete_starage_metadata_for_storage",
+ "DELETE FROM metadata\n"
+ "WHERE foreign_id = (SELECT storages.id\n"
+ " FROM storages\n"
+ " WHERE storages.location = :location)"
+ "AND table_name = :table;",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.query().bindValue(":table", METADATA_STORAGES);
+ loader.exec();
}
+
+ {
+ KisSqlQueryLoader loader("inline://delete_storage",
+ "DELETE FROM storages\n"
+ "WHERE location = :location;",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":location", changeToEmptyIfNull(location));
+ loader.exec();
+ }
+
+ } catch (const KisSqlQueryLoader::FileException &e) {
+ qWarning().noquote() << "ERROR: deleteStorage:" << e.message;
+ qWarning().noquote() << " file:" << e.filePath;
+ qWarning().noquote() << " error:" << e.fileErrorString;
+ return false;
+ } catch (const KisSqlQueryLoader::SQLException &e) {
+ qWarning().noquote() << "ERROR: deleteStorage:" << e.message;
+ qWarning().noquote() << " file:" << e.filePath;
+ qWarning().noquote() << " statement:" << e.statementIndex;
+ qWarning().noquote() << " error:" << e.sqlError.text();
+ return false;
}
+
return true;
}
@@ -2097,6 +2082,35 @@ void KisResourceCacheDb::deleteTemporaryResources()
QSqlQuery q;
+ if (!q.prepare("DELETE FROM metadata\n"
+ "WHERE foreign_id IN (SELECT id\n"
+ " FROM resources\n"
+ " WHERE storage_id in (SELECT id\n"
+ " FROM storages\n"
+ " WHERE storage_type_id == :storage_type))\n"
+ "AND table_name = :table")) {
+ qWarning() << "Could not prepare delete metadata for temporary resources query." << q.lastError();
+ }
+ q.bindValue(":table", METADATA_RESOURCES);
+ q.bindValue(":storage_type", (int)KisResourceStorage::StorageType::Memory);
+
+ if (!q.exec()) {
+ qWarning() << "Could not execute delete metadata for temporary resources query." << q.lastError();
+ }
+
+ if (!q.prepare("DELETE FROM metadata\n"
+ "WHERE foreign_id IN (SELECT id\n"
+ " FROM resources\n"
+ " WHERE temporary = 1)\n"
+ "AND table_name = :table")) {
+ qWarning() << "Could not prepare delete metadata for temporary resources query." << q.lastError();
+ }
+ q.bindValue(":table", METADATA_RESOURCES);
+
+ if (!q.exec()) {
+ qWarning() << "Could not execute delete metadata for temporary resources query." << q.lastError();
+ }
+
if (!q.prepare("DELETE FROM versioned_resources\n"
"WHERE storage_id in (SELECT id\n"
" FROM storages\n"
@@ -2137,9 +2151,9 @@ void KisResourceCacheDb::deleteTemporaryResources()
}
if (!q.prepare("DELETE FROM metadata\n"
- "WHERE foreign_id = (SELECT id\n"
- " FROM storages\n"
- " WHERE storage_type_id == :storage_type)\n"
+ "WHERE foreign_id IN (SELECT id\n"
+ " FROM storages\n"
+ " WHERE storage_type_id == :storage_type)\n"
"AND table_name = :table;")) {
qWarning() << "Could not prepare delete temporary resources query." << q.lastError();
}
@@ -2150,7 +2164,6 @@ void KisResourceCacheDb::deleteTemporaryResources()
qWarning() << "Could not execute delete temporary resources query." << q.lastError();
}
-
if (!q.prepare("DELETE FROM resources\n"
"WHERE temporary = 1")) {
qWarning() << "Could not prepare delete temporary resources query." << q.lastError();
diff --git a/libs/resources/KisResourceStorage.cpp b/libs/resources/KisResourceStorage.cpp
index 00ac8e23ec..2b41f7123a 100644
--- a/libs/resources/KisResourceStorage.cpp
+++ b/libs/resources/KisResourceStorage.cpp
@@ -306,6 +306,11 @@ int KisResourceStorage::storageId()
return d->storageId;
}
+KisStoragePlugin* KisResourceStorage::testingGetStoragePlugin()
+{
+ return d->storagePlugin.data();
+}
+
struct VersionedFileParts
{
QString basename;
diff --git a/libs/resources/KisResourceStorage.h b/libs/resources/KisResourceStorage.h
index 3f9b1f2db6..74a7efa967 100644
--- a/libs/resources/KisResourceStorage.h
+++ b/libs/resources/KisResourceStorage.h
@@ -272,6 +272,9 @@ private:
friend class KisStorageModel;
friend class KisResourceLocator;
friend class KisResourceCacheDb;
+ friend class TestResourceLocator;
+
+ KisStoragePlugin* testingGetStoragePlugin();
void setStorageId(int storageId);
int storageId();
diff --git a/libs/resources/KisSqlQueryLoader.cpp b/libs/resources/KisSqlQueryLoader.cpp
new file mode 100644
index 0000000000..ebb7cee8c0
--- /dev/null
+++ b/libs/resources/KisSqlQueryLoader.cpp
@@ -0,0 +1,129 @@
+/*
+ * SPDX-FileCopyrightText: 2025 Dmitry Kazakov <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#include "KisSqlQueryLoader.h"
+
+#include <algorithm>
+#include <stdexcept>
+
+#include <QtSql>
+#include <QFile>
+#include <QRegularExpression>
+#include <QStringList>
+#include <QTextStream>
+
+#include <kis_assert.h>
+#include <KisMpl.h>
+
+namespace kismpl {
+ template<typename Class, typename MemType, typename MemTypeNoRef = std::remove_reference_t<MemType>>
+ inline auto mem_equal_to(MemTypeNoRef (Class::*ptr)() const noexcept, MemType &&value) {
+ return detail::mem_checker<std::equal_to<>, Class, MemTypeNoRef, decltype(ptr)>{ptr, std::forward<MemType>(value)};
+ }
+}
+
+void KisSqlQueryLoader::init(const QString &fileName, QString entireScript, bool singleStatementMode)
+{
+ m_singleStatementMode = singleStatementMode;
+ m_fileName = fileName;
+
+ QTextStream stream(&entireScript);
+
+ // remove comments by splitting into lines
+ QRegularExpression regexp("^--.*$");
+ while (!stream.atEnd()) {
+ const QString statement = stream.readLine().trimmed();
+ if (!regexp.match(statement).hasMatch()) {
+ m_statements.append(statement);
+ }
+ }
+
+ // split lines into actual statements
+ m_statements = m_statements.join(' ').split(';');
+
+ // trim the statements
+ std::transform(m_statements.begin(), m_statements.end(),
+ m_statements.begin(), [] (const QString &x) { return x.trimmed(); });
+
+ // remove empty statements
+ m_statements.erase(std::remove_if(m_statements.begin(), m_statements.end(),
+ kismpl::mem_equal_to(&QString::isEmpty, true)),
+ m_statements.end());
+
+ if (m_singleStatementMode) {
+ KIS_SAFE_ASSERT_RECOVER_RETURN(m_statements.size() == 1);
+ if (!m_query.prepare(m_statements.first())) {
+ throw SQLException(
+ "Failed to prepare an sql query from file",
+ m_fileName,
+ 0,
+ m_query.lastError());
+ }
+ }
+}
+
+KisSqlQueryLoader::KisSqlQueryLoader(const QString &fileName)
+{
+ QFile file(fileName);
+ if (file.open(QFile::ReadOnly)) {
+ init(fileName, file.readAll(), false);
+ } else {
+ throw FileException("Could not load SQL script file", fileName, file.errorString());
+ }
+}
+
+KisSqlQueryLoader::KisSqlQueryLoader(const QString &fileName, prepare_only_t)
+{
+ QFile file(fileName);
+ if (file.open(QFile::ReadOnly)) {
+ init(fileName, file.readAll(), true);
+ } else {
+ throw FileException("Could not load SQL script file", fileName, file.errorString());
+ }
+}
+
+KisSqlQueryLoader::KisSqlQueryLoader(const QString &scriptName, const QString &script)
+{
+ init(scriptName, script, false);
+}
+
+KisSqlQueryLoader::KisSqlQueryLoader(const QString &scriptName, const QString &script, prepare_only_t)
+{
+ init(scriptName, script, true);
+}
+
+KisSqlQueryLoader::~KisSqlQueryLoader()
+{
+}
+
+QSqlQuery& KisSqlQueryLoader::query()
+{
+ return m_query;
+}
+
+void KisSqlQueryLoader::exec()
+{
+ if (m_singleStatementMode) {
+ if (!m_query.exec()) {
+ throw SQLException(
+ "Failed to execute sql from file",
+ m_fileName,
+ 0,
+ m_query.lastError());
+ }
+ } else {
+ for (int i = 0; i < m_statements.size(); i++) {
+ const QString &statement = m_statements[i];
+ if (!m_query.exec(statement)) {
+ throw SQLException(
+ "Failed to execute sql from file",
+ m_fileName,
+ i,
+ m_query.lastError());
+ }
+ }
+ }
+}
diff --git a/libs/resources/KisSqlQueryLoader.h b/libs/resources/KisSqlQueryLoader.h
new file mode 100644
index 0000000000..f7aab0260a
--- /dev/null
+++ b/libs/resources/KisSqlQueryLoader.h
@@ -0,0 +1,77 @@
+/*
+ * SPDX-FileCopyrightText: 2025 Dmitry Kazakov <[email protected]>
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+#ifndef KISSQLQUERYLOADER_H
+#define KISSQLQUERYLOADER_H
+
+#include <kritaresources_export.h>
+
+#include <exception>
+#include <QSqlQuery>
+#include <QSqlError>
+#include <QStringList>
+#include <QFileDevice>
+
+class KRITARESOURCES_EXPORT KisSqlQueryLoader
+{
+public:
+ struct prepare_only_t {};
+ static constexpr prepare_only_t prepare_only{};
+
+ struct FileException : std::exception
+ {
+ FileException(QString _message,
+ QString _filePath,
+ QString _fileErrorString)
+ : message(_message)
+ , filePath(_filePath)
+ , fileErrorString(_fileErrorString)
+ {}
+
+ QString message;
+ QString filePath;
+ QString fileErrorString;
+ };
+
+ struct SQLException : std::exception
+ {
+ SQLException(QString _message,
+ QString _filePath,
+ int _statementIndex,
+ QSqlError _sqlError)
+ : message(_message)
+ , filePath(_filePath)
+ , statementIndex(_statementIndex)
+ , sqlError(_sqlError)
+ {}
+
+ QString message;
+ QString filePath;
+ int statementIndex {0};
+ QSqlError sqlError;
+ };
+
+public:
+ KisSqlQueryLoader(const QString &fileName);
+ KisSqlQueryLoader(const QString &fileName, prepare_only_t);
+ KisSqlQueryLoader(const QString &scriptName, const QString &script);
+ KisSqlQueryLoader(const QString &scriptName, const QString &script, prepare_only_t);
+
+ ~KisSqlQueryLoader();
+
+ QSqlQuery& query();
+ void exec();
+
+private:
+ void init(const QString &fileName, QString entireScript, bool singleStatementMode);
+
+private:
+ QSqlQuery m_query;
+ QStringList m_statements;
+ bool m_singleStatementMode {false};
+ QString m_fileName;
+};
+
+#endif /* KISSQLQUERYLOADER_H */
diff --git a/libs/resources/sql.qrc b/libs/resources/sql.qrc
index d75399a027..5668e1d47e 100644
--- a/libs/resources/sql.qrc
+++ b/libs/resources/sql.qrc
@@ -26,5 +26,9 @@
<file alias="0_0_18_0001_cleanup_metadata_table.sql">sql/0_0_18_0001_cleanup_metadata_table.sql</file>
<file alias="0_0_18_0002_update_metadata_table_constraints.sql">sql/0_0_18_0002_update_metadata_table_constraints.sql</file>
<file alias="create_index_metadata_key.sql">sql/create_index_metadata_key.sql</file>
+ <file>sql/delete_versioned_resources_for_storage_indirect.sql</file>
+ <file>sql/delete_versioned_resources_for_storage_direct.sql</file>
+ <file>sql/delete_resource_metadata_for_storage.sql</file>
+
</qresource>
</RCC>
diff --git a/libs/resources/sql/delete_resource_metadata_for_storage.sql b/libs/resources/sql/delete_resource_metadata_for_storage.sql
new file mode 100644
index 0000000000..4d9b37cf21
--- /dev/null
+++ b/libs/resources/sql/delete_resource_metadata_for_storage.sql
@@ -0,0 +1,7 @@
+DELETE FROM metadata
+ WHERE metadata.table_name = :table
+ AND foreign_id IN (SELECT id FROM resources
+ WHERE resources.storage_id =
+ (SELECT storages.id
+ FROM storages
+ WHERE storages.location = :location))
\ No newline at end of file
diff --git a/libs/resources/sql/delete_versioned_resources_for_storage_direct.sql b/libs/resources/sql/delete_versioned_resources_for_storage_direct.sql
new file mode 100644
index 0000000000..83b52340c3
--- /dev/null
+++ b/libs/resources/sql/delete_versioned_resources_for_storage_direct.sql
@@ -0,0 +1,6 @@
+WITH storage_id_query
+AS (SELECT storages.id
+ FROM storages
+ WHERE storages.location = :location)
+DELETE FROM versioned_resources
+ WHERE storage_id = (SELECT * FROM storage_id_query)
\ No newline at end of file
diff --git a/libs/resources/sql/delete_versioned_resources_for_storage_indirect.sql b/libs/resources/sql/delete_versioned_resources_for_storage_indirect.sql
new file mode 100644
index 0000000000..e2c2f89f16
--- /dev/null
+++ b/libs/resources/sql/delete_versioned_resources_for_storage_indirect.sql
@@ -0,0 +1,8 @@
+WITH storage_id_query
+AS (SELECT storages.id
+ FROM storages
+ WHERE storages.location = :location)
+DELETE FROM versioned_resources
+ WHERE resource_id
+ IN (SELECT id FROM resources
+ WHERE storage_id = (SELECT * FROM storage_id_query))
\ No newline at end of file
diff --git a/libs/resources/tests/DummyResource.h b/libs/resources/tests/DummyResource.h
index c11d5d3a74..d164f998b3 100644
--- a/libs/resources/tests/DummyResource.h
+++ b/libs/resources/tests/DummyResource.h
@@ -33,6 +33,9 @@ public:
img.fill(Qt::blue);
setImage(img);
+ // add some random metadata to the resource
+ addMetaData("test_metadata", expectedMetaData());
+
setValid(true);
}
@@ -54,7 +57,7 @@ public:
if (!dev->isOpen()) {
dev->open(QIODevice::ReadOnly);
}
- m_something = QString::fromUtf8(dev->readAll());
+ setSomething(QString::fromUtf8(dev->readAll()));
setValid(true);
return true;
}
@@ -71,6 +74,7 @@ public:
void setSomething(const QString &something)
{
m_something = something;
+ addMetaData("test_metadata", expectedMetaData());
}
QString something() const
@@ -78,6 +82,11 @@ public:
return m_something;
}
+ QString expectedMetaData() const
+ {
+ return m_something.left(8);
+ }
+
QPair<QString, QString> resourceType() const override {
return QPair<QString, QString>(m_resourceType, "");
}
@@ -88,4 +97,13 @@ private:
QString m_resourceType;
};
+class DummyResourceWithMetadata : public DummyResource {
+public:
+ DummyResourceWithMetadata(const QString &f, const QString &resourceType = ResourceType::PaintOpPresets)
+ : DummyResource(f, resourceType)
+ {
+
+ }
+};
+
#endif // DUMMYRESOURCE_H
diff --git a/libs/resources/tests/TestResourceLocator.cpp b/libs/resources/tests/TestResourceLocator.cpp
index 604f6efd47..d87c43b6d9 100644
--- a/libs/resources/tests/TestResourceLocator.cpp
+++ b/libs/resources/tests/TestResourceLocator.cpp
@@ -158,6 +158,226 @@ void TestResourceLocator::testDocumentStorage()
QVERIFY(model.rowCount() == rowcount);
}
+#include <KisResourceMetaDataModel.h>
+#include <KisResourceModelProvider.h>
+#include <KisSqlQueryLoader.h>
+
+int countMetaDataForResource(int resourceId)
+{
+ try {
+ KisSqlQueryLoader loader("inline://count_metadata_for_resource",
+ "SELECT COUNT(*) FROM metadata WHERE foreign_id = :resource_id",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":resource_id", resourceId);
+ loader.exec();
+
+ loader.query().first();
+ return loader.query().value(0).toInt();
+
+ } 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 -1;
+ }
+}
+
+int countCurrentResourcesForResourceId(int resourceId)
+{
+ try {
+ KisSqlQueryLoader loader("inline://count_current_resource_for_resource_id",
+ "SELECT COUNT(*) FROM resources WHERE id = :resource_id",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":resource_id", resourceId);
+ loader.exec();
+
+ loader.query().first();
+ return loader.query().value(0).toInt();
+
+ } 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 -1;
+ }
+}
+
+int countVersionedResourcesForResourceId(int resourceId)
+{
+ try {
+ KisSqlQueryLoader loader("inline://count_current_resource_for_resource_id",
+ "SELECT COUNT(*) FROM versioned_resources WHERE resource_id = :resource_id",
+ KisSqlQueryLoader::prepare_only);
+ loader.query().bindValue(":resource_id", resourceId);
+ loader.exec();
+
+ loader.query().first();
+ return loader.query().value(0).toInt();
+
+ } 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 -1;
+ }
+}
+
+void TestResourceLocator::testLoadResourceMetadataFromStorage()
+{
+ 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);
+
+
+ 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());
+
+ QSharedPointer<DummyResource> resource(new DummyResource("metadata_test.kpp", ResourceType::PaintOpPresets));
+ resource->setSomething("123456789012345678901234567890");
+
+ documentStorage->addResource(resource);
+
+ m_locator->addStorage(documentName, documentStorage);
+
+ QVERIFY(m_locator->hasStorage(documentName));
+ QCOMPARE(model.rowCount(), initialRowCount + 1);
+
+ QSharedPointer<DummyResource> loadedResource;
+ int loadedResourceId = -1;
+
+ {
+ auto loadedResources = model.resourcesForFilename("metadata_test.kpp");
+ QCOMPARE(loadedResources.size(), 1);
+ loadedResource = loadedResources.first().dynamicCast<DummyResource>();
+ loadedResourceId = loadedResource->resourceId();
+ QVERIFY(loadedResourceId >= 0);
+
+ QCOMPARE(loadedResource->metadata()["test_metadata"], "12345678");
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "12345678");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 1);
+ }
+
+ const bool addNewVersionsToLocator = false;
+ const bool addNewVersionsToStorageAndSync = true;
+ const bool deleteStorageNormally = false;
+ const bool deleteAllTemporaryStorages = true;
+
+ if (addNewVersionsToLocator) {
+ loadedResource->setSomething("098765432109876543210987654321");
+ model.updateResource(loadedResource);
+
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "09876543");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+
+ loadedResource->setSomething("6666666666666666666666666");
+ model.updateResource(loadedResource);
+
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "66666666");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 3);
+ }
+
+ if (addNewVersionsToStorageAndSync) {
+ const QString resourceType = loadedResource->resourceType().first;
+
+ /**
+ * Create a new version of the resource
+ */
+ loadedResource->setSomething("098765432109876543210987654321");
+
+ // manually upload it into the storage bypassing the locator
+ resource->setVersion(resource->version() + 1);
+ documentStorage->saveAsNewVersion(loadedResource);
+ resource->setMD5Sum(documentStorage->resourceMd5(resourceType + "/" + resource->filename()));
+ resource->setDirty(false);
+
+ // nothing has changed yet, the database is in the old state
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "12345678");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 1);
+
+ // now synchronize storage with the database
+ KisResourceCacheDb::synchronizeStorage(documentStorage);
+ Q_EMIT m_locator->storageResynchronized(documentStorage->location(), false);
+
+ // the changes are present in the database
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "09876543");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 2);
+
+ /**
+ * Create another version of the resource
+ */
+ loadedResource->setSomething("6666666666666666666666666");
+ resource->setVersion(resource->version() + 1);
+ documentStorage->saveAsNewVersion(loadedResource);
+ resource->setMD5Sum(documentStorage->resourceMd5(resourceType + "/" + resource->filename()));
+ resource->setDirty(false);
+
+ KisResourceCacheDb::synchronizeStorage(documentStorage);
+ Q_EMIT m_locator->storageResynchronized(documentStorage->location(), false);
+
+ QCOMPARE(metadataModel->metaDataValue(loadedResourceId, "test_metadata"), "66666666");
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 1);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 1);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 3);
+
+ /**
+ * Now remove the last version from the storage and try
+ * to sync it to the database
+ */
+
+ KisMemoryStorage *memoryStorageBackend =
+ dynamic_cast<KisMemoryStorage*>(documentStorage->testingGetStoragePlugin());
+
+ memoryStorageBackend->testingRemoveResource(resourceType + "/" + resource->filename());
+
+ 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);
+ }
+
+ if (deleteStorageNormally) {
+ m_locator->removeStorage(documentName);
+ }
+
+ if (deleteAllTemporaryStorages) {
+ KisResourceCacheDb::deleteTemporaryResources();
+ }
+
+ if (loadedResourceId >= 0) {
+ QVERIFY(!metadataModel->metaDataValue(loadedResourceId, "test_metadata").isValid());
+
+ QCOMPARE(countMetaDataForResource(loadedResourceId), 0);
+ QCOMPARE(countCurrentResourcesForResourceId(loadedResourceId), 0);
+ QCOMPARE(countVersionedResourcesForResourceId(loadedResourceId), 0);
+ }
+
+ QCOMPARE(model.rowCount(), initialRowCount);
+}
+
void TestResourceLocator::testSyncVersions()
{
int resourceId = -1;
@@ -465,8 +685,8 @@ void TestResourceLocator::testImportDuplicatedResource()
void TestResourceLocator::cleanupTestCase()
{
- ResourceTestHelper::rmTestDb();
- ResourceTestHelper::cleanDstLocation(m_dstLocation);
+ // ResourceTestHelper::rmTestDb();
+ // ResourceTestHelper::cleanDstLocation(m_dstLocation);
}
SIMPLE_TEST_MAIN(TestResourceLocator)
diff --git a/libs/resources/tests/TestResourceLocator.h b/libs/resources/tests/TestResourceLocator.h
index b64acb7bf4..6366828282 100644
--- a/libs/resources/tests/TestResourceLocator.h
+++ b/libs/resources/tests/TestResourceLocator.h
@@ -25,6 +25,7 @@ private Q_SLOTS:
void testResource();
void testResourceForId();
void testDocumentStorage();
+ void testLoadResourceMetadataFromStorage();
void cleanupTestCase();