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