From ca882f992b18f3b3b5f977b1b664340150eff183 Mon Sep 17 00:00:00 2001 From: jordi fita mas Date: Fri, 20 Dec 2024 21:29:46 +0100 Subject: [PATCH] =?UTF-8?q?Do=20not=20keep=20a=20copy=20of=20database?= =?UTF-8?q?=E2=80=99s=20connection=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since i only plan to use a single connection, i can use QtSql’s default connection name. According to the documentation, i have to make sure that no query or database object is open when i remove the database. I now use C++ scopes for that, but i need to have a QString declared outside of it to get the default connection’s name. --- src/database.cpp | 37 ++++++++++++++++++++++--------------- src/database.h | 1 - 2 files changed, 22 insertions(+), 16 deletions(-) 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