File indexing completed on 2024-04-14 04:39:39

0001 #include "accountsdb.h"
0002 
0003 #include <QUuid>
0004 #include <QStandardPaths>
0005 
0006 #ifdef Q_OS_ANDROID
0007 #include "mauiandroid.h"
0008 #endif
0009 
0010 const static QUrl DBDir = QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/maui/");
0011 const static QString DBName = "accounts.db";
0012 const static QUrl DBPath = QUrl(DBDir.toString()+"/"+DBName);
0013 
0014 AccountsDB::AccountsDB(QObject *parent)
0015     : QObject(parent)
0016 {
0017     // get permissions to read and write
0018 #ifdef Q_OS_ANDROID
0019     MAUIAndroid::checkRunTimePermissions({"android.permission.WRITE_EXTERNAL_STORAGE"});
0020 #endif
0021 
0022     QDir collectionDBPath_dir(DBDir.toLocalFile());
0023     if (!collectionDBPath_dir.exists())
0024         collectionDBPath_dir.mkpath(".");
0025 
0026     this->name = QUuid::createUuid().toString();
0027     if (!FMH::fileExists(DBPath)) {
0028         this->openDB(this->name);
0029         this->prepareCollectionDB();
0030     } else
0031         this->openDB(this->name);
0032 }
0033 
0034 AccountsDB::~AccountsDB()
0035 {
0036     this->m_db.close();
0037 }
0038 
0039 void AccountsDB::openDB(const QString &name)
0040 {
0041     if (!QSqlDatabase::contains(name)) {
0042         this->m_db = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), name);
0043         this->m_db.setDatabaseName(DBPath.toLocalFile());
0044     }
0045 
0046     if (!this->m_db.isOpen()) {
0047         if (!this->m_db.open())
0048             qDebug() << "ERROR OPENING DB" << this->m_db.lastError().text() << m_db.connectionName();
0049     }
0050     auto query = this->getQuery("PRAGMA synchronous=OFF");
0051     query.exec();
0052 }
0053 
0054 void AccountsDB::prepareCollectionDB() const
0055 {
0056     QSqlQuery query(this->m_db);
0057 
0058     QFile file(":/accounts/script.sql");
0059 
0060     if (!file.exists()) {
0061         QString log = QStringLiteral("Fatal error on build database. The file '");
0062         log.append(file.fileName() + QStringLiteral("' for database and tables creation query cannot be not found!"));
0063         qDebug() << log;
0064         return;
0065     }
0066 
0067     if (!file.open(QIODevice::ReadOnly)) {
0068         qDebug() << QStringLiteral("Fatal error on try to create database! The file with sql queries for database creation cannot be opened!");
0069         return;
0070     }
0071 
0072     bool hasText;
0073     QString line;
0074     QByteArray readLine;
0075     QString cleanedLine;
0076     QStringList strings;
0077 
0078     while (!file.atEnd()) {
0079         hasText = false;
0080         line = "";
0081         readLine = "";
0082         cleanedLine = "";
0083         strings.clear();
0084         while (!hasText) {
0085             readLine = file.readLine();
0086             cleanedLine = readLine.trimmed();
0087             strings = cleanedLine.split("--");
0088             cleanedLine = strings.at(0);
0089             if (!cleanedLine.startsWith("--") && !cleanedLine.startsWith("DROP") && !cleanedLine.isEmpty())
0090                 line += cleanedLine;
0091             if (cleanedLine.endsWith(";"))
0092                 break;
0093             if (cleanedLine.startsWith("COMMIT"))
0094                 hasText = true;
0095         }
0096         if (!line.isEmpty()) {
0097             if (!query.exec(line)) {
0098                 qDebug() << "exec failed" << query.lastQuery() << query.lastError();
0099             }
0100 
0101         } else
0102             qDebug() << "exec wrong" << query.lastError();
0103     }
0104     file.close();
0105 }
0106 
0107 bool AccountsDB::checkExistance(const QString &tableName, const QString &searchId, const QString &search)
0108 {
0109     auto queryStr = QString("SELECT %1 FROM %2 WHERE %3 = \"%4\"").arg(searchId, tableName, searchId, search);
0110     auto query = this->getQuery(queryStr);
0111 
0112     if (query.exec()) {
0113         if (query.next())
0114             return true;
0115     } else
0116         qDebug() << query.lastError().text();
0117 
0118     return false;
0119 }
0120 
0121 bool AccountsDB::checkExistance(const QString &queryStr)
0122 {
0123     auto query = this->getQuery(queryStr);
0124 
0125     if (query.exec()) {
0126         if (query.next())
0127             return true;
0128     } else
0129         qDebug() << query.lastError().text();
0130 
0131     return false;
0132 }
0133 
0134 QSqlQuery AccountsDB::getQuery(const QString &queryTxt)
0135 {
0136     QSqlQuery query(queryTxt, this->m_db);
0137     return query;
0138 }
0139 
0140 bool AccountsDB::insert(const QString &tableName, const QVariantMap &insertData)
0141 {
0142     if (tableName.isEmpty()) {
0143         qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
0144         return false;
0145 
0146     } else if (insertData.isEmpty()) {
0147         qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
0148         return false;
0149     }
0150 
0151     QStringList strValues;
0152     QStringList fields = insertData.keys();
0153     QVariantList values = insertData.values();
0154     int totalFields = fields.size();
0155     for (int i = 0; i < totalFields; ++i)
0156         strValues.append("?");
0157 
0158     QString sqlQueryString = "INSERT INTO " + tableName + " (" + QString(fields.join(",")) + ") VALUES(" + QString(strValues.join(",")) + ")";
0159     QSqlQuery query(this->m_db);
0160     query.prepare(sqlQueryString);
0161 
0162     int k = 0;
0163     for (const QVariant &value : values)
0164         query.bindValue(k++, value);
0165 
0166     return query.exec();
0167 }
0168 
0169 bool AccountsDB::update(const QString &tableName, const FMH::MODEL &updateData, const QVariantMap &where)
0170 {
0171     if (tableName.isEmpty()) {
0172         qDebug() << QStringLiteral("Fatal error on insert! The table name is empty!");
0173         return false;
0174     } else if (updateData.isEmpty()) {
0175         qDebug() << QStringLiteral("Fatal error on insert! The insertData is empty!");
0176         return false;
0177     }
0178 
0179     QStringList set;
0180     const auto updateKeys = updateData.keys();
0181     for (const auto &key : updateKeys)
0182         set.append(FMH::MODEL_NAME[key] + " = '" + updateData[key] + "'");
0183 
0184     QStringList condition;
0185     const auto keys = where.keys();
0186     for (const auto &key : keys)
0187         condition.append(key + " = '" + where[key].toString() + "'");
0188 
0189     QString sqlQueryString = "UPDATE " + tableName + " SET " + QString(set.join(",")) + " WHERE " + QString(condition.join(","));
0190     auto query = this->getQuery(sqlQueryString);
0191     qDebug() << sqlQueryString;
0192     return query.exec();
0193 }
0194 
0195 bool AccountsDB::update(const QString &table, const QString &column, const QVariant &newValue, const QVariant &op, const QString &id)
0196 {
0197     auto queryStr = QString("UPDATE %1 SET %2 = \"%3\" WHERE %4 = \"%5\"").arg(table, column, newValue.toString().replace("\"", "\"\""), op.toString(), id);
0198     auto query = this->getQuery(queryStr);
0199     return query.exec();
0200 }
0201 
0202 bool AccountsDB::remove(const QString &tableName, const FMH::MODEL &removeData)
0203 {
0204     if (tableName.isEmpty()) {
0205         qDebug() << QStringLiteral("Fatal error on removing! The table name is empty!");
0206         return false;
0207 
0208     } else if (removeData.isEmpty()) {
0209         qDebug() << QStringLiteral("Fatal error on insert! The removeData is empty!");
0210         return false;
0211     }
0212 
0213     QString strValues;
0214     auto i = 0;
0215     const auto keys = removeData.keys();
0216     for (const auto &key : keys) {
0217         strValues.append(QString("%1 = \"%2\"").arg(FMH::MODEL_NAME[key], removeData[key]));
0218         i++;
0219 
0220         if (keys.size() > 1 && i < keys.size())
0221         {
0222              strValues.append(" AND ");
0223         }
0224     }
0225 
0226     QString sqlQueryString = "DELETE FROM " + tableName + " WHERE " + strValues;
0227     qDebug() << sqlQueryString;
0228 
0229     return this->getQuery(sqlQueryString).exec();
0230 }