From f03941e4113e2c8c0a594592be44efc92614ec9d Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Fri, 21 Dec 2018 14:34:28 +0100 Subject: Add overload of QSqlDatabase::cloneDatabase to allow cloning cross threads Since QSqlDatabase::database() cannot be used to access another database from another thread, then the overload is provided to make it possible to clone with just the connection name. This will handle the cloning internally safely then. Fixes: QTBUG-72545 Change-Id: I861cc5aa2c38c1e3797f6f086594a1228f05bada Reviewed-by: Simon Hausmann --- src/sql/kernel/qsqldatabase.cpp | 34 ++++++++++++++++++++++++++++++++++ src/sql/kernel/qsqldatabase.h | 1 + 2 files changed, 35 insertions(+) (limited to 'src/sql') diff --git a/src/sql/kernel/qsqldatabase.cpp b/src/sql/kernel/qsqldatabase.cpp index 2c7b4b83db..12ab9671b5 100644 --- a/src/sql/kernel/qsqldatabase.cpp +++ b/src/sql/kernel/qsqldatabase.cpp @@ -1379,6 +1379,40 @@ QSqlDatabase QSqlDatabase::cloneDatabase(const QSqlDatabase &other, const QStrin return db; } +/*! + \since 5.13 + \overload + + Clones the database connection \a other and stores it as \a + connectionName. All the settings from the original database, e.g. + databaseName(), hostName(), etc., are copied across. Does nothing + if \a other is an invalid database. Returns the newly created + database connection. + + \note The new connection has not been opened. Before using the new + connection, you must call open(). + + This overload is useful when cloning the database in another thread to the + one that is used by the database represented by \a other. +*/ + +QSqlDatabase QSqlDatabase::cloneDatabase(const QString &other, const QString &connectionName) +{ + const QConnectionDict *dict = dbDict(); + Q_ASSERT(dict); + + dict->lock.lockForRead(); + QSqlDatabase otherDb = dict->value(other); + dict->lock.unlock(); + if (!otherDb.isValid()) + return QSqlDatabase(); + + QSqlDatabase db(otherDb.driverName()); + db.d->copy(otherDb.d); + QSqlDatabasePrivate::addDatabase(db, connectionName); + return db; +} + /*! \since 4.4 diff --git a/src/sql/kernel/qsqldatabase.h b/src/sql/kernel/qsqldatabase.h index 3aadab9b2f..f233c72c19 100644 --- a/src/sql/kernel/qsqldatabase.h +++ b/src/sql/kernel/qsqldatabase.h @@ -118,6 +118,7 @@ public: static QSqlDatabase addDatabase(QSqlDriver* driver, const QString& connectionName = QLatin1String(defaultConnection)); static QSqlDatabase cloneDatabase(const QSqlDatabase &other, const QString& connectionName); + static QSqlDatabase cloneDatabase(const QString &other, const QString& connectionName); static QSqlDatabase database(const QString& connectionName = QLatin1String(defaultConnection), bool open = true); static void removeDatabase(const QString& connectionName); -- cgit v1.2.3