diff --git a/shared/sqlitedbservice.cpp b/shared/sqlitedbservice.cpp index ede4e26..915fe31 100644 --- a/shared/sqlitedbservice.cpp +++ b/shared/sqlitedbservice.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "looqsgeneralexception.h" #include "sqlitedbservice.h" #include "filedata.h" #include "logger.h" @@ -233,3 +234,56 @@ SaveFileResult SqliteDbService::saveFile(QFileInfo fileInfo, QVector & } return OK; } + +bool SqliteDbService::addTag(QString tag, QString path) +{ + QVector paths; + paths.append(path); + return addTag(tag, paths); +} + +bool SqliteDbService::addTag(QString tag, const QVector &paths) +{ + QSqlDatabase db = dbFactory->forCurrentThread(); + QSqlQuery tagQuery(db); + QSqlQuery fileTagQuery(db); + + tagQuery.prepare("INSERT OR IGNORE INTO tag (name) VALUES(?)"); + tagQuery.addBindValue(tag); + + fileTagQuery.prepare("INSERT INTO filetag(fileid, tagid) VALUES((SELECT id FROM file WHERE path = ?), (SELECT id " + "FROM tag WHERE name = ?))"); + fileTagQuery.bindValue(1, tag); + if(!db.transaction()) + { + Logger::error() << "Failed to open transaction to add paths for tag " << tag << " : " << db.lastError() + << Qt::endl; + return false; + } + if(!tagQuery.exec()) + { + db.rollback(); + Logger::error() << "Failed INSERT query" << tagQuery.lastError() << Qt::endl; + return false; + } + + for(const QString &path : paths) + { + fileTagQuery.bindValue(0, path); + if(!fileTagQuery.exec()) + { + db.rollback(); + Logger::error() << "Failed to add paths to tag" << Qt::endl; + return false; + } + } + + if(!db.commit()) + { + db.rollback(); + Logger::error() << "Failed to commit tag insertion transaction" << db.lastError() << Qt::endl; + return false; + } + + return true; +} diff --git a/shared/sqlitedbservice.h b/shared/sqlitedbservice.h index 09509f6..2ae8b9c 100644 --- a/shared/sqlitedbservice.h +++ b/shared/sqlitedbservice.h @@ -28,6 +28,8 @@ class SqliteDbService bool fileExistsInDatabase(QString path); bool fileExistsInDatabase(QString path, qint64 mtime); bool fileExistsInDatabase(QString path, qint64 mtime, QChar filetype); + bool addTag(QString tag, QString path); + bool addTag(QString tag, const QVector &paths); QVector search(const LooqsQuery &query); std::optional queryFileType(QString absPath);