MauiKit Accounts

accountsdb.cpp
1#include "accountsdb.h"
2
3#include <QUuid>
4#include <QStandardPaths>
5
6#ifdef Q_OS_ANDROID
7#include "mauiandroid.h"
8#endif
9
11const static QString DBName = "accounts.db";
12const static QUrl DBPath = QUrl(DBDir.toString()+"/"+DBName);
13
14AccountsDB::AccountsDB(QObject *parent)
15 : QObject(parent)
16{
17 // get permissions to read and write
18#ifdef Q_OS_ANDROID
19 MAUIAndroid::checkRunTimePermissions({"android.permission.WRITE_EXTERNAL_STORAGE"});
20#endif
21
22 QDir collectionDBPath_dir(DBDir.toLocalFile());
23 if (!collectionDBPath_dir.exists())
24 collectionDBPath_dir.mkpath(".");
25
27 if (!FMH::fileExists(DBPath)) {
28 this->openDB(this->name);
29 this->prepareCollectionDB();
30 } else
31 this->openDB(this->name);
32}
33
34AccountsDB::~AccountsDB()
35{
36 this->m_db.close();
37}
38
39void AccountsDB::openDB(const QString &name)
40{
41 if (!QSqlDatabase::contains(name)) {
42 this->m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), name);
43 this->m_db.setDatabaseName(DBPath.toLocalFile());
44 }
45
46 if (!this->m_db.isOpen()) {
47 if (!this->m_db.open())
48 qDebug() << "ERROR OPENING DB" << this->m_db.lastError().text() << m_db.connectionName();
49 }
50 auto query = this->getQuery("PRAGMA synchronous=OFF");
51 query.exec();
52}
53
54void AccountsDB::prepareCollectionDB() const
55{
56 QSqlQuery query(this->m_db);
57
58 QFile file(":/accounts/script.sql");
59
60 if (!file.exists()) {
61 QString log = QStringLiteral("Fatal error on build database. The file '");
62 log.append(file.fileName() + QStringLiteral("' for database and tables creation query cannot be not found!"));
63 qDebug() << log;
64 return;
65 }
66
67 if (!file.open(QIODevice::ReadOnly)) {
68 qDebug() << QStringLiteral("Fatal error on try to create database! The file with sql queries for database creation cannot be opened!");
69 return;
70 }
71
72 bool hasText;
73 QString line;
74 QByteArray readLine;
75 QString cleanedLine;
76 QStringList strings;
77
78 while (!file.atEnd()) {
79 hasText = false;
80 line = "";
81 readLine = "";
82 cleanedLine = "";
83 strings.clear();
84 while (!hasText) {
85 readLine = file.readLine();
86 cleanedLine = readLine.trimmed();
87 strings = cleanedLine.split("--");
88 cleanedLine = strings.at(0);
89 if (!cleanedLine.startsWith("--") && !cleanedLine.startsWith("DROP") && !cleanedLine.isEmpty())
90 line += cleanedLine;
91 if (cleanedLine.endsWith(";"))
92 break;
93 if (cleanedLine.startsWith("COMMIT"))
94 hasText = true;
95 }
96 if (!line.isEmpty()) {
97 if (!query.exec(line)) {
98 qDebug() << "exec failed" << query.lastQuery() << query.lastError();
99 }
100
101 } else
102 qDebug() << "exec wrong" << query.lastError();
103 }
104 file.close();
105}
106
107bool AccountsDB::checkExistance(const QString &tableName, const QString &searchId, const QString &search)
108{
109 auto queryStr = QString("SELECT %1 FROM %2 WHERE %3 = \"%4\"").arg(searchId, tableName, searchId, search);
110 auto query = this->getQuery(queryStr);
111
112 if (query.exec()) {
113 if (query.next())
114 return true;
115 } else
116 qDebug() << query.lastError().text();
117
118 return false;
119}
120
121bool AccountsDB::checkExistance(const QString &queryStr)
122{
123 auto query = this->getQuery(queryStr);
124
125 if (query.exec()) {
126 if (query.next())
127 return true;
128 } else
129 qDebug() << query.lastError().text();
130
131 return false;
132}
133
134QSqlQuery AccountsDB::getQuery(const QString &queryTxt)
135{
136 QSqlQuery query(queryTxt, this->m_db);
137 return query;
138}
139
140bool AccountsDB::insert(const QString &tableName, const QVariantMap &insertData)
141{
142 if (tableName.isEmpty()) {
143 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
144 return false;
145
146 } else if (insertData.isEmpty()) {
147 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
148 return false;
149 }
150
151 QStringList strValues;
152 QStringList fields = insertData.keys();
153 QVariantList values = insertData.values();
154 int totalFields = fields.size();
155 for (int i = 0; i < totalFields; ++i)
156 strValues.append("?");
157
158 QString sqlQueryString = "INSERT INTO " + tableName + " (" + QString(fields.join(",")) + ") VALUES(" + QString(strValues.join(",")) + ")";
159 QSqlQuery query(this->m_db);
160 query.prepare(sqlQueryString);
161
162 int k = 0;
163 for (const QVariant &value : values)
164 query.bindValue(k++, value);
165
166 return query.exec();
167}
168
169bool AccountsDB::update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where)
170{
171 if (tableName.isEmpty()) {
172 qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
173 return false;
174 } else if (updateData.isEmpty()) {
175 qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
176 return false;
177 }
178
179 QStringList set;
180 const auto updateKeys = updateData.keys();
181 for (const auto &key : updateKeys)
182 set.append(FMH::MODEL_NAME[key] + " = '" + updateData[key] + "'");
183
184 QStringList condition;
185 const auto keys = where.keys();
186 for (const auto &key : keys)
187 condition.append(key + " = '" + where[key].toString() + "'");
188
189 QString sqlQueryString = "UPDATE " + tableName + " SET " + QString(set.join(",")) + " WHERE " + QString(condition.join(","));
190 auto query = this->getQuery(sqlQueryString);
191 qDebug() << sqlQueryString;
192 return query.exec();
193}
194
195bool AccountsDB::update(const QString &table, const QString &column, const QVariant &newValue, const QVariant &op, const QString &id)
196{
197 auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"").arg(table, column, newValue.toString().replace("\"", "\"\""), op.toString(), id);
198 auto query = this->getQuery(queryStr);
199 return query.exec();
200}
201
202bool AccountsDB::remove(const QString &tableName, const FMH::MODEL &removeData)
203{
204 if (tableName.isEmpty()) {
205 qDebug() << QStringLiteral("Fatal error on removing! The table name is empty!");
206 return false;
207
208 } else if (removeData.isEmpty()) {
209 qDebug() << QStringLiteral("Fatal error on insert! The removeData is empty!");
210 return false;
211 }
212
213 QString strValues;
214 auto i = 0;
215 const auto keys = removeData.keys();
216 for (const auto &key : keys) {
217 strValues.append(QString("%1 = \"%2\"").arg(FMH::MODEL_NAME[key], removeData[key]));
218 i++;
219
220 if (keys.size() > 1 && i < keys.size())
221 {
222 strValues.append(" AND ");
223 }
224 }
225
226 QString sqlQueryString = "DELETE FROM " + tableName + " WHERE " + strValues;
227 qDebug() << sqlQueryString;
228
229 return this->getQuery(sqlQueryString).exec();
230}
char * toString(const EngineQuery &query)
bool fileExists(const QUrl &path)
static const QHash< MODEL_KEY, QString > MODEL_NAME
KSERVICE_EXPORT KService::List query(FilterFunc filterFunc)
QString name(StandardAction id)
QByteArray trimmed() const const
bool isEmpty() const const
QList< Key > keys() 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 writableLocation(StandardLocation type)
QString & append(QChar ch)
QString arg(Args &&... args) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
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)
QString toLocalFile() const const
QString toString(FormattingOptions options) const const
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 Mon Nov 18 2024 12:10:56 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.