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()
32 : QObject(nullptr)
33{
34 QDir collectionDBPath_dir(TAG::TaggingPath);
35 if (!collectionDBPath_dir.exists())
36 collectionDBPath_dir.mkpath(QStringLiteral("."));
37
39 if (!FMH::fileExists(QUrl::fromLocalFile(TAG::TaggingPath + TAG::DBName))) {
40 this->openDB(this->name);
41 qDebug() << "Collection doesn't exists, trying to create it" << TAG::TaggingPath + TAG::DBName;
42 this->prepareCollectionDB();
43 } else
44 this->openDB(this->name);
45}
46
47TAGDB::~TAGDB()
48{
49 qDebug() << "CLOSING THE TAGGING DATA BASE";
50 this->m_db.close();
51}
52
53void TAGDB::openDB(const QString &name)
54{
55 if (!QSqlDatabase::contains(name)) {
56 this->m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), name);
57 this->m_db.setDatabaseName(TAG::TaggingPath + TAG::DBName);
58 }
59
60 if (!this->m_db.isOpen()) {
61 if (!this->m_db.open())
62 qDebug() << "ERROR OPENING DB" << this->m_db.lastError().text() << m_db.connectionName();
63 }
64 auto query = this->getQuery(QStringLiteral("PRAGMA synchronous=OFF"));
65 query.exec();
66}
67
68void TAGDB::prepareCollectionDB() const
69{
70 QSqlQuery query(this->m_db);
71
72 QFile file(QStringLiteral(":/script.sql"));
73
74 if (!file.exists()) {
75 QString log = QStringLiteral("Fatal error on build database. The file '");
76 log.append(file.fileName() + QStringLiteral("' for database and tables creation query cannot be not found!"));
77 qDebug() << log;
78 return;
79 }
80
81 if (!file.open(QIODevice::ReadOnly)) {
82 qDebug() << QStringLiteral("Fatal error on try to create database! The file with sql queries for database creation cannot be opened!");
83 return;
84 }
85
86 bool hasText;
87 QString line;
88 QByteArray readLine;
89 QString cleanedLine;
90 QStringList strings;
91
92 while (!file.atEnd()) {
93 hasText = false;
94 line = QStringLiteral("");
95 readLine = "";
96 cleanedLine = QStringLiteral("");
97 strings.clear();
98 while (!hasText) {
99 readLine = file.readLine();
100 cleanedLine = QString::fromStdString(readLine.trimmed().toStdString());
101 strings = cleanedLine.split(QStringLiteral("--"));
102 cleanedLine = strings.at(0);
103 if (!cleanedLine.startsWith(QStringLiteral("--")) && !cleanedLine.startsWith(QStringLiteral("DROP")) && !cleanedLine.isEmpty())
104 line += cleanedLine;
105 if (cleanedLine.endsWith(QStringLiteral(";")))
106 break;
107 if (cleanedLine.startsWith(QStringLiteral("COMMIT")))
108 hasText = true;
109 }
110 if (!line.isEmpty()) {
111 if (!query.exec(line)) {
112 qDebug() << "exec failed" << query.lastQuery() << query.lastError();
113 }
114
115 } else
116 qDebug() << "exec wrong" << query.lastError();
117 }
118 file.close();
119}
120
121bool TAGDB::checkExistance(const QString &tableName, const QString &searchId, const QString &search) const
122{
123 const auto queryStr = QString(QStringLiteral("SELECT %1 FROM %2 WHERE %3 = \"%4\"")).arg(searchId, tableName, searchId, search);
124 return this->checkExistance(queryStr);
125}
126
127bool TAGDB::checkExistance(const QString &queryStr) const
128{
129 qDebug() << "CHECKIGN QUERY TAG" << queryStr;
130 auto query = this->getQuery(queryStr);
131
132 if (query.exec()) {
133 if (query.next())
134 return true;
135 } else
136 qDebug() << query.lastError().text();
137
138 return false;
139}
140
141QSqlQuery TAGDB::getQuery(const QString &queryTxt) const
142{
143 QSqlQuery query(queryTxt, this->m_db);
144 return query;
145}
146
148{
149 QSqlQuery query(this->m_db);
150 return query;
151}
152
153bool TAGDB::insert(const QString &tableName, const QVariantMap &insertData) const
154{
155 if (tableName.isEmpty()) {
156 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
157 return false;
158
159 } else if (insertData.isEmpty()) {
160 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
161 return false;
162 }
163
164 QStringList strValues;
165 QStringList fields = insertData.keys();
166 QVariantList values = insertData.values();
167 int totalFields = fields.size();
168 for (int i = 0; i < totalFields; ++i)
169 strValues.append(QStringLiteral("?"));
170
171 QString sqlQueryString = QStringLiteral("INSERT INTO ") + tableName + QStringLiteral(" (") + QString(fields.join(QStringLiteral(","))) + QStringLiteral(") VALUES(") + QString(strValues.join(QStringLiteral(","))) + QStringLiteral(")");
172 QSqlQuery query(this->m_db);
173 query.prepare(sqlQueryString);
174
175 int k = 0;
176
177 for(const QVariant &value : values)
178 query.bindValue(k++, value);
179
180 return query.exec();
181}
182
183bool TAGDB::update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where) const
184{
185 if (tableName.isEmpty()) {
186 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
187 return false;
188 } else if (updateData.isEmpty()) {
189 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
190 return false;
191 }
192
193 QStringList set;
194 const auto updateKeys = updateData.keys();
195 for (const auto &key : updateKeys)
196 {
197 set.append(FMH::MODEL_NAME[key] + QStringLiteral(" = '") + updateData[key] + QStringLiteral("'"));
198 }
199
200 QStringList condition;
201 const auto whereKeys = where.keys();
202 for (const auto &key : whereKeys)
203 {
204 condition.append(key + QStringLiteral(" = '") + where[key].toString() + QStringLiteral("'"));
205 }
206
207 QString sqlQueryString = QStringLiteral("UPDATE ") + tableName + QStringLiteral(" SET ") + QString(set.join(QStringLiteral(","))) + QStringLiteral(" WHERE ") + QString(condition.join(QStringLiteral(",")));
208 auto query = this->getQuery(sqlQueryString);
209 qDebug() << sqlQueryString;
210 return query.exec();
211}
212
213bool TAGDB::update(const QString &table, const QString &column, const QVariant &newValue, const QVariant &op, const QString &id) const
214{
215 auto queryStr = QString(QStringLiteral("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"")).arg(table, column, newValue.toString().replace(QStringLiteral("\""), QStringLiteral("\"\"")), op.toString(), id);
216 auto query = this->getQuery(queryStr);
217 return query.exec();
218}
219
220bool TAGDB::remove(const QString &tableName, const FMH::MODEL &removeData) const
221{
222 if (tableName.isEmpty()) {
223 qDebug() << QStringLiteral("Fatal error on removing! The table name is empty!");
224 return false;
225
226 } else if (removeData.isEmpty()) {
227 qDebug() << QStringLiteral("Fatal error on insert! The removeData is empty!");
228 return false;
229 }
230
231 QString strValues;
232 auto i = 0;
233 const auto keys = removeData.keys();
234 for (const auto &key : keys) {
235 strValues.append(QString(QStringLiteral("%1 = \"%2\"")).arg(FMH::MODEL_NAME[key], removeData[key]));
236 i++;
237
238 if (removeData.size() > 1 && i < removeData.size())
239 {
240 strValues.append(QStringLiteral(" AND "));
241 }
242 }
243
244 QString sqlQueryString = QStringLiteral("DELETE FROM ") + tableName + QStringLiteral(" WHERE ") + strValues;
245 qDebug() << sqlQueryString;
246
247 return this->getQuery(sqlQueryString).exec();
248}
249
250const QSqlDatabase & TAGDB::db() const
251{
252 return this->m_db;
253}
bool update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where) const
Update data in the database.
Definition tagdb.cpp:183
bool checkExistance(const QString &tableName, const QString &searchId, const QString &search) const
Check for the existence of an entry.
Definition tagdb.cpp:121
QSqlQuery getQuery() const
Return an empty query object to use arbitrary with any query.
Definition tagdb.cpp:147
bool insert(const QString &tableName, const QVariantMap &insertData) const
Insert data into the given table.
Definition tagdb.cpp:153
bool remove(const QString &tableName, const FMH::MODEL &removeData) const
remove
Definition tagdb.cpp:220
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 Fri May 17 2024 11:51:27 by doxygen 1.10.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.