Added databasefactory to create database connections
Tá an tiomantas seo le fáil i:
tuismitheoir
60cc13c4b0
tiomantas
a6fec60ed5
40
cli/databasefactory.cpp
Comhad gnáth
40
cli/databasefactory.cpp
Comhad gnáth
@ -0,0 +1,40 @@
|
|||||||
|
#include <QThread>
|
||||||
|
#include "databasefactory.h"
|
||||||
|
#include "logger.h"
|
||||||
|
DatabaseFactory::DatabaseFactory(QString connectionString)
|
||||||
|
{
|
||||||
|
this->connectionString = connectionString;
|
||||||
|
}
|
||||||
|
static QThreadStorage<QSqlDatabase> 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;
|
||||||
|
}
|
17
cli/databasefactory.h
Comhad gnáth
17
cli/databasefactory.h
Comhad gnáth
@ -0,0 +1,17 @@
|
|||||||
|
#ifndef DATABASEFACTORY_H
|
||||||
|
#define DATABASEFACTORY_H
|
||||||
|
#include <QSqlDatabase>
|
||||||
|
#include <QThreadStorage>
|
||||||
|
#include "utils.h"
|
||||||
|
class DatabaseFactory
|
||||||
|
{
|
||||||
|
private:
|
||||||
|
QString connectionString;
|
||||||
|
|
||||||
|
public:
|
||||||
|
DatabaseFactory(QString connectionString);
|
||||||
|
QSqlDatabase createNew();
|
||||||
|
QSqlDatabase forCurrentThread();
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // DATABASEFACTORY_H
|
Á lódáil...
x
Tagairt in Eagrán Nua
Cuir bac ar úsáideoir