Do not keep a copy of database’s connection name

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.
This commit is contained in:
jordi fita mas 2024-12-20 21:29:46 +01:00
parent 5cc7192387
commit ca882f992b
2 changed files with 22 additions and 16 deletions

View File

@ -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<void> Database::open(const QString &user, const QString &password)
{
return QtConcurrent::run(&m_pool, [this, user, password]() {
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", m_connectionName);
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();
} else {
const QString errorMessage(db.lastError().text());
db = QSqlDatabase(); // Otherwise removeDatabase complains is still being used.
QSqlDatabase::removeDatabase(m_connectionName);
emit errorOcurred(errorMessage);
return;
}
errorMessage = db.lastError().text();
connectionName = db.connectionName();
}
QSqlDatabase::removeDatabase(connectionName);
emit errorOcurred(errorMessage);
});
}
QFuture<void> Database::close()
{
return QtConcurrent::run(&m_pool, [this]() {
QSqlDatabase db = QSqlDatabase::database(m_connectionName);
QString connectionName;
{
QSqlDatabase db = QSqlDatabase::database();
if (!db.isValid()) {
return;
}
connectionName = db.connectionName();
db.close();
QSqlDatabase::removeDatabase(m_connectionName);
}
QSqlDatabase::removeDatabase(connectionName);
emit closed();
});
}

View File

@ -25,7 +25,6 @@ signals:
private:
QThreadPool m_pool;
QString m_connectionName;
};
#endif // DATABASE_H