MauiKit File Browsing

tagdb.cpp
1/*
2 * Copyright 2018 Camilo Higuita <milo.h@aol.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Library General Public License as
6 * published by the Free Software Foundation; either version 2, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details
13 *
14 * You should have received a copy of the GNU Library General Public
15 * License along with this program; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 */
19
20#include "tagdb.h"
21
22#include <QDebug>
23#include <QDir>
24#include <QList>
25#include <QSqlDriver>
26#include <QSqlError>
27#include <QSqlQuery>
28#include <QSqlRecord>
29#include <QUuid>
30
31TAGDB::TAGDB() : QObject(nullptr)
32{
33 QDir collectionDBPath_dir(TAG::TaggingPath);
34 if (!collectionDBPath_dir.exists())
35 collectionDBPath_dir.mkpath(QStringLiteral("."));
36
38 if (!FMH::fileExists(QUrl::fromLocalFile(TAG::TaggingPath + TAG::DBName))) {
39 this->openDB(this->name);
40 qDebug() << "Collection doesn't exists, trying to create it" << TAG::TaggingPath + TAG::DBName;
41 this->prepareCollectionDB();
42 } else
43 this->openDB(this->name);
44}
45
46TAGDB::~TAGDB()
47{
48 qDebug() << "CLOSING THE TAGGING DATA BASE";
49 this->m_db.close();
50}
51
52void TAGDB::openDB(const QString &name)
53{
54 if (!QSqlDatabase::contains(name)) {
55 this->m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), name);
56 this->m_db.setDatabaseName(TAG::TaggingPath + TAG::DBName);
57 }
58
59 if (!this->m_db.isOpen()) {
60 if (!this->m_db.open())
61 qDebug() << "ERROR OPENING DB" << this->m_db.lastError().text() << m_db.connectionName();
62 }
63 auto query = this->getQuery(QStringLiteral("PRAGMA synchronous=OFF"));
64 query.exec();
65}
66
67void TAGDB::prepareCollectionDB() const
68{
69 QSqlQuery query(this->m_db);
70
71 QFile file(QStringLiteral(":/script.sql"));
72
73 if (!file.exists()) {
74 QString log = QStringLiteral("Fatal error on build database. The file '");
75 log.append(file.fileName() + QStringLiteral("' for database and tables creation query cannot be not found!"));
76 qDebug() << log;
77 return;
78 }
79
80 if (!file.open(QIODevice::ReadOnly)) {
81 qDebug() << QStringLiteral("Fatal error on try to create database! The file with sql queries for database creation cannot be opened!");
82 return;
83 }
84
85 bool hasText;
86 QString line;
87 QByteArray readLine;
88 QString cleanedLine;
89 QStringList strings;
90
91 while (!file.atEnd()) {
92 hasText = false;
93 line = QStringLiteral("");
94 readLine = "";
95 cleanedLine = QStringLiteral("");
96 strings.clear();
97 while (!hasText) {
98 readLine = file.readLine();
99 cleanedLine = QString::fromStdString(readLine.trimmed().toStdString());
100 strings = cleanedLine.split(QStringLiteral("--"));
101 cleanedLine = strings.at(0);
102 if (!cleanedLine.startsWith(QStringLiteral("--")) && !cleanedLine.startsWith(QStringLiteral("DROP")) && !cleanedLine.isEmpty())
103 line += cleanedLine;
104 if (cleanedLine.endsWith(QStringLiteral(";")))
105 break;
106 if (cleanedLine.startsWith(QStringLiteral("COMMIT")))
107 hasText = true;
108 }
109 if (!line.isEmpty()) {
110 if (!query.exec(line)) {
111 qDebug() << "exec failed" << query.lastQuery() << query.lastError();
112 }
113
114 } else
115 qDebug() << "exec wrong" << query.lastError();
116 }
117 file.close();
118}
119
120bool TAGDB::checkExistance(const QString &tableName, const QString &searchId, const QString &search) const
121{
122 const auto queryStr = QString(QStringLiteral("SELECT %1 FROM %2 WHERE %3 = \"%4\"")).arg(searchId, tableName, searchId, search);
123 return this->checkExistance(queryStr);
124}
125
126bool TAGDB::checkExistance(const QString &queryStr) const
127{
128 qDebug() << "CHECKIGN QUERY TAG" << queryStr;
129 auto query = this->getQuery(queryStr);
130
131 if (query.exec()) {
132 if (query.next())
133 return true;
134 } else
135 qDebug() << query.lastError().text();
136
137 return false;
138}
139
140QSqlQuery TAGDB::getQuery(const QString &queryTxt) const
141{
142 QSqlQuery query(queryTxt, this->m_db);
143 return query;
144}
145
147{
148 QSqlQuery query(this->m_db);
149 return query;
150}
151
152bool TAGDB::insert(const QString &tableName, const QVariantMap &insertData) const
153{
154 if (tableName.isEmpty()) {
155 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
156 return false;
157
158 } else if (insertData.isEmpty()) {
159 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
160 return false;
161 }
162
163 QStringList strValues;
164 QStringList fields = insertData.keys();
165 QVariantList values = insertData.values();
166 int totalFields = fields.size();
167 for (int i = 0; i < totalFields; ++i)
168 strValues.append(QStringLiteral("?"));
169
170 QString sqlQueryString = QStringLiteral("INSERT INTO ") + tableName + QStringLiteral(" (") + QString(fields.join(QStringLiteral(","))) + QStringLiteral(") VALUES(") + QString(strValues.join(QStringLiteral(","))) + QStringLiteral(")");
171 QSqlQuery query(this->m_db);
172 query.prepare(sqlQueryString);
173
174 int k = 0;
175
176 for(const QVariant &value : values)
177 query.bindValue(k++, value);
178
179 return query.exec();
180}
181
182bool TAGDB::update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where) const
183{
184 if (tableName.isEmpty()) {
185 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
186 return false;
187 } else if (updateData.isEmpty()) {
188 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
189 return false;
190 }
191
192 QStringList set;
193 const auto updateKeys = updateData.keys();
194 for (const auto &key : updateKeys)
195 {
196 set.append(FMH::MODEL_NAME[key] + QStringLiteral(" = '") + updateData[key] + QStringLiteral("'"));
197 }
198
199 QStringList condition;
200 const auto whereKeys = where.keys();
201 for (const auto &key : whereKeys)
202 {
203 condition.append(key + QStringLiteral(" = '") + where[key].toString() + QStringLiteral("'"));
204 }
205
206 QString sqlQueryString = QStringLiteral("UPDATE ") + tableName + QStringLiteral(" SET ") + QString(set.join(QStringLiteral(","))) + QStringLiteral(" WHERE ") + QString(condition.join(QStringLiteral(",")));
207 auto query = this->getQuery(sqlQueryString);
208 qDebug() << sqlQueryString;
209 return query.exec();
210}
211
212bool TAGDB::update(const QString &table, const QString &column, const QVariant &newValue, const QVariant &op, const QString &id) const
213{
214 auto queryStr = QString(QStringLiteral("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"")).arg(table, column, newValue.toString().replace(QStringLiteral("\""), QStringLiteral("\"\"")), op.toString(), id);
215 auto query = this->getQuery(queryStr);
216 return query.exec();
217}
218
219bool TAGDB::remove(const QString &tableName, const FMH::MODEL &removeData) const
220{
221 if (tableName.isEmpty()) {
222 qDebug() << QStringLiteral("Fatal error on removing! The table name is empty!");
223 return false;
224
225 } else if (removeData.isEmpty()) {
226 qDebug() << QStringLiteral("Fatal error on insert! The removeData is empty!");
227 return false;
228 }
229
230 QString strValues;
231 auto i = 0;
232 const auto keys = removeData.keys();
233 for (const auto &key : keys) {
234 strValues.append(QString(QStringLiteral("%1 = \"%2\"")).arg(FMH::MODEL_NAME[key], removeData[key]));
235 i++;
236
237 if (removeData.size() > 1 && i < removeData.size())
238 {
239 strValues.append(QStringLiteral(" AND "));
240 }
241 }
242
243 QString sqlQueryString = QStringLiteral("DELETE FROM ") + tableName + QStringLiteral(" WHERE ") + strValues;
244 qDebug() << sqlQueryString;
245
246 return this->getQuery(sqlQueryString).exec();
247}
248
249const QSqlDatabase & TAGDB::db() const
250{
251 return this->m_db;
252}
bool update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where) const
Update data in the database.
Definition tagdb.cpp:182
bool checkExistance(const QString &tableName, const QString &searchId, const QString &search) const
Check for the existence of an entry.
Definition tagdb.cpp:120
QSqlQuery getQuery() const
Return an empty query object to use arbitrary with any query.
Definition tagdb.cpp:146
bool insert(const QString &tableName, const QVariantMap &insertData) const
Insert data into the given table.
Definition tagdb.cpp:152
bool remove(const QString &tableName, const FMH::MODEL &removeData) const
remove
Definition tagdb.cpp:219
std::optional< QSqlQuery > query(const QString &queryStatement)
bool fileExists(const QUrl &path)
static const QHash< MODEL_KEY, QString > MODEL_NAME
QString name(StandardAction id)
std::string toStdString() const const
QByteArray trimmed() const const
bool isEmpty() const const
QList< Key > keys() const const
qsizetype size() const const
void append(QList< T > &&value)
const_reference at(qsizetype i) const const
void clear()
qsizetype size() const const
QSqlDatabase addDatabase(QSqlDriver *driver, const QString &connectionName)
QString connectionName() const const
bool contains(const QString &connectionName)
bool isOpen() const const
QSqlError lastError() const const
void setDatabaseName(const QString &name)
QString text() const const
bool exec()
QString & append(QChar ch)
QString arg(Args &&... args) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
QString fromStdString(const std::string &str)
bool isEmpty() const const
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
QString join(QChar separator) const const
QUrl fromLocalFile(const QString &localFile)
QUuid createUuid()
QString toString(StringFormat mode) const const
QString toString() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Sat Dec 21 2024 16:58:02 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.