diff --git a/src/database.cpp b/src/database.cpp index 56f2812..537553b 100644 --- a/src/database.cpp +++ b/src/database.cpp @@ -6,7 +6,6 @@ Database::Database(QObject *parent) : QObject{parent} , m_pool{} - , m_connectionName{"main"} { m_pool.setMaxThreadCount(1); m_pool.setExpiryTimeout(-1); @@ -15,28 +14,36 @@ Database::Database(QObject *parent) QFuture 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); + QString errorMessage; + QString connectionName; + { + QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); + db.setConnectOptions("service=camper; options=-csearch_path=camper,public"); + if (db.open(user, password)) { + emit opened(); + return; + } + errorMessage = db.lastError().text(); + connectionName = db.connectionName(); } + QSqlDatabase::removeDatabase(connectionName); + emit errorOcurred(errorMessage); }); } QFuture Database::close() { return QtConcurrent::run(&m_pool, [this]() { - QSqlDatabase db = QSqlDatabase::database(m_connectionName); - if (!db.isValid()) { - return; + QString connectionName; + { + QSqlDatabase db = QSqlDatabase::database(); + if (!db.isValid()) { + return; + } + connectionName = db.connectionName(); + db.close(); } - db.close(); - QSqlDatabase::removeDatabase(m_connectionName); + QSqlDatabase::removeDatabase(connectionName); emit closed(); }); } diff --git a/src/database.h b/src/database.h index eb53aab..084acd6 100644 --- a/src/database.h +++ b/src/database.h @@ -25,7 +25,6 @@ signals: private: QThreadPool m_pool; - QString m_connectionName; }; #endif // DATABASE_H