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

source code of qtbase/src/sql/kernel/qsqldatabase.cpp