From c676b640f1153ecd61c3152a3cf98563cc0c5bd7 Mon Sep 17 00:00:00 2001 From: Paulchen-Panther Date: Tue, 16 Jul 2019 23:11:53 +0200 Subject: [PATCH] unique sql database connection is created on different threads Signed-off-by: Paulchen-Panther --- include/db/DBManager.h | 2 +- include/db/InstanceTable.h | 2 +- libsrc/db/DBManager.cpp | 36 +++++++++++++----------------------- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/include/db/DBManager.h b/include/db/DBManager.h index b0cffe54..5a74dbc0 100644 --- a/include/db/DBManager.h +++ b/include/db/DBManager.h @@ -32,7 +32,7 @@ public: /// set root path void setRootPath(const QString& rootPath); /// define the database to work with - void setDB(const QString& dbn); + void setDatabaseName(const QString& dbn) { _dbn = dbn; }; /// set a table to work with void setTable(const QString& table); diff --git a/include/db/InstanceTable.h b/include/db/InstanceTable.h index 91201209..4018ee87 100644 --- a/include/db/InstanceTable.h +++ b/include/db/InstanceTable.h @@ -19,7 +19,7 @@ public: { // Init Hyperion database usage setRootPath(rootPath); - setDB("hyperion"); + setDatabaseName("hyperion"); // Init instance table setTable("instances"); diff --git a/libsrc/db/DBManager.cpp b/libsrc/db/DBManager.cpp index 43c9c55f..fe0d5575 100644 --- a/libsrc/db/DBManager.cpp +++ b/libsrc/db/DBManager.cpp @@ -4,10 +4,13 @@ #include #include #include +#include +#include #include // not in header because of linking static QString _rootPath; +static QThreadStorage _databasePool; DBManager::DBManager(QObject* parent) : QObject(parent) @@ -26,22 +29,6 @@ void DBManager::setRootPath(const QString& rootPath) QDir().mkpath(_rootPath+"/db"); } -void DBManager::setDB(const QString& dbn) -{ - _dbn = dbn; - // new database connection if not found - if(!QSqlDatabase::contains(dbn)) - { - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE",dbn); - db.setDatabaseName(_rootPath+"/db/"+dbn+".db"); - if(!db.open()) - { - Error(_log, QSTRING_CSTR(db.lastError().text())); - throw std::runtime_error("Failed to open database connection!"); - } - } -} - void DBManager::setTable(const QString& table) { _table = table; @@ -49,17 +36,20 @@ void DBManager::setTable(const QString& table) QSqlDatabase DBManager::getDB() const { - QSqlDatabase db = QSqlDatabase::database(_dbn); - - if (db.isOpen() && db.isValid()) - return db; + if(_databasePool.hasLocalData()) + return _databasePool.localData(); else { - db = QSqlDatabase::addDatabase("QSQLITE", _dbn); + auto db = QSqlDatabase::addDatabase("QSQLITE", QUuid::createUuid().toString()); + _databasePool.setLocalData(db); db.setDatabaseName(_rootPath+"/db/"+_dbn+".db"); + if(!db.open()) + { + Error(_log, QSTRING_CSTR(db.lastError().text())); + throw std::runtime_error("Failed to open database connection!"); + } + return db; } - - return db; } bool DBManager::createRecord(const VectorPair& conditions, const QVariantMap& columns) const