Commit 4af312b7 authored by Martin Straka's avatar Martin Straka

Database code refactoring

parent dd5e7167
......@@ -92,8 +92,6 @@ SOURCES += \
src/dialogues/widget_message_dialogue.cpp \
src/files.cpp \
src/io/filesystem.cpp \
src/io/sqlite/db.cpp \
src/io/sqlite/table.cpp \
src/isds/isds_conversion.cpp \
src/locker.cpp \
src/log/log.cpp \
......@@ -115,12 +113,14 @@ SOURCES += \
src/settings.cpp \
src/setwrapper.cpp \
src/sqlite/account_db.cpp \
src/sqlite/db.cpp \
src/sqlite/dbs.cpp \
src/sqlite/db_tables.cpp \
src/sqlite/file_db_container.cpp \
src/sqlite/file_db.cpp \
src/sqlite/message_db_container.cpp \
src/sqlite/message_db.cpp \
src/sqlite/table.cpp \
src/sqlite/zfo_db.cpp \
src/worker/emitter.cpp \
src/worker/pool.cpp \
......@@ -147,8 +147,6 @@ HEADERS += \
src/dialogues/widget_message_dialogue.h \
src/files.h \
src/io/filesystem.h \
src/io/sqlite/db.h \
src/io/sqlite/table.h \
src/isds/isds_conversion.h \
src/locker.h \
src/log/log.h \
......@@ -170,12 +168,14 @@ HEADERS += \
src/settings.h \
src/setwrapper.h \
src/sqlite/account_db.h \
src/sqlite/db.h \
src/sqlite/dbs.h \
src/sqlite/db_tables.h \
src/sqlite/file_db_container.h \
src/sqlite/file_db.h \
src/sqlite/message_db_container.h \
src/sqlite/message_db.h \
src/sqlite/table.h \
src/sqlite/zfo_db.h \
src/worker/emitter.h \
src/worker/pool.h \
......
......@@ -331,6 +331,17 @@ int main(int argc, char *argv[])
evntsTbl.reloadLocalisedDescription();
msgZfoTbl.reloadLocalisedDescription();
/* Load accounts from settings to account model. */
{
QSettings settings(Settings::settingsPath(),
QSettings::IniFormat);
accountModelPtr->loadAccountsFromSettings(settings);
/*
* No need to load counters here as some messages are likely
* to be deleted.
*/
}
/* init and open account database */
AccountDb globAccountDb("ACCOUNTS");
globAccountDbPtr = &globAccountDb;
......@@ -353,17 +364,6 @@ int main(int argc, char *argv[])
ZfoDb globZfoDb("ZFOS");
globZfoDbPtr = &globZfoDb;
/* Load accounts from settings to account model. */
{
QSettings settings(Settings::settingsPath(),
QSettings::IniFormat);
accountModelPtr->loadAccountsFromSettings(settings);
/*
* No need to load counters here as some messages are likely
* to be deleted.
*/
}
/*
* Open ZFO database, the second parameter means: true = zfo db will
* store in disk, false = only in memory
......
This diff is collapsed.
......@@ -27,8 +27,8 @@
#include <QList>
#include <QString>
#include "src/io/sqlite/db.h"
#include "src/net/db_wrapper.h"
#include "src/sqlite/db.h"
/*!
* @brief Encapsulates account database.
......@@ -39,57 +39,91 @@ public:
explicit AccountDb(const QString &connectionName);
/*!
* @brief Open database file.
*/
bool openDb(const QString &fileName, bool storeToDisk);
/*!
* @brief Return data box identifier.
*
* @param[in] userName Account user name.
* @param[in] defaultValue Default value.
* @return Databox id string.
*/
const QString dbId(const QString &userName,
const QString &defaultValue = QString()) const;
/*!
* @brief Return sender name guess.
* @brief Delete account info from db.
*
* @param[in] userName Account user name.
* @return True on success.
*/
const QString senderNameGuess(const QString &userName,
const QString &defaultValue = QString()) const;
bool deleteAccountInfoFromDb(const QString &userName) const;
/*!
* @brief Update pwd expiration in db
* @brief Delete user info from db.
*
* @param[in] userName Account user name.
* @return List of user info. * @return True on success.
*/
bool updatePwdExpirInDb(const QString &userName, const QString &date);
bool deleteUserInfoFromDb(const QString &userName) const;
/*!
* @brief Insert account info into db
* @brief Get user info from db.
*
* @param[in] userName Account user name.
* @return List of user info.
*/
bool insertAccountInfoIntoDb(const DbWrapper::AccountInfo &accountData);
QStringList getUserDataboxInfo(const QString &userName) const;
/*!
* @brief delete account info from db
* @brief Get account info and user info from db as html text.
*
* @param[in] userName Account user name.
* @return Html string of account detail.
*/
bool deleteAccountInfoFromDb(const QString &userName) const;
QString getAccountDetail(const QString &userName) const;
/*!
* @brief Insert user info into db
* @brief Insert account info into db.
*
* @param[in] accountData Account (owner) info structure.
* @return True on success.
*/
bool insertAccountInfoIntoDb(const DbWrapper::AccountInfo &accountData);
/*!
* @brief Insert user info into db.
*
* @param[in] userData User info structure.
* @return True on success.
*/
bool insertUserInfoIntoDb(const DbWrapper::UserInfo &userData);
/*!
* @brief delete user info from db
* @brief Open database file.
*
* @param[in] userName Account user name.
* @param[in] storeToDisk True if db is store on the local storage.
* @return True on success.
*/
bool deleteUserInfoFromDb(const QString &userName) const;
bool openDb(const QString &fileName, bool storeToDisk);
/*!
* @brief Get user info from db.
* @brief Return sender name guess.
*
* @param[in] userName Account user name.
* @param[in] defaultValue Default value.
* @return Guess name string.
*/
QStringList getUserDataboxInfo(const QString &userName) const;
const QString senderNameGuess(const QString &userName,
const QString &defaultValue = QString()) const;
/*!
* @brief Get account info and user info from db as html text.
* @brief Update pwd expiration in db.
*
* @param[in] userName Account user name.
* @param[in] date New expiration date.
* @return True on success.
*/
QString getAccountDetail(const QString &userName) const;
bool updatePwdExpirInDb(const QString &userName, const QString &date);
private:
......@@ -110,7 +144,7 @@ private:
};
/*!
* @brief Global account database.
* @brief Global account database pointer.
*/
extern AccountDb *globAccountDbPtr;
......
/*
* Copyright (C) 2014-2016 CZ.NIC
* Copyright (C) 2014-2017 CZ.NIC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -21,14 +21,15 @@
* the two.
*/
#include <QDebug>
#include <QDir>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include "src/io/sqlite/db.h"
#include "src/io/sqlite/table.h"
#include "src/log/log.h"
#include "src/sqlite/db.h"
#include "src/sqlite/table.h"
const QString SQLiteDb::memoryLocation(":memory:");
const QString SQLiteDb::dbDriverType("QSQLITE");
......@@ -48,35 +49,6 @@ QString SQLiteDb::fileName(void) const
return m_db.databaseName();
}
bool SQLiteDb::openDb(const QString &fileName, bool forceInMemory,
const QList<class SQLiteTbl *> &tables)
{
bool ret;
if (m_db.isOpen()) {
m_db.close();
}
if (!forceInMemory) {
m_db.setDatabaseName(QDir::toNativeSeparators(fileName));
} else {
m_db.setDatabaseName(memoryLocation);
}
ret = m_db.open();
if (ret) {
/* Ensure database contains all tables. */
ret = createEmptyMissingTables(tables);
}
if (!ret) {
m_db.close();
}
return ret;
}
bool SQLiteDb::beginTransaction(void)
{
QSqlQuery query(m_db);
......@@ -202,7 +174,6 @@ bool SQLiteDb::rollbackTransaction(const QString &savePointName)
bool SQLiteDb::dbDriverSupport(void)
{
QStringList driversList = QSqlDatabase::drivers();
return driversList.contains(dbDriverType, Qt::CaseSensitive);
}
......@@ -211,80 +182,67 @@ void SQLiteDb::closeDb(void)
m_db.close();
}
bool SQLiteDb::checkDb(bool quick)
bool SQLiteDb::copyDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables)
{
QSqlQuery query(m_db);
bool ret = false;
bool copy_ret, open_ret;
QString queryStr;
if (quick) {
queryStr = "PRAGMA quick_check";
} else {
queryStr = "PRAGMA integrity_check";
}
if (!query.prepare(queryStr)) {
logErrorNL("Cannot prepare SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
}
if (query.exec() && query.isActive()) {
query.first();
if (query.isValid()) {
ret = query.value(0).toBool();
} else {
ret = false;
}
} else {
logErrorNL("Cannot execute SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
/* Close database. */
m_db.close();
/* Backup old file name. */
QString oldFileName = fileName();
QFileInfo fi(oldFileName);
QString fileName = fi.fileName();
QString newFileName =
newLocDir + QDir::separator() + QDir::toNativeSeparators(fileName);
/* Fail if target equals the source. */
/* TODO -- Perform a more reliable check than string comparison. */
if (oldFileName == newFileName) {
return false;
}
return ret;
/* Erase target if exists. */
QFile::remove(newFileName);
fail:
return false;
}
/* Copy database file. */
copy_ret = QFile::copy(oldFileName, newFileName);
bool SQLiteDb::attachDb2(QSqlQuery &query, const QString &attachFileName)
{
QString queryStr("ATTACH DATABASE :fileName AS " DB2);
if (!query.prepare(queryStr)) {
logErrorNL("Cannot prepare SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
}
query.bindValue(":fileName", attachFileName);
if (!query.exec()) {
logErrorNL("Cannot execute SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
/* Open database. */
open_ret = openDb(newFileName, true, tables);
if (!open_ret) {
Q_ASSERT(0);
return false;
}
return true;
fail:
return false;
return copy_ret;
}
bool SQLiteDb::detachDb2(QSqlQuery &query)
bool SQLiteDb::createDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables)
{
QString queryStr = "DETACH DATABASE " DB2;
if (!query.prepare(queryStr)) {
logErrorNL("Cannot prepare SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
}
if (!query.exec()) {
logErrorNL("Cannot execute SQL query: %s.",
query.lastError().text().toUtf8().constData());
goto fail;
/* Close database. */
m_db.close();
/* Backup old file name. */
QString oldFileName = fileName();
QFileInfo fi(oldFileName);
QString fileName = fi.fileName();
QString newFileName =
newLocDir + QDir::separator() + QDir::toNativeSeparators(fileName);
/* Fail if target equals the source. */
/* TODO -- Perform a more reliable check than string comparison. */
if (oldFileName == newFileName) {
return false;
}
return true;
/* Erase target if exists. */
QFile::remove(newFileName);
fail:
return false;
/* Open new database in the new location.*/
return openDb(newFileName, true, tables);
}
bool SQLiteDb::createEmptyMissingTables(const QList<class SQLiteTbl *> &tables)
......@@ -300,3 +258,127 @@ bool SQLiteDb::createEmptyMissingTables(const QList<class SQLiteTbl *> &tables)
fail:
return false;
}
bool SQLiteDb::deleteCurrentDbCreateNew(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables)
{
bool open_ret;
/* Close database. */
m_db.close();
/* Backup old file name. */
QString oldFileName = fileName();
QFileInfo fi(oldFileName);
QString fileName = fi.fileName();
QString newFileName =
newLocDir + QDir::separator() + QDir::toNativeSeparators(fileName);
/* Fail if target equals the source. */
/* TODO -- Perform a more reliable check than string comparison. */
if (oldFileName == newFileName) {
return false;
}
/* Erase target if exists. */
QFile::remove(newFileName);
/*
* Open database in the new location.
* If error durring opening of new dabatase, open back old database.
*/
open_ret = openDb(newFileName, true, tables);
if (!open_ret) {
open_ret = openDb(oldFileName, true, tables);
return false;
}
/* Delete file. */
return QFile::remove(oldFileName);
}
bool SQLiteDb::deleteDb(const QString &LocDir)
{
/* Close database. */
m_db.close();
/* Backup old file name. */
QString oldFileName = fileName();
QFileInfo fi(oldFileName);
QString fileName = fi.fileName();
QString newFileName =
LocDir + QDir::separator() + QDir::toNativeSeparators(fileName);
/* Erase target if exists. */
return QFile::remove(newFileName);
}
bool SQLiteDb::openDb(const QString &fileName, bool forceInMemory,
const QList<class SQLiteTbl *> &tables)
{
bool ret;
if (m_db.isOpen()) {
m_db.close();
}
if (!forceInMemory) {
m_db.setDatabaseName(QDir::toNativeSeparators(fileName));
} else {
m_db.setDatabaseName(memoryLocation);
}
ret = m_db.open();
if (ret) {
/* Ensure database contains all tables. */
ret = createEmptyMissingTables(tables);
}
if (!ret) {
m_db.close();
}
qDebug() << m_db.databaseName();
return ret;
}
bool SQLiteDb::moveDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables)
{
bool move_ret, open_ret;
/* Close database. */
m_db.close();
/* Backup old file name. */
QString oldFileName = fileName();
QFileInfo fi(oldFileName);
QString fileName = fi.fileName();
QString newFileName =
newLocDir + QDir::separator() + QDir::toNativeSeparators(fileName);
/* Fail if target equals the source. */
/* TODO -- Perform a more reliable check than string comparison. */
if (oldFileName == newFileName) {
return false;
}
/* Erase target if exists. */
QFile::remove(newFileName);
/* Move database file. */
move_ret = QFile::rename(oldFileName, newFileName);
/* Open database. */
open_ret = openDb(move_ret ? newFileName : oldFileName, true, tables);
if (!open_ret) {
Q_ASSERT(0);
return false;
}
return move_ret;
}
/*
* Copyright (C) 2014-2016 CZ.NIC
* Copyright (C) 2014-2017 CZ.NIC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -28,8 +28,6 @@
#include <QSqlDatabase>
#include <QString>
#define DB2 "db2"
/*!
* @brief Database prototype.
*/
......@@ -55,19 +53,6 @@ public:
*/
QString fileName(void) const;
/*!
* @brief Open database file.
*
* @param[in] fileName File name.
* @param[in] forceInMemory True if the message should be stored in
* memory only.
* @param[in] tables List of table prototypes that should be
* created if missing.
* @return True on success, false on any error.
*/
bool openDb(const QString &fileName, bool forceInMemory,
const QList<class SQLiteTbl *> &tables);
/*!
* @brief Begin a transaction.
*
......@@ -121,37 +106,78 @@ public:
bool dbDriverSupport(void);
protected:
/*!
* @brief Close database file.
*/
void closeDb(void);
/*!
* @brief Perform a database integrity check.
* @brief Copy db.
*
* @return False if check fails.
* @param[in] newLocDir New location name.
* @param[in] tables List of table prototypes that should be created
* if missing.
* @return True on success.
*
* @note The copy is continued to be used. Original is closed.
*/
bool checkDb(bool quick);
bool copyDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables);
/*!
* @brief Attaches a database file to opened database.
* @brief Create new database in the new location.
*
* @param[in,out] query Query to work with.
* @param[in] attachFileName File containing database to be
* attached.
* @return False on error.
* @param[in] newLocDir New location name.
* @param[in] tables List of table prototypes that should be created
* if missing.
* @return True on success.
*/
static
bool attachDb2(class QSqlQuery &query, const QString &attachFileName);
bool createDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables);
/*!
* @brief Delete current message db and create new in new location.
*
* @param[in] newLocDir New location name.
* @param[in] tables List of table prototypes that should be created
* if missing.
* @return True on success.
*/
bool deleteCurrentDbCreateNew(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables);
/*!
* @brief Detaches attached database file from opened database.
* @brief Delete database from location.
*
* @param[in,out] query Query to work with.
* @return False on error.
* @param[in] LocDir New location name.
* @return True on success.
*/
static
bool detachDb2(class QSqlQuery &query);
bool deleteDb(const QString &LocDir);
/*!
* @brief Move db.
*
* @param[in] newLocDir New location name.
* @param[in] tables List of table prototypes that should be created
* if missing.
* @return True on success.
*/
bool moveDb(const QString &newLocDir,
const QList<class SQLiteTbl *> &tables);
/*!
* @brief Open database file.
*
* @param[in] fileName File name.
* @param[in] forceInMemory True if the message should be stored in
* memory only.
* @param[in] tables List of table prototypes that should be
* created if missing.
* @return True on success, false on any error.
*/
bool openDb(const QString &fileName, bool forceInMemory,
const QList<class SQLiteTbl *> &tables);
QSqlDatabase m_db; /*!< Database. */
......
......@@ -24,7 +24,7 @@
#ifndef _DB_TABLES_H_
#define _DB_TABLES_H_
#include "src/io/sqlite/table.h"
#include "src/sqlite/table.h"
/*
* Account database.
......
/*
* Copyright (C) 2014-2016 CZ.NIC
* Copyright (C) 2014-2017 CZ.NIC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -24,8 +24,7 @@
#include <QDateTime>
#include <QString>
#include "dbs.h"
#include "src/sqlite/dbs.h"
/*!
* @brief Date/time format stored in db.
......@@ -36,13 +35,7 @@
static const QString dbDateTimeFormat("yyyy-MM-dd HH:mm:ss.zzz");
static const QString dbShortDateTimeFormat("yyyy-MM-dd HH:mm:ss");
/* ========================================================================= */
/*
* Converts date from database format into desired format if possible.
*/
QDateTime dateTimeFromDbFormat(const QString &dateTimeDbStr)
/* ========================================================================= */
{
QDateTime dateTime = QDateTime::fromString(dateTimeDbStr,
dbDateTimeFormat);
......@@ -50,14 +43,8 @@ QDateTime dateTimeFromDbFormat(const QString &dateTimeDbStr)
return dateTime.toLocalTime();
}
/* ========================================================================= */
/*
* Converts date from database format into desired format if possible.
*/
QString dateTimeStrFromDbFormat(const QString &dateTimeDbStr,
const QString &tgtFmt)
/* ========================================================================= */
{
QDateTime dateTime = dateTimeFromDbFormat(dateTimeDbStr);
......@@ -68,13 +55,7 @@ QString dateTimeStrFromDbFormat(const QString &dateTimeDbStr,
}
}
/* ========================================================================= */
/*
* Converts date and time to UTC for database store.
*/
QString dateTimeStrToUTCDbFormat(const QString &dateTimeStr)
/* ========================================================================= */
{
QDateTime dateTime = QDateTime::fromString(dateTimeStr, Qt::ISODate);
dateTime = dateTime.toTimeSpec(Qt::UTC);
......
/*
* Copyright (C) 2014-2016 CZ.NIC
* Copyright (C) 2014-2017 CZ.NIC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
......@@ -24,7 +24,6 @@
#ifndef _DBS_H_
#define _DBS_H_
#include <QDate>
#include <QDateTime>
#include <QString>
......@@ -36,7 +35,6 @@
*/
QDateTime dateTimeFromDbFormat(const QString &dateTimeDbStr);
/*!
* @brief Converts date and time from database format into desired format if
* possible.
......@@ -44,7 +42,6 @@ QDateTime dateTimeFromDbFormat(const QString &dateTimeDbStr);
QString dateTimeStrFromDbFormat(const QString &dateTimeDbStr,
const QString &tgtFmt);