camper/src/database.cpp

45 lines
1.3 KiB
C++

#include "database.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QtConcurrent>
Database::Database(QObject *parent)
: QObject{parent}
, m_pool{}
, m_connectionName{"main"}
{
m_pool.setMaxThreadCount(1);
m_pool.setExpiryTimeout(-1);
}
QFuture<void> Database::open(const QString &user, const QString &password)
{
return QtConcurrent::run(&m_pool, [this, user, password]() {
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", m_connectionName);
db.setConnectOptions("service=camper; options=-csearch_path=camper,public");
if (db.open(user, password)) {
emit opened();
} else {
const QString errorMessage(db.lastError().text());
db = QSqlDatabase(); // Otherwise removeDatabase complains is still being used.
QSqlDatabase::removeDatabase(m_connectionName);
emit errorOcurred(errorMessage);
}
});
}
QFuture<void> Database::close()
{
return QtConcurrent::run(&m_pool, [this]() {
QSqlDatabase db = QSqlDatabase::database(m_connectionName);
if (!db.isValid()) {
return;
}
db.close();
QSqlDatabase::removeDatabase(m_connectionName);
emit closed();
});
}
#include "moc_database.cpp"