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 
56 QT_BEGIN_NAMESPACE
57 
58 Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
59                           (QSqlDriverFactoryInterface_iid,
60                            QLatin1String("/sqldrivers")))
61 
62 const char *QSqlDatabase::defaultConnection = const_cast<char *>("qt_sql_default_connection");
63 
64 typedef QHash<QString, QSqlDriverCreatorBase*> DriverDict;
65 
66 class QConnectionDict: public QHash<QString, QSqlDatabase>
67 {
68 public:
contains_ts(const QString & key)69     inline bool contains_ts(const QString &key)
70     {
71         QReadLocker locker(&lock);
72         return contains(key);
73     }
keys_ts() const74     inline QStringList keys_ts() const
75     {
76         QReadLocker locker(&lock);
77         return keys();
78     }
79 
80     mutable QReadWriteLock lock;
81 };
82 Q_GLOBAL_STATIC(QConnectionDict, dbDict)
83 
84 class QSqlDatabasePrivate
85 {
86 public:
QSqlDatabasePrivate(QSqlDatabase * d,QSqlDriver * dr=nullptr)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 
QSqlDatabasePrivate(const QSqlDatabasePrivate & other)123 QSqlDatabasePrivate::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 
~QSqlDatabasePrivate()139 QSqlDatabasePrivate::~QSqlDatabasePrivate()
140 {
141     if (driver != shared_null()->driver)
142         delete driver;
143 }
144 
cleanConnections()145 void 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 
159 static bool qDriverDictInit = false;
cleanDriverDict()160 static void cleanDriverDict()
161 {
162     qDeleteAll(QSqlDatabasePrivate::driverDict());
163     QSqlDatabasePrivate::driverDict().clear();
164     QSqlDatabasePrivate::cleanConnections();
165     qDriverDictInit = false;
166 }
167 
driverDict()168 DriverDict &QSqlDatabasePrivate::driverDict()
169 {
170     static DriverDict dict;
171     if (!qDriverDictInit) {
172         qDriverDictInit = true;
173         qAddPostRoutine(cleanDriverDict);
174     }
175     return dict;
176 }
177 
shared_null()178 QSqlDatabasePrivate *QSqlDatabasePrivate::shared_null()
179 {
180     static QSqlNullDriver dr;
181     static QSqlDatabasePrivate n(nullptr, &dr);
182     return &n;
183 }
184 
invalidateDb(const QSqlDatabase & db,const QString & name,bool doWarn)185 void 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 
removeDatabase(const QString & name)195 void 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 
addDatabase(const QSqlDatabase & db,const QString & name)207 void 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 */
database(const QString & name,bool open)224 QSqlDatabase 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 */
copy(const QSqlDatabasePrivate * other)251 void 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 
disable()266 void 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 */
addDatabase(const QString & type,const QString & connectionName)470 QSqlDatabase 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 
database(const QString & connectionName,bool open)491 QSqlDatabase 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 
removeDatabase(const QString & connectionName)523 void 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 
drivers()534 QStringList 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 */
registerSqlDriver(const QString & name,QSqlDriverCreatorBase * creator)571 void 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 
contains(const QString & connectionName)587 bool 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 */
connectionNames()599 QStringList 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     \row \li QSQLITE2 \li SQLite version 2
623     \row \li QTDS     \li Sybase Adaptive Server
624     \endtable
625 
626     Additional third party drivers, including your own custom
627     drivers, can be loaded dynamically.
628 
629     \sa {SQL Database Drivers}, registerSqlDriver(), drivers()
630 */
631 
QSqlDatabase(const QString & type)632 QSqlDatabase::QSqlDatabase(const QString &type)
633 {
634     d = new QSqlDatabasePrivate(this);
635     d->init(type);
636 }
637 
638 /*!
639     \overload
640 
641     Creates a database connection using the given \a driver.
642 */
643 
QSqlDatabase(QSqlDriver * driver)644 QSqlDatabase::QSqlDatabase(QSqlDriver *driver)
645 {
646     d = new QSqlDatabasePrivate(this, driver);
647 }
648 
649 /*!
650     Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
651     removeDatabase(), and database() to get valid QSqlDatabase
652     objects.
653 */
QSqlDatabase()654 QSqlDatabase::QSqlDatabase()
655 {
656     d = QSqlDatabasePrivate::shared_null();
657     d->ref.ref();
658 }
659 
660 /*!
661     Creates a copy of \a other.
662 */
QSqlDatabase(const QSqlDatabase & other)663 QSqlDatabase::QSqlDatabase(const QSqlDatabase &other)
664 {
665     d = other.d;
666     d->ref.ref();
667 }
668 
669 /*!
670     Assigns \a other to this object.
671 */
operator =(const QSqlDatabase & other)672 QSqlDatabase &QSqlDatabase::operator=(const QSqlDatabase &other)
673 {
674     qAtomicAssign(d, other.d);
675     return *this;
676 }
677 
678 /*!
679     \internal
680 
681     Create the actual driver instance \a type.
682 */
683 
init(const QString & type)684 void QSqlDatabasePrivate::init(const QString &type)
685 {
686     drvName = type;
687 
688     if (!driver) {
689         DriverDict dict = QSqlDatabasePrivate::driverDict();
690         for (DriverDict::const_iterator it = dict.constBegin();
691              it != dict.constEnd() && !driver; ++it) {
692             if (type == it.key()) {
693                 driver = ((QSqlDriverCreatorBase*)(*it))->createObject();
694             }
695         }
696     }
697 
698     if (!driver && loader())
699         driver = qLoadPlugin<QSqlDriver, QSqlDriverPlugin>(loader(), type);
700 
701     if (!driver) {
702         qWarning("QSqlDatabase: %s driver not loaded", type.toLatin1().data());
703         qWarning("QSqlDatabase: available drivers: %s",
704                         QSqlDatabase::drivers().join(QLatin1Char(' ')).toLatin1().data());
705         if (QCoreApplication::instance() == nullptr)
706             qWarning("QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
707         driver = shared_null()->driver;
708     }
709 }
710 
711 /*!
712     Destroys the object and frees any allocated resources.
713 
714     \note When the last connection is destroyed, the destructor
715     implicitly calls close() to release the database connection.
716 
717     \sa close()
718 */
719 
~QSqlDatabase()720 QSqlDatabase::~QSqlDatabase()
721 {
722     if (!d->ref.deref()) {
723         close();
724         delete d;
725     }
726 }
727 
728 /*!
729     Executes a SQL statement on the database and returns a QSqlQuery
730     object. Use lastError() to retrieve error information. If \a
731     query is empty, an empty, invalid query is returned and
732     lastError() is not affected.
733 
734     \sa QSqlQuery, lastError()
735 */
736 
exec(const QString & query) const737 QSqlQuery QSqlDatabase::exec(const QString & query) const
738 {
739     QSqlQuery r(d->driver->createResult());
740     if (!query.isEmpty()) {
741         r.exec(query);
742         d->driver->setLastError(r.lastError());
743     }
744     return r;
745 }
746 
747 /*!
748     Opens the database connection using the current connection
749     values. Returns \c true on success; otherwise returns \c false. Error
750     information can be retrieved using lastError().
751 
752     \sa lastError(), setDatabaseName(), setUserName(), setPassword(),
753         setHostName(), setPort(), setConnectOptions()
754 */
755 
open()756 bool QSqlDatabase::open()
757 {
758     return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
759                             d->port, d->connOptions);
760 }
761 
762 /*!
763     \overload
764 
765     Opens the database connection using the given \a user name and \a
766     password. Returns \c true on success; otherwise returns \c false. Error
767     information can be retrieved using the lastError() function.
768 
769     This function does not store the password it is given. Instead,
770     the password is passed directly to the driver for opening the
771     connection and it is then discarded.
772 
773     \sa lastError()
774 */
775 
open(const QString & user,const QString & password)776 bool QSqlDatabase::open(const QString& user, const QString& password)
777 {
778     setUserName(user);
779     return d->driver->open(d->dbname, user, password, d->hname,
780                             d->port, d->connOptions);
781 }
782 
783 /*!
784     Closes the database connection, freeing any resources acquired, and
785     invalidating any existing QSqlQuery objects that are used with the
786     database.
787 
788     This will also affect copies of this QSqlDatabase object.
789 
790     \sa removeDatabase()
791 */
792 
close()793 void QSqlDatabase::close()
794 {
795     d->driver->close();
796 }
797 
798 /*!
799     Returns \c true if the database connection is currently open;
800     otherwise returns \c false.
801 */
802 
isOpen() const803 bool QSqlDatabase::isOpen() const
804 {
805     return d->driver->isOpen();
806 }
807 
808 /*!
809     Returns \c true if there was an error opening the database
810     connection; otherwise returns \c false. Error information can be
811     retrieved using the lastError() function.
812 */
813 
isOpenError() const814 bool QSqlDatabase::isOpenError() const
815 {
816     return d->driver->isOpenError();
817 }
818 
819 /*!
820   Begins a transaction on the database if the driver supports
821   transactions. Returns \c{true} if the operation succeeded.
822   Otherwise it returns \c{false}.
823 
824   \sa QSqlDriver::hasFeature(), commit(), rollback()
825 */
transaction()826 bool QSqlDatabase::transaction()
827 {
828     if (!d->driver->hasFeature(QSqlDriver::Transactions))
829         return false;
830     return d->driver->beginTransaction();
831 }
832 
833 /*!
834   Commits a transaction to the database if the driver supports
835   transactions and a transaction() has been started. Returns \c{true}
836   if the operation succeeded. Otherwise it returns \c{false}.
837 
838   \note For some databases, the commit will fail and return \c{false}
839   if there is an \l{QSqlQuery::isActive()} {active query} using the
840   database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
841   {inactive} before doing the commit.
842 
843   Call lastError() to get information about errors.
844 
845   \sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), rollback()
846 */
commit()847 bool QSqlDatabase::commit()
848 {
849     if (!d->driver->hasFeature(QSqlDriver::Transactions))
850         return false;
851     return d->driver->commitTransaction();
852 }
853 
854 /*!
855   Rolls back a transaction on the database, if the driver supports
856   transactions and a transaction() has been started. Returns \c{true}
857   if the operation succeeded. Otherwise it returns \c{false}.
858 
859   \note For some databases, the rollback will fail and return
860   \c{false} if there is an \l{QSqlQuery::isActive()} {active query}
861   using the database for a \c{SELECT}. Make the query
862   \l{QSqlQuery::isActive()} {inactive} before doing the rollback.
863 
864   Call lastError() to get information about errors.
865 
866   \sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), commit()
867 */
rollback()868 bool QSqlDatabase::rollback()
869 {
870     if (!d->driver->hasFeature(QSqlDriver::Transactions))
871         return false;
872     return d->driver->rollbackTransaction();
873 }
874 
875 /*!
876     Sets the connection's database name to \a name. To have effect,
877     the database name must be set \e{before} the connection is
878     \l{open()} {opened}.  Alternatively, you can close() the
879     connection, set the database name, and call open() again.  \note
880     The \e{database name} is not the \e{connection name}. The
881     connection name must be passed to addDatabase() at connection
882     object create time.
883 
884     For the QSQLITE driver, if the database name specified does not
885     exist, then it will create the file for you unless the
886     QSQLITE_OPEN_READONLY option is set.
887 
888     Additionally, \a name can be set to \c ":memory:" which will
889     create a temporary database which is only available for the
890     lifetime of the application.
891 
892     For the QOCI (Oracle) driver, the database name is the TNS
893     Service Name.
894 
895     For the QODBC driver, the \a name can either be a DSN, a DSN
896     filename (in which case the file must have a \c .dsn extension),
897     or a connection string.
898 
899     For example, Microsoft Access users can use the following
900     connection string to open an \c .mdb file directly, instead of
901     having to create a DSN entry in the ODBC manager:
902 
903     \snippet code/src_sql_kernel_qsqldatabase.cpp 3
904 
905     There is no default value.
906 
907     \sa databaseName(), setUserName(), setPassword(), setHostName(),
908         setPort(), setConnectOptions(), open()
909 */
910 
setDatabaseName(const QString & name)911 void QSqlDatabase::setDatabaseName(const QString& name)
912 {
913     if (isValid())
914         d->dbname = name;
915 }
916 
917 /*!
918     Sets the connection's user name to \a name. To have effect, the
919     user name must be set \e{before} the connection is \l{open()}
920     {opened}.  Alternatively, you can close() the connection, set the
921     user name, and call open() again.
922 
923     There is no default value.
924 
925     \sa userName(), setDatabaseName(), setPassword(), setHostName(),
926         setPort(), setConnectOptions(), open()
927 */
928 
setUserName(const QString & name)929 void QSqlDatabase::setUserName(const QString& name)
930 {
931     if (isValid())
932         d->uname = name;
933 }
934 
935 /*!
936     Sets the connection's password to \a password. To have effect, the
937     password must be set \e{before} the connection is \l{open()}
938     {opened}.  Alternatively, you can close() the connection, set the
939     password, and call open() again.
940 
941     There is no default value.
942 
943     \warning This function stores the password in plain text within
944     Qt. Use the open() call that takes a password as parameter to
945     avoid this behavior.
946 
947     \sa password(), setUserName(), setDatabaseName(), setHostName(),
948         setPort(), setConnectOptions(), open()
949 */
950 
setPassword(const QString & password)951 void QSqlDatabase::setPassword(const QString& password)
952 {
953     if (isValid())
954         d->pword = password;
955 }
956 
957 /*!
958     Sets the connection's host name to \a host. To have effect, the
959     host name must be set \e{before} the connection is \l{open()}
960     {opened}.  Alternatively, you can close() the connection, set the
961     host name, and call open() again.
962 
963     There is no default value.
964 
965     \sa hostName(), setUserName(), setPassword(), setDatabaseName(),
966         setPort(), setConnectOptions(), open()
967 */
968 
setHostName(const QString & host)969 void QSqlDatabase::setHostName(const QString& host)
970 {
971     if (isValid())
972         d->hname = host;
973 }
974 
975 /*!
976     Sets the connection's port number to \a port. To have effect, the
977     port number must be set \e{before} the connection is \l{open()}
978     {opened}.  Alternatively, you can close() the connection, set the
979     port number, and call open() again..
980 
981     There is no default value.
982 
983     \sa port(), setUserName(), setPassword(), setHostName(),
984         setDatabaseName(), setConnectOptions(), open()
985 */
986 
setPort(int port)987 void QSqlDatabase::setPort(int port)
988 {
989     if (isValid())
990         d->port = port;
991 }
992 
993 /*!
994     Returns the connection's database name, which may be empty.
995     \note The database name is not the connection name.
996 
997     \sa setDatabaseName()
998 */
databaseName() const999 QString QSqlDatabase::databaseName() const
1000 {
1001     return d->dbname;
1002 }
1003 
1004 /*!
1005     Returns the connection's user name; it may be empty.
1006 
1007     \sa setUserName()
1008 */
userName() const1009 QString QSqlDatabase::userName() const
1010 {
1011     return d->uname;
1012 }
1013 
1014 /*!
1015     Returns the connection's password. An empty string will be returned
1016     if the password was not set with setPassword(), and if the password
1017     was given in the open() call, or if no password was used.
1018 */
password() const1019 QString QSqlDatabase::password() const
1020 {
1021     return d->pword;
1022 }
1023 
1024 /*!
1025     Returns the connection's host name; it may be empty.
1026 
1027     \sa setHostName()
1028 */
hostName() const1029 QString QSqlDatabase::hostName() const
1030 {
1031     return d->hname;
1032 }
1033 
1034 /*!
1035     Returns the connection's driver name.
1036 
1037     \sa addDatabase(), driver()
1038 */
driverName() const1039 QString QSqlDatabase::driverName() const
1040 {
1041     return d->drvName;
1042 }
1043 
1044 /*!
1045     Returns the connection's port number. The value is undefined if
1046     the port number has not been set.
1047 
1048     \sa setPort()
1049 */
port() const1050 int QSqlDatabase::port() const
1051 {
1052     return d->port;
1053 }
1054 
1055 /*!
1056     Returns the database driver used to access the database
1057     connection.
1058 
1059     \sa addDatabase(), drivers()
1060 */
1061 
driver() const1062 QSqlDriver* QSqlDatabase::driver() const
1063 {
1064     return d->driver;
1065 }
1066 
1067 /*!
1068     Returns information about the last error that occurred on the
1069     database.
1070 
1071     Failures that occur in conjunction with an individual query are
1072     reported by QSqlQuery::lastError().
1073 
1074     \sa QSqlError, QSqlQuery::lastError()
1075 */
1076 
lastError() const1077 QSqlError QSqlDatabase::lastError() const
1078 {
1079     return d->driver->lastError();
1080 }
1081 
1082 
1083 /*!
1084     Returns a list of the database's tables, system tables and views,
1085     as specified by the parameter \a type.
1086 
1087     \sa primaryIndex(), record()
1088 */
1089 
tables(QSql::TableType type) const1090 QStringList QSqlDatabase::tables(QSql::TableType type) const
1091 {
1092     return d->driver->tables(type);
1093 }
1094 
1095 /*!
1096     Returns the primary index for table \a tablename. If no primary
1097     index exists, an empty QSqlIndex is returned.
1098 
1099     \note Some drivers, such as the \l {QPSQL Case Sensitivity}{QPSQL}
1100     driver, may may require you to pass \a tablename in lower case if
1101     the table was not quoted when created. See the
1102     \l{sql-driver.html}{Qt SQL driver} documentation for more information.
1103 
1104     \sa tables(), record()
1105 */
1106 
primaryIndex(const QString & tablename) const1107 QSqlIndex QSqlDatabase::primaryIndex(const QString& tablename) const
1108 {
1109     return d->driver->primaryIndex(tablename);
1110 }
1111 
1112 
1113 /*!
1114     Returns a QSqlRecord populated with the names of all the fields in
1115     the table (or view) called \a tablename. The order in which the
1116     fields appear in the record is undefined. If no such table (or
1117     view) exists, an empty record is returned.
1118 
1119     \note Some drivers, such as the \l {QPSQL Case Sensitivity}{QPSQL}
1120     driver, may may require you to pass \a tablename in lower case if
1121     the table was not quoted when created. See the
1122     \l{sql-driver.html}{Qt SQL driver} documentation for more information.
1123 */
1124 
record(const QString & tablename) const1125 QSqlRecord QSqlDatabase::record(const QString& tablename) const
1126 {
1127     return d->driver->record(tablename);
1128 }
1129 
1130 
1131 /*!
1132     Sets database-specific \a options. This must be done before the
1133     connection is opened, otherwise it has no effect. Another possibility
1134     is to close the connection, call QSqlDatabase::setConnectOptions(),
1135     and open() the connection again.
1136 
1137     The format of the \a options string is a semicolon separated list
1138     of option names or option=value pairs. The options depend on the
1139     database client used:
1140 
1141     \table
1142     \header \li ODBC \li MySQL \li PostgreSQL
1143     \row
1144 
1145     \li
1146     \list
1147     \li SQL_ATTR_ACCESS_MODE
1148     \li SQL_ATTR_LOGIN_TIMEOUT
1149     \li SQL_ATTR_CONNECTION_TIMEOUT
1150     \li SQL_ATTR_CURRENT_CATALOG
1151     \li SQL_ATTR_METADATA_ID
1152     \li SQL_ATTR_PACKET_SIZE
1153     \li SQL_ATTR_TRACEFILE
1154     \li SQL_ATTR_TRACE
1155     \li SQL_ATTR_CONNECTION_POOLING
1156     \li SQL_ATTR_ODBC_VERSION
1157     \endlist
1158 
1159     \li
1160     \list
1161     \li CLIENT_COMPRESS
1162     \li CLIENT_FOUND_ROWS
1163     \li CLIENT_IGNORE_SPACE
1164     \li CLIENT_ODBC
1165     \li CLIENT_NO_SCHEMA
1166     \li CLIENT_INTERACTIVE
1167     \li UNIX_SOCKET
1168     \li MYSQL_OPT_RECONNECT
1169     \li MYSQL_OPT_CONNECT_TIMEOUT
1170     \li MYSQL_OPT_READ_TIMEOUT
1171     \li MYSQL_OPT_WRITE_TIMEOUT
1172     \li SSL_KEY
1173     \li SSL_CERT
1174     \li SSL_CA
1175     \li SSL_CAPATH
1176     \li SSL_CIPHER
1177     \endlist
1178 
1179     \li
1180     \list
1181     \li connect_timeout
1182     \li options
1183     \li tty
1184     \li requiressl
1185     \li service
1186     \endlist
1187 
1188     \header \li DB2 \li OCI \li TDS
1189     \row
1190 
1191     \li
1192     \list
1193     \li SQL_ATTR_ACCESS_MODE
1194     \li SQL_ATTR_LOGIN_TIMEOUT
1195     \endlist
1196 
1197     \li
1198     \list
1199     \li OCI_ATTR_PREFETCH_ROWS
1200     \li OCI_ATTR_PREFETCH_MEMORY
1201     \endlist
1202 
1203     \li
1204     \e none
1205 
1206     \header \li SQLite \li Interbase
1207     \row
1208 
1209     \li
1210     \list
1211     \li QSQLITE_BUSY_TIMEOUT
1212     \li QSQLITE_OPEN_READONLY
1213     \li QSQLITE_OPEN_URI
1214     \li QSQLITE_ENABLE_SHARED_CACHE
1215     \li QSQLITE_ENABLE_REGEXP
1216     \endlist
1217 
1218     \li
1219     \list
1220     \li ISC_DPB_LC_CTYPE
1221     \li ISC_DPB_SQL_ROLE_NAME
1222     \endlist
1223 
1224     \endtable
1225 
1226     Examples:
1227     \snippet code/src_sql_kernel_qsqldatabase.cpp 4
1228 
1229     Refer to the client library documentation for more information
1230     about the different options.
1231 
1232     \sa connectOptions()
1233 */
1234 
setConnectOptions(const QString & options)1235 void QSqlDatabase::setConnectOptions(const QString &options)
1236 {
1237     if (isValid())
1238         d->connOptions = options;
1239 }
1240 
1241 /*!
1242     Returns the connection options string used for this connection.
1243     The string may be empty.
1244 
1245     \sa setConnectOptions()
1246  */
connectOptions() const1247 QString QSqlDatabase::connectOptions() const
1248 {
1249     return d->connOptions;
1250 }
1251 
1252 /*!
1253     Returns \c true if a driver called \a name is available; otherwise
1254     returns \c false.
1255 
1256     \sa drivers()
1257 */
1258 
isDriverAvailable(const QString & name)1259 bool QSqlDatabase::isDriverAvailable(const QString& name)
1260 {
1261     return drivers().contains(name);
1262 }
1263 
1264 /*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1265 
1266     This overload is useful when you want to create a database
1267     connection with a \l{QSqlDriver} {driver} you instantiated
1268     yourself. It might be your own database driver, or you might just
1269     need to instantiate one of the Qt drivers yourself. If you do
1270     this, it is recommended that you include the driver code in your
1271     application. For example, you can create a PostgreSQL connection
1272     with your own QPSQL driver like this:
1273 
1274     \snippet code/src_sql_kernel_qsqldatabase_snippet.cpp 6
1275 
1276     The above code sets up a PostgreSQL connection and instantiates a
1277     QPSQLDriver object. Next, addDatabase() is called to add the
1278     connection to the known connections so that it can be used by the
1279     Qt SQL classes. When a driver is instantiated with a connection
1280     handle (or set of handles), Qt assumes that you have already
1281     opened the database connection.
1282 
1283     \note We assume that \c qtdir is the directory where Qt is
1284     installed. This will pull in the code that is needed to use the
1285     PostgreSQL client library and to instantiate a QPSQLDriver object,
1286     assuming that you have the PostgreSQL headers somewhere in your
1287     include search path.
1288 
1289     Remember that you must link your application against the database
1290     client library. Make sure the client library is in your linker's
1291     search path, and add lines like these to your \c{.pro} file:
1292 
1293     \snippet code/src_sql_kernel_qsqldatabase_snippet.cpp 7
1294 
1295     The method described works for all the supplied drivers.  The only
1296     difference will be in the driver constructor arguments.  Here is a
1297     table of the drivers included with Qt, their source code files,
1298     and their constructor arguments:
1299 
1300     \table
1301     \header \li Driver \li Class name \li Constructor arguments \li File to include
1302     \row
1303     \li QPSQL
1304     \li QPSQLDriver
1305     \li PGconn *connection
1306     \li \c qsql_psql.cpp
1307     \row
1308     \li QMYSQL
1309     \li QMYSQLDriver
1310     \li MYSQL *connection
1311     \li \c qsql_mysql.cpp
1312     \row
1313     \li QOCI
1314     \li QOCIDriver
1315     \li OCIEnv *environment, OCISvcCtx *serviceContext
1316     \li \c qsql_oci.cpp
1317     \row
1318     \li QODBC
1319     \li QODBCDriver
1320     \li SQLHANDLE environment, SQLHANDLE connection
1321     \li \c qsql_odbc.cpp
1322     \row
1323     \li QDB2
1324     \li QDB2
1325     \li SQLHANDLE environment, SQLHANDLE connection
1326     \li \c qsql_db2.cpp
1327     \row
1328     \li QTDS
1329     \li QTDSDriver
1330     \li LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
1331     \li \c qsql_tds.cpp
1332     \row
1333     \li QSQLITE
1334     \li QSQLiteDriver
1335     \li sqlite *connection
1336     \li \c qsql_sqlite.cpp
1337     \row
1338     \li QIBASE
1339     \li QIBaseDriver
1340     \li isc_db_handle connection
1341     \li \c qsql_ibase.cpp
1342     \endtable
1343 
1344     The host name (or service name) is needed when constructing the
1345     QTDSDriver for creating new connections for internal queries. This
1346     is to prevent blocking when several QSqlQuery objects are used
1347     simultaneously.
1348 
1349     \warning Adding a database connection with the same connection
1350     name as an existing connection, causes the existing connection to
1351     be replaced by the new one.
1352 
1353     \warning The SQL framework takes ownership of the \a driver. It
1354     must not be deleted. To remove the connection, use
1355     removeDatabase().
1356 
1357     \sa drivers()
1358 */
addDatabase(QSqlDriver * driver,const QString & connectionName)1359 QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
1360 {
1361     QSqlDatabase db(driver);
1362     QSqlDatabasePrivate::addDatabase(db, connectionName);
1363     return db;
1364 }
1365 
1366 /*!
1367     Returns \c true if the QSqlDatabase has a valid driver.
1368 
1369     Example:
1370     \snippet code/src_sql_kernel_qsqldatabase.cpp 8
1371 */
isValid() const1372 bool QSqlDatabase::isValid() const
1373 {
1374     return d->driver && d->driver != d->shared_null()->driver;
1375 }
1376 
1377 /*!
1378     Clones the database connection \a other and stores it as \a
1379     connectionName. All the settings from the original database, e.g.
1380     databaseName(), hostName(), etc., are copied across. Does nothing
1381     if \a other is an invalid database. Returns the newly created
1382     database connection.
1383 
1384     \note The new connection has not been opened. Before using the new
1385     connection, you must call open().
1386 */
cloneDatabase(const QSqlDatabase & other,const QString & connectionName)1387 QSqlDatabase QSqlDatabase::cloneDatabase(const QSqlDatabase &other, const QString &connectionName)
1388 {
1389     if (!other.isValid())
1390         return QSqlDatabase();
1391 
1392     QSqlDatabase db(other.driverName());
1393     db.d->copy(other.d);
1394     QSqlDatabasePrivate::addDatabase(db, connectionName);
1395     return db;
1396 }
1397 
1398 /*!
1399     \since 5.13
1400     \overload
1401 
1402     Clones the database connection \a other and stores it as \a
1403     connectionName. All the settings from the original database, e.g.
1404     databaseName(), hostName(), etc., are copied across. Does nothing
1405     if \a other is an invalid database. Returns the newly created
1406     database connection.
1407 
1408     \note The new connection has not been opened. Before using the new
1409     connection, you must call open().
1410 
1411     This overload is useful when cloning the database in another thread to the
1412     one that is used by the database represented by \a other.
1413 */
1414 
cloneDatabase(const QString & other,const QString & connectionName)1415 QSqlDatabase QSqlDatabase::cloneDatabase(const QString &other, const QString &connectionName)
1416 {
1417     const QConnectionDict *dict = dbDict();
1418     Q_ASSERT(dict);
1419 
1420     dict->lock.lockForRead();
1421     QSqlDatabase otherDb = dict->value(other);
1422     dict->lock.unlock();
1423     if (!otherDb.isValid())
1424         return QSqlDatabase();
1425 
1426     QSqlDatabase db(otherDb.driverName());
1427     db.d->copy(otherDb.d);
1428     QSqlDatabasePrivate::addDatabase(db, connectionName);
1429     return db;
1430 }
1431 
1432 /*!
1433     \since 4.4
1434 
1435     Returns the connection name, which may be empty.  \note The
1436     connection name is not the \l{databaseName()} {database name}.
1437 
1438     \sa addDatabase()
1439 */
connectionName() const1440 QString QSqlDatabase::connectionName() const
1441 {
1442     return d->connName;
1443 }
1444 
1445 /*!
1446     \since 4.6
1447 
1448     Sets the default numerical precision policy used by queries created
1449     on this database connection to \a precisionPolicy.
1450 
1451     Note: Drivers that don't support fetching numerical values with low
1452     precision will ignore the precision policy. You can use
1453     QSqlDriver::hasFeature() to find out whether a driver supports this
1454     feature.
1455 
1456     Note: Setting the default precision policy to \a precisionPolicy
1457     doesn't affect any currently active queries.
1458 
1459     \sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(),
1460         QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()
1461 */
setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)1462 void QSqlDatabase::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
1463 {
1464     if(driver())
1465         driver()->setNumericalPrecisionPolicy(precisionPolicy);
1466     d->precisionPolicy = precisionPolicy;
1467 }
1468 
1469 /*!
1470     \since 4.6
1471 
1472     Returns the current default precision policy for the database connection.
1473 
1474     \sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy(),
1475         QSqlQuery::numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy()
1476 */
numericalPrecisionPolicy() const1477 QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy() const
1478 {
1479     if(driver())
1480         return driver()->numericalPrecisionPolicy();
1481     else
1482         return d->precisionPolicy;
1483 }
1484 
1485 
1486 #ifndef QT_NO_DEBUG_STREAM
operator <<(QDebug dbg,const QSqlDatabase & d)1487 QDebug operator<<(QDebug dbg, const QSqlDatabase &d)
1488 {
1489     QDebugStateSaver saver(dbg);
1490     dbg.nospace();
1491     dbg.noquote();
1492     if (!d.isValid()) {
1493         dbg << "QSqlDatabase(invalid)";
1494         return dbg;
1495     }
1496 
1497     dbg << "QSqlDatabase(driver=\"" << d.driverName() << "\", database=\""
1498         << d.databaseName() << "\", host=\"" << d.hostName() << "\", port=" << d.port()
1499         << ", user=\"" << d.userName() << "\", open=" << d.isOpen() << ')';
1500     return dbg;
1501 }
1502 #endif
1503 
1504 QT_END_NAMESPACE
1505