From d2712e5293d82ea1229fa2c9d2dd27cfc47f9c7c Mon Sep 17 00:00:00 2001 From: Albert S Date: Tue, 16 Apr 2019 08:47:30 +0200 Subject: [PATCH] Added databasefactory to create database connections --- cli/databasefactory.cpp | 39 +++++++++++++++++++++++++++++++++++++++ cli/databasefactory.h | 16 ++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 cli/databasefactory.cpp create mode 100644 cli/databasefactory.h diff --git a/cli/databasefactory.cpp b/cli/databasefactory.cpp new file mode 100644 index 0000000..9625e56 --- /dev/null +++ b/cli/databasefactory.cpp @@ -0,0 +1,39 @@ +#include +#include "databasefactory.h" +#include "logger.h" +DatabaseFactory::DatabaseFactory(QString connectionString) +{ + this->connectionString = connectionString; +} +static QThreadStorage dbStore; + +//TODO: not threadsafe +QSqlDatabase DatabaseFactory::createNew() +{ + static int counter = 0; + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "QSS" + QString::number(counter++)); + db.setDatabaseName(this->connectionString); + if(!db.open()) + { + Logger::error() << "Failed to open the database: " << this->connectionString << endl; + throw QSSGeneralException("Failed to create open new connection"); + } + return db; +} + +QSqlDatabase DatabaseFactory::forCurrentThread() +{ + if(dbStore.hasLocalData()) + { + return dbStore.localData(); + } + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "QSS" + QString::number((quint64)QThread::currentThread(), 16)); + db.setDatabaseName(this->connectionString); + if(!db.open()) + { + Logger::error() << "Failed to open the database: " << this->connectionString << endl; + throw QSSGeneralException("Failed to create open new connection"); + } + dbStore.setLocalData(db); + return db; +} diff --git a/cli/databasefactory.h b/cli/databasefactory.h new file mode 100644 index 0000000..909e0aa --- /dev/null +++ b/cli/databasefactory.h @@ -0,0 +1,16 @@ +#ifndef DATABASEFACTORY_H +#define DATABASEFACTORY_H +#include +#include +#include "utils.h" +class DatabaseFactory +{ +private: + QString connectionString; +public: + DatabaseFactory(QString connectionString); + QSqlDatabase createNew(); + QSqlDatabase forCurrentThread(); +}; + +#endif // DATABASEFACTORY_H