Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qsqldatabase.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:credentials
4
5#include "qsqldatabase.h"
6#include "qsqlquery.h"
10#include "qsqldriver.h"
11#include "qsqldriver_p.h"
13#include "qsqlindex.h"
14#include "QtCore/qapplicationstatic.h"
15#include "private/qfactoryloader_p.h"
16#include "private/qsqlnulldriver_p.h"
17#include "qhash.h"
18#include "qthread.h"
19
21
22Q_STATIC_LOGGING_CATEGORY(lcSqlDb, "qt.sql.qsqldatabase")
23
24using namespace Qt::StringLiterals;
25
26#define CHECK_QCOREAPPLICATION
27 if (Q_UNLIKELY(!QCoreApplication::instanceExists())) {
28 qCWarning(lcSqlDb, "QSqlDatabase requires a QCoreApplication");
29 return;
30 }
31#define CHECK_QCOREAPPLICATION_RETVAL
32 if (Q_UNLIKELY(!QCoreApplication::instanceExists())) {
33 qCWarning(lcSqlDb, "QSqlDatabase requires a QCoreApplication");
34 return {};
35 }
36
37Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
38 (QSqlDriverFactoryInterface_iid, "/sqldrivers"_L1))
39
40namespace {
41 struct QtSqlGlobals
42 {
43 ~QtSqlGlobals();
44 QSqlDatabase connection(const QString &key) const
45 {
46 QReadLocker locker(&lock);
47 return connections.value(key);
48 }
49 bool connectionExists(const QString &key) const
50 {
51 QReadLocker locker(&lock);
52 return connections.contains(key);
53 }
54 QStringList connectionNames() const
55 {
56 QReadLocker locker(&lock);
57 return connections.keys();
58 }
59 mutable QReadWriteLock lock;
60 QHash<QString, QSqlDriverCreatorBase*> registeredDrivers;
61 QHash<QString, QSqlDatabase> connections;
62 };
63}
64Q_APPLICATION_STATIC(QtSqlGlobals, s_sqlGlobals)
65
67{
68public:
69 QSqlDatabasePrivate(QSqlDriver *dr):
70 ref(1),
71 driver(dr),
72 port(-1)
73 {
74 precisionPolicy = QSql::LowPrecisionDouble;
75 }
78 void init(const QString& type);
79 void copy(const QSqlDatabasePrivate *other);
80 void disable();
81
83 QSqlDriver* driver;
89 int port;
93
95 static QSqlDatabase database(const QString& name, bool open);
96 static void addDatabase(const QSqlDatabase &db, const QString & name);
97 static void removeDatabase(const QString& name);
98 static void invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn = true);
99};
100
102{
103 dbname = other.dbname;
104 uname = other.uname;
105 pword = other.pword;
106 hname = other.hname;
107 drvName = other.drvName;
108 port = other.port;
109 connOptions = other.connOptions;
110 driver = other.driver;
111 precisionPolicy = other.precisionPolicy;
112 if (driver) {
113 driver->setNumericalPrecisionPolicy(other.driver->numericalPrecisionPolicy());
114 auto drvPriv = static_cast<QSqlDriverPrivate *>(QObjectPrivate::get(driver));
115 drvPriv->connectionName = connName;
116 }
117}
118
124
125QtSqlGlobals::~QtSqlGlobals()
126{
127 qDeleteAll(registeredDrivers);
128 for (const auto &[k, v] : std::as_const(connections).asKeyValueRange())
129 QSqlDatabasePrivate::invalidateDb(v, k, false);
130}
131
133{
134 static QSqlNullDriver dr;
135 static QSqlDatabasePrivate n(&dr);
136 return &n;
137}
138
139void QSqlDatabasePrivate::invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn)
140{
141 if (db.d->ref.loadRelaxed() != 1 && doWarn) {
142 qCWarning(lcSqlDb, "QSqlDatabasePrivate::removeDatabase: connection '%ls' is still in use, "
143 "all queries will cease to work.", qUtf16Printable(name));
144 db.d->disable();
145 db.d->connName.clear();
146 }
147}
148
149void QSqlDatabasePrivate::removeDatabase(const QString &name)
150{
152 QtSqlGlobals *sqlGlobals = s_sqlGlobals();
153 QWriteLocker locker(&sqlGlobals->lock);
154
155 if (!sqlGlobals->connections.contains(name))
156 return;
157
158 invalidateDb(sqlGlobals->connections.take(name), name);
159}
160
161void QSqlDatabasePrivate::addDatabase(const QSqlDatabase &db, const QString &name)
162{
164 QtSqlGlobals *sqlGlobals = s_sqlGlobals();
165 QWriteLocker locker(&sqlGlobals->lock);
166
167 if (sqlGlobals->connections.contains(name)) {
168 invalidateDb(sqlGlobals->connections.take(name), name);
169 qCWarning(lcSqlDb, "QSqlDatabasePrivate::addDatabase: duplicate connection name '%ls', old "
170 "connection removed.", qUtf16Printable(name));
171 }
172 sqlGlobals->connections.insert(name, db);
173 db.d->connName = name;
174 auto drvPriv = static_cast<QSqlDriverPrivate *>(QObjectPrivate::get(db.d->driver));
175 drvPriv->connectionName = name;
176}
177
178/*! \internal
179*/
180QSqlDatabase QSqlDatabasePrivate::database(const QString& name, bool open)
181{
183 QSqlDatabase db = s_sqlGlobals()->connection(name);
184 if (!db.isValid())
185 return db;
186 if (db.driver()->thread() != QThread::currentThread()) {
187 qCWarning(lcSqlDb, "QSqlDatabasePrivate::database: requested database does not belong to the calling thread.");
188 return QSqlDatabase();
189 }
190
191 if (open && !db.isOpen()) {
192 if (!db.open())
193 qCWarning(lcSqlDb) << "QSqlDatabasePrivate::database: unable to open database:" << db.lastError().text();
194
195 }
196 return db;
197}
198
199
200/*! \internal
201 Copies the connection data from \a other.
202*/
204{
205 dbname = other->dbname;
206 uname = other->uname;
207 pword = other->pword;
208 hname = other->hname;
209 drvName = other->drvName;
210 port = other->port;
211 connOptions = other->connOptions;
212 precisionPolicy = other->precisionPolicy;
213 if (driver)
214 driver->setNumericalPrecisionPolicy(other->driver->numericalPrecisionPolicy());
215}
216
218{
220 delete driver;
222 }
223}
224
225/*!
226 \class QSqlDriverCreatorBase
227 \brief The QSqlDriverCreatorBase class is the base class for
228 SQL driver factories.
229
230 \ingroup database
231 \inmodule QtSql
232
233 Reimplement createObject() to return an instance of the specific
234 QSqlDriver subclass that you want to provide.
235
236 See QSqlDatabase::registerSqlDriver() for details.
237
238 \sa QSqlDriverCreator
239*/
240
241/*!
242 \fn QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
243
244 Destroys the SQL driver creator object.
245*/
246QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
247 = default;
248
249/*!
250 \fn QSqlDriver *QSqlDriverCreatorBase::createObject() const
251
252 Reimplement this function to returns a new instance of a
253 QSqlDriver subclass.
254*/
255
256/*!
257 \class QSqlDriverCreator
258 \brief The QSqlDriverCreator class is a template class that
259 provides a SQL driver factory for a specific driver type.
260
261 \ingroup database
262 \inmodule QtSql
263
264 QSqlDriverCreator<T> instantiates objects of type T, where T is a
265 QSqlDriver subclass.
266
267 See QSqlDatabase::registerSqlDriver() for details.
268*/
269
270/*!
271 \fn template <class T> QSqlDriver *QSqlDriverCreator<T>::createObject() const
272 \reimp
273*/
274
275/*!
276 \class QSqlDatabase
277 \brief The QSqlDatabase class handles a connection to
278 a database.
279
280 \ingroup database
281
282 \inmodule QtSql
283
284 The QSqlDatabase class provides an interface for accessing a
285 database through a connection. An instance of QSqlDatabase
286 represents the connection. The connection provides access to the
287 database via one of the \l{SQL Database Drivers#Supported
288 Databases} {supported database drivers}, which are derived from
289 QSqlDriver. Alternatively, you can subclass your own database
290 driver from QSqlDriver. See \l{How to Write Your Own Database
291 Driver} for more information.
292 A QSqlDatabase instance must only be accessed by the thread it
293 was created in. Therefore you have to make sure to create them
294 in the correct context. Alternatively you can change the context
295 with QSqlDatabase::moveToThread().
296
297 Create a connection (i.e., an instance of QSqlDatabase) by calling
298 one of the static addDatabase() functions, where you specify
299 \l{SQL Database Drivers#Supported Databases} {the driver or type
300 of driver} to use (depending on the type of database)
301 and a connection name. A connection is known by its own name,
302 \e{not} by the name of the database it connects to. You can have
303 multiple connections to one database. QSqlDatabase also supports
304 the concept of a \e{default} connection, which is the unnamed
305 connection. To create the default connection, don't pass the
306 connection name argument when you call addDatabase().
307 Subsequently, the default connection will be assumed if you call
308 any static member function without specifying the connection name.
309 The following snippet shows how to create and open a default connection
310 to a PostgreSQL database:
311
312 \snippet sqldatabase/sqldatabase.cpp 0
313
314 Once the QSqlDatabase object has been created, set the connection
315 parameters with setDatabaseName(), setUserName(), setPassword(),
316 setHostName(), setPort(), and setConnectOptions(). Then call
317 open() to activate the physical connection to the database. The
318 connection is not usable until you open it.
319
320 The connection defined above will be the \e{default} connection,
321 because we didn't give a connection name to \l{QSqlDatabase::}
322 {addDatabase()}. Subsequently, you can get the default connection
323 by calling database() without the connection name argument:
324
325 \snippet sqldatabase/sqldatabase.cpp 1
326
327 QSqlDatabase is a value class. Changes made to a database
328 connection via one instance of QSqlDatabase will affect other
329 instances of QSqlDatabase that represent the same connection. Use
330 cloneDatabase() to create an independent database connection based
331 on an existing one.
332
333 \warning It is highly recommended that you do not keep a copy of the
334 QSqlDatabase around as a member of a class, as this will prevent the
335 instance from being correctly cleaned up on shutdown. If you need to
336 access an existing QSqlDatabase, it should be accessed with database().
337 If you chose to have a QSqlDatabase member variable, this needs to be
338 deleted before the QCoreApplication instance is deleted, otherwise it
339 may lead to undefined behavior.
340
341 If you create multiple database connections, specify a unique
342 connection name for each one, when you call addDatabase(). Use
343 database() with a connection name to get that connection. Use
344 removeDatabase() with a connection name to remove a connection.
345 QSqlDatabase outputs a warning if you try to remove a connection
346 referenced by other QSqlDatabase objects. Use contains() to see if
347 a given connection name is in the list of connections.
348
349 \table
350 \header
351 \li {2,1}Some utility methods:
352 \row
353 \li tables()
354 \li returns the list of tables
355 \row
356 \li primaryIndex()
357 \li returns a table's primary index
358 \row
359 \li record()
360 \li returns meta-information about a table's fields
361 \row
362 \li transaction()
363 \li starts a transaction
364 \row
365 \li commit()
366 \li saves and completes a transaction
367 \row
368 \li rollback()
369 \li cancels a transaction
370 \row
371 \li hasFeature()
372 \li checks if a driver supports transactions
373 \row
374 \li lastError()
375 \li returns information about the last error
376 \row
377 \li drivers()
378 \li returns the names of the available SQL drivers
379 \row
380 \li isDriverAvailable()
381 \li checks if a particular driver is available
382 \row
383 \li registerSqlDriver()
384 \li registers a custom-made driver
385 \endtable
386
387 \note When using transactions, you must start the
388 transaction before you create your query.
389
390 \sa QSqlDriver, QSqlQuery, {Qt SQL}, {Threads and the SQL Module}
391*/
392
393/*! \fn QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
394 \threadsafe
395
396 Adds a database to the list of database connections using the
397 driver \a type and the connection name \a connectionName. If
398 there already exists a database connection called \a
399 connectionName, that connection is removed.
400
401 The database connection is referred to by \a connectionName. The
402 newly added database connection is returned.
403
404 If \a type is not available or could not be loaded, isValid() returns \c false.
405
406 If \a connectionName is not specified, the new connection becomes
407 the default connection for the application, and subsequent calls
408 to database() without the connection name argument will return the
409 default connection. If a \a connectionName is provided here, use
410 database(\a connectionName) to retrieve the connection.
411
412 \warning If you add a connection with the same name as an existing
413 connection, the new connection replaces the old one. If you call
414 this function more than once without specifying \a connectionName,
415 the default connection will be the one replaced.
416
417 Before using the connection, it must be initialized. e.g., call
418 some or all of setDatabaseName(), setUserName(), setPassword(),
419 setHostName(), setPort(), and setConnectOptions(), and, finally,
420 open().
421
422 \sa database(), removeDatabase(), {Threads and the SQL Module}
423*/
424QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
425{
426 QSqlDatabase db(type);
427 QSqlDatabasePrivate::addDatabase(db, connectionName);
428 return db;
429}
430
431/*!
432 \threadsafe
433
434 Returns the database connection called \a connectionName. The
435 database connection must have been previously added with
436 addDatabase(). If \a open is true (the default) and the database
437 connection is not already open it is opened now. If no \a
438 connectionName is specified the default connection is used. If \a
439 connectionName does not exist in the list of databases, an invalid
440 connection is returned.
441
442 \sa isOpen(), {Threads and the SQL Module}
443*/
444
445QSqlDatabase QSqlDatabase::database(const QString& connectionName, bool open)
446{
447 return QSqlDatabasePrivate::database(connectionName, open);
448}
449
450/*!
451 \threadsafe
452
453 Removes the database connection \a connectionName from the list of
454 database connections.
455
456 \warning There should be no open queries on the database
457 connection when this function is called, otherwise a resource leak
458 will occur.
459
460 Example:
461
462 \snippet code/src_sql_kernel_qsqldatabase.cpp 0
463
464 The correct way to do it:
465
466 \snippet code/src_sql_kernel_qsqldatabase.cpp 1
467
468 To remove the default connection, which may have been created with a
469 call to addDatabase() not specifying a connection name, you can
470 retrieve the default connection name by calling connectionName() on
471 the database returned by database(). Note that if a default database
472 hasn't been created an invalid database will be returned.
473
474 \sa database(), connectionName(), {Threads and the SQL Module}
475*/
476
477void QSqlDatabase::removeDatabase(const QString& connectionName)
478{
479 QSqlDatabasePrivate::removeDatabase(connectionName);
480}
481
482/*!
483 Returns a list of all the available database drivers.
484
485 \sa registerSqlDriver()
486*/
487
488QStringList QSqlDatabase::drivers()
489{
491 QStringList list;
492
493 if (QFactoryLoader *fl = loader()) {
494 typedef QMultiMap<int, QString> PluginKeyMap;
495
496 const PluginKeyMap keyMap = fl->keyMap();
497 for (const QString &val : keyMap) {
498 if (!list.contains(val))
499 list << val;
500 }
501 }
502
503 QtSqlGlobals *sqlGlobals = s_sqlGlobals();
504 QReadLocker locker(&sqlGlobals->lock);
505 const auto &dict = sqlGlobals->registeredDrivers;
506 for (const auto &[k, _] : dict.asKeyValueRange()) {
507 if (!list.contains(k))
508 list << k;
509 }
510
511 return list;
512}
513
514/*!
515 This function registers a new SQL driver called \a name, within
516 the SQL framework. This is useful if you have a custom SQL driver
517 and don't want to compile it as a plugin.
518
519 Example:
520 \snippet code/src_sql_kernel_qsqldatabase_snippet.cpp 2
521
522 QSqlDatabase takes ownership of the \a creator pointer, so you
523 mustn't delete it yourself.
524
525 \sa drivers()
526*/
527void QSqlDatabase::registerSqlDriver(const QString& name, QSqlDriverCreatorBase *creator)
528{
530 QtSqlGlobals *sqlGlobals = s_sqlGlobals();
531 QWriteLocker locker(&sqlGlobals->lock);
532 delete sqlGlobals->registeredDrivers.take(name);
533 if (creator)
534 sqlGlobals->registeredDrivers.insert(name, creator);
535}
536
537/*!
538 \threadsafe
539
540 Returns \c true if the list of database connections contains \a
541 connectionName; otherwise returns \c false.
542
543 \sa connectionNames(), database(), {Threads and the SQL Module}
544*/
545
546bool QSqlDatabase::contains(const QString& connectionName)
547{
549 return s_sqlGlobals()->connectionExists(connectionName);
550}
551
552/*!
553 \threadsafe
554
555 Returns a list containing the names of all connections.
556
557 \sa contains(), database(), {Threads and the SQL Module}
558*/
559QStringList QSqlDatabase::connectionNames()
560{
562 return s_sqlGlobals()->connectionNames();
563}
564
565/*!
566 \overload
567
568 Creates a QSqlDatabase connection that uses the driver referred
569 to by \a type. If the \a type is not recognized, the database
570 connection will have no functionality.
571
572 The currently available driver types are:
573
574 \table
575 \header \li Driver Type \li Description
576 \row \li QDB2 \li IBM DB2
577 \row \li QIBASE \li Borland InterBase Driver
578 \row \li QMYSQL \li MySQL Driver
579 \row \li QOCI \li Oracle Call Interface Driver
580 \row \li QODBC \li ODBC Driver (includes Microsoft SQL Server)
581 \row \li QPSQL \li PostgreSQL Driver
582 \row \li QSQLITE \li SQLite version 3 or above
583 \row \li QMIMER \li Mimer SQL 11 or above
584 \endtable
585
586 Additional third party drivers, including your own custom
587 drivers, can be loaded dynamically.
588
589 \sa {SQL Database Drivers}, registerSqlDriver(), drivers()
590*/
591
592QSqlDatabase::QSqlDatabase(const QString &type)
593 : d(new QSqlDatabasePrivate(nullptr))
594{
595 d->init(type);
596}
597
598/*!
599 \overload
600
601 Creates a database connection using the given \a driver.
602*/
603
604QSqlDatabase::QSqlDatabase(QSqlDriver *driver)
605 : d(new QSqlDatabasePrivate(driver))
606{
607}
608
609/*!
610 Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
611 removeDatabase(), and database() to get valid QSqlDatabase
612 objects.
613*/
614QSqlDatabase::QSqlDatabase()
615 : d(QSqlDatabasePrivate::shared_null())
616{
617 d->ref.ref();
618}
619
620/*!
621 Creates a copy of \a other.
622*/
623QSqlDatabase::QSqlDatabase(const QSqlDatabase &other)
624{
625 d = other.d;
626 d->ref.ref();
627}
628
629/*!
630 Assigns \a other to this object.
631*/
632QSqlDatabase &QSqlDatabase::operator=(const QSqlDatabase &other)
633{
634 qAtomicAssign(d, other.d);
635 return *this;
636}
637
638/*!
639 \internal
640
641 Create the actual driver instance \a type.
642*/
643
644void QSqlDatabasePrivate::init(const QString &type)
645{
647 drvName = type;
648
649 if (!driver) {
650 QtSqlGlobals *sqlGlobals = s_sqlGlobals();
651 QReadLocker locker(&sqlGlobals->lock);
652 const auto &dict = sqlGlobals->registeredDrivers;
653 auto it = dict.find(type);
654 if (it != dict.end())
655 driver = it.value()->createObject();
656 }
657
658 if (!driver && loader())
659 driver = qLoadPlugin<QSqlDriver, QSqlDriverPlugin>(loader(), type);
660
661 if (!driver) {
662 qCWarning(lcSqlDb,
663 "QSqlDatabase: can not load requested driver '%ls', available drivers: %ls",
664 qUtf16Printable(type), qUtf16Printable(QSqlDatabase::drivers().join(u' ')));
665 if (!QCoreApplication::instanceExists())
666 qCWarning(lcSqlDb, "QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
668 }
669}
670
671/*!
672 Destroys the object and frees any allocated resources.
673
674 \note When the last connection is destroyed, the destructor
675 implicitly calls close() to release the database connection.
676
677 \sa close()
678*/
679
680QSqlDatabase::~QSqlDatabase()
681{
682 if (!d->ref.deref()) {
683 close();
684 delete d;
685 }
686}
687
688/*!
689 Executes a SQL statement on the database and returns a QSqlQuery
690 object. Use lastError() to retrieve error information. If \a
691 query is empty, an empty, invalid query is returned and
692 lastError() is not affected.
693
694 \sa QSqlQuery, lastError()
695 \deprecated [6.6] Use QSqlQuery::exec() instead.
696*/
697#if QT_DEPRECATED_SINCE(6, 6)
698QSqlQuery QSqlDatabase::exec(const QString & query) const
699{
700 QSqlQuery r(d->driver->createResult());
701 if (!query.isEmpty()) {
702 r.exec(query);
703 d->driver->setLastError(r.lastError());
704 }
705 return r;
706}
707#endif
708
709/*!
710 Opens the database connection using the current connection
711 values. Returns \c true on success; otherwise returns \c false. Error
712 information can be retrieved using lastError().
713
714 \sa lastError(), setDatabaseName(), setUserName(), setPassword(),
715 setHostName(), setPort(), setConnectOptions()
716*/
717
718bool QSqlDatabase::open()
719{
720 return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
721 d->port, d->connOptions);
722}
723
724/*!
725 \overload
726
727 Opens the database connection using the given \a user name and \a
728 password. Returns \c true on success; otherwise returns \c false. Error
729 information can be retrieved using the lastError() function.
730
731 This function does not store the password it is given. Instead,
732 the password is passed directly to the driver for opening the
733 connection and it is then discarded.
734
735 \sa lastError()
736*/
737
738bool QSqlDatabase::open(const QString& user, const QString& password)
739{
740 setUserName(user);
741 return d->driver->open(d->dbname, user, password, d->hname,
742 d->port, d->connOptions);
743}
744
745/*!
746 Closes the database connection, freeing any resources acquired, and
747 invalidating any existing QSqlQuery objects that are used with the
748 database.
749
750 This will also affect copies of this QSqlDatabase object.
751
752 \sa removeDatabase()
753*/
754
755void QSqlDatabase::close()
756{
757 d->driver->close();
758}
759
760/*!
761 Returns \c true if the database connection is currently open;
762 otherwise returns \c false.
763*/
764
765bool QSqlDatabase::isOpen() const
766{
767 return d->driver->isOpen();
768}
769
770/*!
771 Returns \c true if there was an error opening the database
772 connection; otherwise returns \c false. Error information can be
773 retrieved using the lastError() function.
774*/
775
776bool QSqlDatabase::isOpenError() const
777{
778 return d->driver->isOpenError();
779}
780
781/*!
782 Begins a transaction on the database if the driver supports
783 transactions. Returns \c{true} if the operation succeeded.
784 Otherwise it returns \c{false}.
785
786 \sa QSqlDriver::hasFeature(), commit(), rollback()
787*/
788bool QSqlDatabase::transaction()
789{
790 if (!d->driver->hasFeature(QSqlDriver::Transactions))
791 return false;
792 return d->driver->beginTransaction();
793}
794
795/*!
796 Commits a transaction to the database if the driver supports
797 transactions and a transaction() has been started. Returns \c{true}
798 if the operation succeeded. Otherwise it returns \c{false}.
799
800 \note For some databases, the commit will fail and return \c{false}
801 if there is an \l{QSqlQuery::isActive()} {active query} using the
802 database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
803 {inactive} before doing the commit.
804
805 Call lastError() to get information about errors.
806
807 \sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), rollback()
808*/
809bool QSqlDatabase::commit()
810{
811 if (!d->driver->hasFeature(QSqlDriver::Transactions))
812 return false;
813 return d->driver->commitTransaction();
814}
815
816/*!
817 Rolls back a transaction on the database, if the driver supports
818 transactions and a transaction() has been started. Returns \c{true}
819 if the operation succeeded. Otherwise it returns \c{false}.
820
821 \note For some databases, the rollback will fail and return
822 \c{false} if there is an \l{QSqlQuery::isActive()} {active query}
823 using the database for a \c{SELECT}. Make the query
824 \l{QSqlQuery::isActive()} {inactive} before doing the rollback.
825
826 Call lastError() to get information about errors.
827
828 \sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), commit()
829*/
830bool QSqlDatabase::rollback()
831{
832 if (!d->driver->hasFeature(QSqlDriver::Transactions))
833 return false;
834 return d->driver->rollbackTransaction();
835}
836
837/*!
838 Sets the connection's database name to \a name. To have effect,
839 the database name must be set \e{before} the connection is
840 \l{open()} {opened}. Alternatively, you can close() the
841 connection, set the database name, and call open() again. \note
842 The \e{database name} is not the \e{connection name}. The
843 connection name must be passed to addDatabase() at connection
844 object create time.
845
846 For the QSQLITE driver, if the database name specified does not
847 exist, then it will create the file for you unless the
848 QSQLITE_OPEN_READONLY option is set.
849
850 Additionally, \a name can be set to \c ":memory:" which will
851 create a temporary database which is only available for the
852 lifetime of the application.
853
854 For the QOCI (Oracle) driver, the database name is the TNS
855 Service Name.
856
857 For the QODBC driver, the \a name can either be a DSN, a DSN
858 filename (in which case the file must have a \c .dsn extension),
859 or a connection string.
860
861 For example, Microsoft Access users can use the following
862 connection string to open an \c .mdb file directly, instead of
863 having to create a DSN entry in the ODBC manager:
864
865 \snippet code/src_sql_kernel_qsqldatabase.cpp 3
866
867 There is no default value.
868
869 \sa databaseName(), setUserName(), setPassword(), setHostName(),
870 setPort(), setConnectOptions(), open()
871*/
872
873void QSqlDatabase::setDatabaseName(const QString& name)
874{
875 if (isValid())
876 d->dbname = name;
877}
878
879/*!
880 Sets the connection's user name to \a name. To have effect, the
881 user name must be set \e{before} the connection is \l{open()}
882 {opened}. Alternatively, you can close() the connection, set the
883 user name, and call open() again.
884
885 There is no default value.
886
887 \sa userName(), setDatabaseName(), setPassword(), setHostName(),
888 setPort(), setConnectOptions(), open()
889*/
890
891void QSqlDatabase::setUserName(const QString& name)
892{
893 if (isValid())
894 d->uname = name;
895}
896
897/*!
898 Sets the connection's password to \a password. To have effect, the
899 password must be set \e{before} the connection is \l{open()}
900 {opened}. Alternatively, you can close() the connection, set the
901 password, and call open() again.
902
903 There is no default value.
904
905 \warning This function stores the password in plain text within
906 Qt. Use the open() call that takes a password as parameter to
907 avoid this behavior.
908
909 \sa password(), setUserName(), setDatabaseName(), setHostName(),
910 setPort(), setConnectOptions(), open()
911*/
912
913void QSqlDatabase::setPassword(const QString& password)
914{
915 if (isValid())
916 d->pword = password;
917}
918
919/*!
920 Sets the connection's host name to \a host. To have effect, the
921 host name must be set \e{before} the connection is \l{open()}
922 {opened}. Alternatively, you can close() the connection, set the
923 host name, and call open() again.
924
925 There is no default value.
926
927 \sa hostName(), setUserName(), setPassword(), setDatabaseName(),
928 setPort(), setConnectOptions(), open()
929*/
930
931void QSqlDatabase::setHostName(const QString& host)
932{
933 if (isValid())
934 d->hname = host;
935}
936
937/*!
938 Sets the connection's port number to \a port. To have effect, the
939 port number must be set \e{before} the connection is \l{open()}
940 {opened}. Alternatively, you can close() the connection, set the
941 port number, and call open() again..
942
943 There is no default value.
944
945 \sa port(), setUserName(), setPassword(), setHostName(),
946 setDatabaseName(), setConnectOptions(), open()
947*/
948
949void QSqlDatabase::setPort(int port)
950{
951 if (isValid())
952 d->port = port;
953}
954
955/*!
956 Returns the connection's database name, which may be empty.
957 \note The database name is not the connection name.
958
959 \sa setDatabaseName()
960*/
961QString QSqlDatabase::databaseName() const
962{
963 return d->dbname;
964}
965
966/*!
967 Returns the connection's user name; it may be empty.
968
969 \sa setUserName()
970*/
971QString QSqlDatabase::userName() const
972{
973 return d->uname;
974}
975
976/*!
977 Returns the connection's password. An empty string will be returned
978 if the password was not set with setPassword(), and if the password
979 was given in the open() call, or if no password was used.
980*/
981QString QSqlDatabase::password() const
982{
983 return d->pword;
984}
985
986/*!
987 Returns the connection's host name; it may be empty.
988
989 \sa setHostName()
990*/
991QString QSqlDatabase::hostName() const
992{
993 return d->hname;
994}
995
996/*!
997 Returns the connection's driver name.
998
999 \sa addDatabase(), driver()
1000*/
1001QString QSqlDatabase::driverName() const
1002{
1003 return d->drvName;
1004}
1005
1006/*!
1007 Returns the connection's port number. The value is undefined if
1008 the port number has not been set.
1009
1010 \sa setPort()
1011*/
1012int QSqlDatabase::port() const
1013{
1014 return d->port;
1015}
1016
1017/*!
1018 Returns the database driver used to access the database
1019 connection.
1020
1021 \sa addDatabase(), drivers()
1022*/
1023
1024QSqlDriver* QSqlDatabase::driver() const
1025{
1026 return d->driver;
1027}
1028
1029/*!
1030 Returns information about the last error that occurred on the
1031 database.
1032
1033 Failures that occur in conjunction with an individual query are
1034 reported by QSqlQuery::lastError().
1035
1036 \sa QSqlError, QSqlQuery::lastError()
1037*/
1038
1039QSqlError QSqlDatabase::lastError() const
1040{
1041 return d->driver->lastError();
1042}
1043
1044
1045/*!
1046 Returns a list of the database's tables, system tables and views,
1047 as specified by the parameter \a type.
1048
1049 \sa primaryIndex(), record()
1050*/
1051
1052QStringList QSqlDatabase::tables(QSql::TableType type) const
1053{
1054 return d->driver->tables(type);
1055}
1056
1057/*!
1058 Returns the primary index for table \a tablename. If no primary
1059 index exists, an empty QSqlIndex is returned.
1060
1061 \note Some drivers, such as the \l {QPSQL Case Sensitivity}{QPSQL}
1062 driver, may may require you to pass \a tablename in lower case if
1063 the table was not quoted when created. See the
1064 \l{sql-driver.html}{Qt SQL driver} documentation for more information.
1065
1066 \sa tables(), record()
1067*/
1068
1069QSqlIndex QSqlDatabase::primaryIndex(const QString& tablename) const
1070{
1071 return d->driver->primaryIndex(tablename);
1072}
1073
1074
1075/*!
1076 Returns a QSqlRecord populated with the names of all the fields in
1077 the table (or view) called \a tablename. The order in which the
1078 fields appear in the record is undefined. If no such table (or
1079 view) exists, an empty record is returned.
1080
1081 \note Some drivers, such as the \l {QPSQL Case Sensitivity}{QPSQL}
1082 driver, may may require you to pass \a tablename in lower case if
1083 the table was not quoted when created. See the
1084 \l{sql-driver.html}{Qt SQL driver} documentation for more information.
1085*/
1086
1087QSqlRecord QSqlDatabase::record(const QString& tablename) const
1088{
1089 return d->driver->record(tablename);
1090}
1091
1092
1093/*!
1094 Sets database-specific \a options. This must be done before the
1095 connection is opened, otherwise it has no effect. Another possibility
1096 is to close the connection, call QSqlDatabase::setConnectOptions(),
1097 and open() the connection again.
1098
1099 The format of the \a options string is a semicolon separated list
1100 of option names or option=value pairs. The options depend on the
1101 database client used and are described for each plugin in the
1102 \l{sql-driver.html}{SQL Database Drivers} page.
1103
1104 Examples:
1105 \snippet code/src_sql_kernel_qsqldatabase.cpp 4
1106
1107 Refer to the client library documentation for more information
1108 about the different options.
1109
1110 \sa connectOptions()
1111*/
1112
1113void QSqlDatabase::setConnectOptions(const QString &options)
1114{
1115 if (isValid())
1116 d->connOptions = options;
1117}
1118
1119/*!
1120 Returns the connection options string used for this connection.
1121 The string may be empty.
1122
1123 \sa setConnectOptions()
1124 */
1125QString QSqlDatabase::connectOptions() const
1126{
1127 return d->connOptions;
1128}
1129
1130/*!
1131 Returns \c true if a driver called \a name is available; otherwise
1132 returns \c false.
1133
1134 \sa drivers()
1135*/
1136
1137bool QSqlDatabase::isDriverAvailable(const QString& name)
1138{
1139 return drivers().contains(name);
1140}
1141
1142/*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1143 \overload
1144
1145 This overload is useful when you want to create a database
1146 connection with a \l{QSqlDriver} {driver} you instantiated
1147 yourself. It might be your own database driver, or you might just
1148 need to instantiate one of the Qt drivers yourself. If you do
1149 this, it is recommended that you include the driver code in your
1150 application. For example, you can create a PostgreSQL connection
1151 with your own QPSQL driver like this:
1152
1153 \snippet code/src_sql_kernel_qsqldatabase_snippet.cpp 6
1154
1155 The above code sets up a PostgreSQL connection and instantiates a
1156 QPSQLDriver object. Next, addDatabase() is called to add the
1157 connection to the known connections so that it can be used by the
1158 Qt SQL classes. When a driver is instantiated with a connection
1159 handle (or set of handles), Qt assumes that you have already
1160 opened the database connection.
1161
1162 \note We assume that \c qtdir is the directory where Qt is
1163 installed. This will pull in the code that is needed to use the
1164 PostgreSQL client library and to instantiate a QPSQLDriver object,
1165 assuming that you have the PostgreSQL headers somewhere in your
1166 include search path.
1167
1168 Remember that you must link your application against the database
1169 client library. Make sure the client library is in your linker's
1170 search path, and add lines like these to your \c{.pro} file:
1171
1172 \snippet code/src_sql_kernel_qsqldatabase_snippet.cpp 7
1173
1174 The method described works for all the supplied drivers. The only
1175 difference will be in the driver constructor arguments. Here is a
1176 table of the drivers included with Qt, their source code files,
1177 and their constructor arguments:
1178
1179 \table
1180 \header \li Driver \li Class name \li Constructor arguments \li File to include
1181 \row
1182 \li QPSQL
1183 \li QPSQLDriver
1184 \li PGconn *connection
1185 \li \c qsql_psql.cpp
1186 \row
1187 \li QMYSQL
1188 \li QMYSQLDriver
1189 \li MYSQL *connection
1190 \li \c qsql_mysql.cpp
1191 \row
1192 \li QOCI
1193 \li QOCIDriver
1194 \li OCIEnv *environment, OCISvcCtx *serviceContext
1195 \li \c qsql_oci.cpp
1196 \row
1197 \li QODBC
1198 \li QODBCDriver
1199 \li SQLHANDLE environment, SQLHANDLE connection
1200 \li \c qsql_odbc.cpp
1201 \row
1202 \li QDB2
1203 \li QDB2
1204 \li SQLHANDLE environment, SQLHANDLE connection
1205 \li \c qsql_db2.cpp
1206 \row
1207 \li QSQLITE
1208 \li QSQLiteDriver
1209 \li sqlite *connection
1210 \li \c qsql_sqlite.cpp
1211 \row
1212 \li QMIMER
1213 \li QMimerSQLDriver
1214 \li MimerSession *connection
1215 \li \c qsql_mimer.cpp
1216 \row
1217 \li QIBASE
1218 \li QIBaseDriver
1219 \li isc_db_handle connection
1220 \li \c qsql_ibase.cpp
1221 \endtable
1222
1223 \warning Adding a database connection with the same connection
1224 name as an existing connection, causes the existing connection to
1225 be replaced by the new one.
1226
1227 \warning The SQL framework takes ownership of the \a driver. It
1228 must not be deleted. To remove the connection, use
1229 removeDatabase().
1230
1231 \sa drivers()
1232*/
1233QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1234{
1235 QSqlDatabase db(driver);
1236 QSqlDatabasePrivate::addDatabase(db, connectionName);
1237 return db;
1238}
1239
1240/*!
1241 Returns \c true if the QSqlDatabase has a valid driver.
1242
1243 Example:
1244 \snippet code/src_sql_kernel_qsqldatabase.cpp 8
1245*/
1246bool QSqlDatabase::isValid() const
1247{
1248 return d->driver && d->driver != d->shared_null()->driver;
1249}
1250
1251/*!
1252 Clones the database connection \a other and stores it as \a
1253 connectionName. All the settings from the original database, e.g.
1254 databaseName(), hostName(), etc., are copied across. Does nothing
1255 if \a other is an invalid database. Returns the newly created
1256 database connection.
1257
1258 \note The new connection has not been opened. Before using the new
1259 connection, you must call open().
1260
1261 \reentrant
1262*/
1263QSqlDatabase QSqlDatabase::cloneDatabase(const QSqlDatabase &other, const QString &connectionName)
1264{
1265 if (!other.isValid())
1266 return QSqlDatabase();
1267
1268 QSqlDatabase db(other.driverName());
1269 db.d->copy(other.d);
1270 QSqlDatabasePrivate::addDatabase(db, connectionName);
1271 return db;
1272}
1273
1274/*!
1275 \since 5.13
1276 \overload
1277
1278 Clones the database connection \a other and stores it as \a
1279 connectionName. All the settings from the original database, e.g.
1280 databaseName(), hostName(), etc., are copied across. Does nothing
1281 if \a other is an invalid database. Returns the newly created
1282 database connection.
1283
1284 \note The new connection has not been opened. Before using the new
1285 connection, you must call open().
1286
1287 This overload is useful when cloning the database in another thread to the
1288 one that is used by the database represented by \a other.
1289*/
1290
1291QSqlDatabase QSqlDatabase::cloneDatabase(const QString &other, const QString &connectionName)
1292{
1294 return cloneDatabase(s_sqlGlobals()->connection(other), connectionName);
1295}
1296
1297/*!
1298 Returns the connection name, which may be empty. \note The
1299 connection name is not the \l{databaseName()} {database name}.
1300
1301 \sa addDatabase()
1302*/
1303QString QSqlDatabase::connectionName() const
1304{
1305 return d->connName;
1306}
1307
1308/*!
1309 \property QSqlDatabase::numericalPrecisionPolicy
1310 \since 6.8
1311
1312 This property holds the default numerical precision policy used by
1313 queries created on this database connection.
1314
1315 Note: Drivers that don't support fetching numerical values with low
1316 precision will ignore the precision policy. You can use
1317 QSqlDriver::hasFeature() to find out whether a driver supports this
1318 feature.
1319
1320 Note: Setting the default precision policy to \a precisionPolicy
1321 doesn't affect any currently active queries.
1322
1323 \sa QSql::NumericalPrecisionPolicy, QSqlQuery::numericalPrecisionPolicy,
1324 QSqlDriver::numericalPrecisionPolicy
1325*/
1326/*!
1327 Sets \l numericalPrecisionPolicy to \a precisionPolicy.
1328 */
1329void QSqlDatabase::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
1330{
1331 if (driver())
1332 driver()->setNumericalPrecisionPolicy(precisionPolicy);
1333 d->precisionPolicy = precisionPolicy;
1334}
1335
1336/*!
1337 Returns the \l numericalPrecisionPolicy.
1338*/
1339QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy() const
1340{
1341 if (driver())
1342 return driver()->numericalPrecisionPolicy();
1343 else
1344 return d->precisionPolicy;
1345}
1346
1347/*!
1348 \since 6.8
1349
1350 Changes the thread affinity for QSqlDatabase and its associated driver.
1351 This function returns \c true when the function succeeds. Event processing
1352 will continue in the \a targetThread.
1353
1354 During this operation you have to make sure that there is no QSqlQuery
1355 bound to this instance otherwise the QSqlDatabase will not be moved to
1356 the given thread and the function returns \c false.
1357
1358 Since the associated driver is derived from QObject, all constraints for
1359 moving a QObject to another thread also apply to this function.
1360
1361 \sa QObject::moveToThread(), {Threads and the SQL Module}
1362*/
1363bool QSqlDatabase::moveToThread(QThread *targetThread)
1364{
1365 if (auto drv = driver()) {
1366 if (drv != QSqlDatabasePrivate::shared_null()->driver) {
1367 // two instances are alive - the one here and the one in dbDict()
1368 if (d->ref.loadRelaxed() > 2) {
1369 qWarning("QSqlDatabasePrivate::moveToThread: connection '%ls' is still in use "
1370 "in the current thread.", qUtf16Printable(d->connName));
1371 return false;
1372 }
1373 return drv->moveToThread(targetThread);
1374 }
1375 }
1376 return false;
1377}
1378
1379/*!
1380 \since 6.8
1381
1382 Returns a pointer to the associated QThread instance.
1383*/
1384QThread *QSqlDatabase::thread() const
1385{
1386 if (auto drv = driver())
1387 return drv->thread();
1388 return nullptr;
1389}
1390
1391
1392#ifndef QT_NO_DEBUG_STREAM
1393QDebug operator<<(QDebug dbg, const QSqlDatabase &d)
1394{
1395 QDebugStateSaver saver(dbg);
1396 dbg.nospace();
1397 dbg.noquote();
1398 if (!d.isValid()) {
1399 dbg << "QSqlDatabase(invalid)";
1400 return dbg;
1401 }
1402
1403 dbg << "QSqlDatabase(driver=\"" << d.driverName() << "\", database=\""
1404 << d.databaseName() << "\", host=\"" << d.hostName() << "\", port=" << d.port()
1405 << ", user=\"" << d.userName() << "\", open=" << d.isOpen() << ')';
1406 return dbg;
1407}
1408#endif
1409
1410QT_END_NAMESPACE
1411
1412#include "moc_qsqldatabase.cpp"
static QSqlDatabasePrivate * shared_null()
void init(const QString &type)
QSqlDatabasePrivate(QSqlDriver *dr)
static QSqlDatabase database(const QString &name, bool open)
QSqlDatabasePrivate(const QSqlDatabasePrivate &other)
static void removeDatabase(const QString &name)
static void invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn=true)
QSql::NumericalPrecisionPolicy precisionPolicy
static void addDatabase(const QSqlDatabase &db, const QString &name)
void copy(const QSqlDatabasePrivate *other)
The QSqlDriverPlugin class provides an abstract base for custom QSqlDriver plugins.
#define qCWarning(category,...)
#define Q_STATIC_LOGGING_CATEGORY(name,...)
Q_GLOBAL_STATIC_WITH_ARGS(PermissionStatusHash, g_permissionStatusHash,({ { qMetaTypeId< QCameraPermission >(), Qt::PermissionStatus::Undetermined }, { qMetaTypeId< QMicrophonePermission >(), Qt::PermissionStatus::Undetermined }, { qMetaTypeId< QBluetoothPermission >(), Qt::PermissionStatus::Undetermined }, { qMetaTypeId< QContactsPermission >(), Qt::PermissionStatus::Undetermined }, { qMetaTypeId< QCalendarPermission >(), Qt::PermissionStatus::Undetermined }, { qMetaTypeId< QLocationPermission >(), Qt::PermissionStatus::Undetermined } }))
#define CHECK_QCOREAPPLICATION
#define CHECK_QCOREAPPLICATION_RETVAL
#define QSqlDriverFactoryInterface_iid