Qt 4.8
Public Types | Public Functions | Protected Slots | Protected Functions | Private Slots | Private Functions | Properties | List of all members
QPSQLDriver Class Reference

#include <qsql_psql.h>

Inheritance diagram for QPSQLDriver:
QSqlDriver QObject

Public Types

enum  Protocol {
  VersionUnknown = -1, Version6 = 6, Version7 = 7, Version71 = 8,
  Version73 = 9, Version74 = 10, Version8 = 11, Version81 = 12,
  Version82 = 13, Version83 = 14, Version84 = 15, Version9 = 16
}
 
- Public Types inherited from QSqlDriver
enum  DriverFeature {
  Transactions, QuerySize, BLOB, Unicode,
  PreparedQueries, NamedPlaceholders, PositionalPlaceholders, LastInsertId,
  BatchOperations, SimpleLocking, LowPrecisionNumbers, EventNotifications,
  FinishQuery, MultipleResultSets
}
 This enum contains a list of features a driver might support. More...
 
enum  IdentifierType { FieldName, TableName }
 This enum contains a list of SQL identifier types. More...
 
enum  StatementType {
  WhereStatement, SelectStatement, UpdateStatement, InsertStatement,
  DeleteStatement
}
 This enum contains a list of SQL statement (or clause) types the driver can create. More...
 

Public Functions

void close ()
 Derived classes must reimplement this pure virtual function in order to close the database connection. More...
 
QSqlResultcreateResult () const
 Creates an empty SQL result on the database. More...
 
QString escapeIdentifier (const QString &identifier, IdentifierType type) const
 Returns the identifier escaped according to the database rules. More...
 
QString formatValue (const QSqlField &field, bool trimStrings) const
 Returns a string representation of the field value for the database. More...
 
QVariant handle () const
 Returns the low-level database handle wrapped in a QVariant or an invalid variant if there is no handle. More...
 
bool hasFeature (DriverFeature f) const
 Returns true if the driver supports feature feature; otherwise returns false. More...
 
bool isOpen () const
 Returns true if the database connection is open; otherwise returns false. More...
 
bool open (const QString &db, const QString &user, const QString &password, const QString &host, int port, const QString &connOpts)
 Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options. More...
 
QSqlIndex primaryIndex (const QString &tablename) const
 Returns the primary index for table tableName. More...
 
Protocol protocol () const
 
 QPSQLDriver (QObject *parent=0)
 
 QPSQLDriver (PGconn *conn, QObject *parent=0)
 
QSqlRecord record (const QString &tablename) const
 Returns a QSqlRecord populated with the names of the fields in table tableName. More...
 
QStringList tables (QSql::TableType) const
 Returns a list of the names of the tables in the database. More...
 
 ~QPSQLDriver ()
 
- Public Functions inherited from QSqlDriver
bool isIdentifierEscaped (const QString &identifier, IdentifierType type) const
 Returns whether identifier is escaped according to the database rules. More...
 
bool isOpenError () const
 Returns true if the there was an error opening the database connection; otherwise returns false. More...
 
QSqlError lastError () const
 Returns a QSqlError object which contains information about the last error that occurred on the database. More...
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy () const
 Returns the current default precision policy for the database connection. More...
 
 QSqlDriver (QObject *parent=0)
 Constructs a new driver with the given parent. More...
 
void setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy)
 Sets the default numerical precision policy used by queries created by this driver to precisionPolicy. More...
 
virtual QString sqlStatement (StatementType type, const QString &tableName, const QSqlRecord &rec, bool preparedStatement) const
 Returns a SQL statement of type type for the table tableName with the values from rec. More...
 
QString stripDelimiters (const QString &identifier, IdentifierType type) const
 Returns the identifier with the leading and trailing delimiters removed, identifier can either be a table name or field name, dependent on type. More...
 
QStringList subscribedToNotifications () const
 Returns a list of the names of the event notifications that are currently subscribed to. More...
 
bool subscribeToNotification (const QString &name)
 This function is called to subscribe to event notifications from the database. More...
 
bool unsubscribeFromNotification (const QString &name)
 This function is called to unsubscribe from event notifications from the database. More...
 
 ~QSqlDriver ()
 Destroys the object and frees any allocated resources. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Slots

QStringList subscribedToNotificationsImplementation () const
 
bool subscribeToNotificationImplementation (const QString &name)
 
bool unsubscribeFromNotificationImplementation (const QString &name)
 
- Protected Slots inherited from QSqlDriver
bool isIdentifierEscapedImplementation (const QString &identifier, IdentifierType type) const
 This slot returns whether identifier is escaped according to the database rules. More...
 
QString stripDelimitersImplementation (const QString &identifier, IdentifierType type) const
 This slot returns identifier with the leading and trailing delimiters removed, identifier can either be a tablename or field name, dependent on type. More...
 
QStringList subscribedToNotificationsImplementation () const
 Returns a list of the names of the event notifications that are currently subscribed to. More...
 
bool subscribeToNotificationImplementation (const QString &name)
 This slot is called to subscribe to event notifications from the database. More...
 
bool unsubscribeFromNotificationImplementation (const QString &name)
 This slot is called to unsubscribe from event notifications from the database. More...
 

Protected Functions

bool beginTransaction ()
 This function is called to begin a transaction. More...
 
bool commitTransaction ()
 This function is called to commit a transaction. More...
 
bool rollbackTransaction ()
 This function is called to rollback a transaction. More...
 
- Protected Functions inherited from QSqlDriver
virtual void setLastError (const QSqlError &e)
 This function is used to set the value of the last error, error, that occurred on the database. More...
 
virtual void setOpen (bool o)
 This function sets the open state of the database to open. More...
 
virtual void setOpenError (bool e)
 This function sets the open error state of the database to error. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Private Slots

void _q_handleNotification (int)
 

Private Functions

void init ()
 

Properties

QPSQLDriverPrivated
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Signals inherited from QSqlDriver
void notification (const QString &name)
 This signal is emitted when the database posts an event notification that the driver subscribes to. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

Definition at line 95 of file qsql_psql.h.

Enumerations

◆ Protocol

Enumerator
VersionUnknown 
Version6 
Version7 
Version71 
Version73 
Version74 
Version8 
Version81 
Version82 
Version83 
Version84 
Version9 

Definition at line 99 of file qsql_psql.h.

Constructors and Destructors

◆ QPSQLDriver() [1/2]

QPSQLDriver::QPSQLDriver ( QObject parent = 0)
explicit

Definition at line 760 of file qsql_psql.cpp.

761  : QSqlDriver(parent)
762 {
763  init();
764 }
QSqlDriver(QObject *parent=0)
Constructs a new driver with the given parent.
Definition: qsqldriver.cpp:112
void init()
Definition: qsql_psql.cpp:779

◆ QPSQLDriver() [2/2]

QPSQLDriver::QPSQLDriver ( PGconn conn,
QObject parent = 0 
)
explicit

Definition at line 766 of file qsql_psql.cpp.

767  : QSqlDriver(parent)
768 {
769  init();
770  d->connection = conn;
771  if (conn) {
772  d->pro = d->getPSQLVersion();
774  setOpen(true);
775  setOpenError(false);
776  }
777 }
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
void detectBackslashEscape()
Definition: qsql_psql.cpp:650
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
QPSQLDriver::Protocol getPSQLVersion()
Definition: qsql_psql.cpp:711
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136
QSqlDriver(QObject *parent=0)
Constructs a new driver with the given parent.
Definition: qsqldriver.cpp:112
void init()
Definition: qsql_psql.cpp:779

◆ ~QPSQLDriver()

QPSQLDriver::~QPSQLDriver ( )

Definition at line 784 of file qsql_psql.cpp.

785 {
786  if (d->connection)
787  PQfinish(d->connection);
788  delete d;
789 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152

Functions

◆ _q_handleNotification

void QPSQLDriver::_q_handleNotification ( int  )
privateslot

Definition at line 1402 of file qsql_psql.cpp.

Referenced by close(), subscribeToNotificationImplementation(), and unsubscribeFromNotificationImplementation().

1403 {
1404  d->pendingNotifyCheck = false;
1405  PQconsumeInput(d->connection);
1406 
1407  PGnotify *notify = 0;
1408  while((notify = PQnotifies(d->connection)) != 0) {
1409  QString name(QLatin1String(notify->relname));
1410  if (d->seid.contains(name))
1412  else
1413  qWarning("QPSQLDriver: received notification for '%s' which isn't subscribed to.",
1414  qPrintable(name));
1415 
1416  qPQfreemem(notify);
1417  }
1418 }
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
void qPQfreemem(void *buffer)
Definition: qsql_psql.cpp:115
const char * name
#define emit
Definition: qobjectdefs.h:76
Q_CORE_EXPORT void qWarning(const char *,...)
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
QStringList seid
Definition: qsql_psql.cpp:138
#define qPrintable(string)
Definition: qglobal.h:1750
void notification(const QString &name)
This signal is emitted when the database posts an event notification that the driver subscribes to...

◆ beginTransaction()

bool QPSQLDriver::beginTransaction ( )
protectedvirtual

This function is called to begin a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
commitTransaction(), rollbackTransaction()

Reimplemented from QSqlDriver.

Definition at line 907 of file qsql_psql.cpp.

908 {
909  if (!isOpen()) {
910  qWarning("QPSQLDriver::beginTransaction: Database not open");
911  return false;
912  }
913  PGresult* res = d->exec("BEGIN");
914  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
915  setLastError(qMakeError(tr("Could not begin transaction"),
917  PQclear(res);
918  return false;
919  }
920  PQclear(res);
921  return true;
922 }
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
Q_CORE_EXPORT void qWarning(const char *,...)
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
struct pg_result PGresult
Definition: qsql_psql.h:57
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
PGresult * exec(const char *stmt) const
Definition: qsql_psql.cpp:175

◆ close()

void QPSQLDriver::close ( )
virtual

Derived classes must reimplement this pure virtual function in order to close the database connection.

Return true on success, false on failure.

See also
open(), setOpen()

Implements QSqlDriver.

Definition at line 883 of file qsql_psql.cpp.

Referenced by open().

884 {
885  if (isOpen()) {
886 
887  d->seid.clear();
888  if (d->sn) {
889  disconnect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
890  delete d->sn;
891  d->sn = 0;
892  }
893 
894  if (d->connection)
895  PQfinish(d->connection);
896  d->connection = 0;
897  setOpen(false);
898  setOpenError(false);
899  }
900 }
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
#define SLOT(a)
Definition: qobjectdefs.h:226
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
#define SIGNAL(a)
Definition: qobjectdefs.h:227
void clear()
Removes all items from the list.
Definition: qlist.h:764
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895
QSocketNotifier * sn
Definition: qsql_psql.cpp:137
void _q_handleNotification(int)
Definition: qsql_psql.cpp:1402
QStringList seid
Definition: qsql_psql.cpp:138

◆ commitTransaction()

bool QPSQLDriver::commitTransaction ( )
protectedvirtual

This function is called to commit a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
beginTransaction(), rollbackTransaction()

Reimplemented from QSqlDriver.

Definition at line 924 of file qsql_psql.cpp.

925 {
926  if (!isOpen()) {
927  qWarning("QPSQLDriver::commitTransaction: Database not open");
928  return false;
929  }
930  PGresult* res = d->exec("COMMIT");
931 
932  bool transaction_failed = false;
933 
934  // XXX
935  // This hack is used to tell if the transaction has succeeded for the protocol versions of
936  // PostgreSQL below. For 7.x and other protocol versions we are left in the dark.
937  // This hack can dissapear once there is an API to query this sort of information.
938  if (d->pro == QPSQLDriver::Version8 ||
944  transaction_failed = qstrcmp(PQcmdStatus(res), "ROLLBACK") == 0;
945  }
946 
947  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK || transaction_failed) {
948  setLastError(qMakeError(tr("Could not commit transaction"),
950  PQclear(res);
951  return false;
952  }
953  PQclear(res);
954  return true;
955 }
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
Q_CORE_EXPORT void qWarning(const char *,...)
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
struct pg_result PGresult
Definition: qsql_psql.h:57
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136
int qstrcmp(const QByteArray &str1, const char *str2)
Definition: qbytearray.cpp:336
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
PGresult * exec(const char *stmt) const
Definition: qsql_psql.cpp:175

◆ createResult()

QSqlResult * QPSQLDriver::createResult ( ) const
virtual

Creates an empty SQL result on the database.

Derived classes must reimplement this function and return a QSqlResult object appropriate for their database to the caller.

Implements QSqlDriver.

Definition at line 902 of file qsql_psql.cpp.

Referenced by primaryIndex(), record(), and tables().

903 {
904  return new QPSQLResult(this, d);
905 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152

◆ escapeIdentifier()

QString QPSQLDriver::escapeIdentifier ( const QString identifier,
IdentifierType  type 
) const
virtual

Returns the identifier escaped according to the database rules.

identifier can either be a table name or field name, dependent on type.

The default implementation does nothing.

See also
isIdentifierEscaped()

Reimplemented from QSqlDriver.

Definition at line 1308 of file qsql_psql.cpp.

Referenced by subscribeToNotificationImplementation(), and unsubscribeFromNotificationImplementation().

1309 {
1310  QString res = identifier;
1311  if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) {
1312  res.replace(QLatin1Char('"'), QLatin1String("\"\""));
1313  res.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
1314  res.replace(QLatin1Char('.'), QLatin1String("\".\""));
1315  }
1316  return res;
1317 }
QString & replace(int i, int len, QChar after)
Definition: qstring.cpp:2005
QString & prepend(QChar c)
Definition: qstring.h:261
bool startsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string starts with s; otherwise returns false.
Definition: qstring.cpp:3734
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
QString & append(QChar c)
Definition: qstring.cpp:1777
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition: qstring.cpp:3796
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ formatValue()

QString QPSQLDriver::formatValue ( const QSqlField field,
bool  trimStrings 
) const
virtual

Returns a string representation of the field value for the database.

Use the other formatValue() overload instead.

This is used, for example, when constructing INSERT and UPDATE statements.

The default implementation returns the value formatted as a string according to the following rules:

  • If field is character data, the value is returned enclosed in single quotation marks, which is appropriate for many SQL databases. Any embedded single-quote characters are escaped (replaced with two single-quote characters). If trimStrings is true (the default is false), all trailing whitespace is trimmed from the field.

  • If field is date/time data, the value is formatted in ISO format and enclosed in single quotation marks. If the date/time data is invalid, "NULL" is returned.

  • If field is bytearray data, and the driver can edit binary fields, the value is formatted as a hexadecimal string.

  • For any other field type, toString() is called on its value and the result of this is returned.

See also
QVariant::toString()

Reimplemented from QSqlDriver.

Definition at line 1223 of file qsql_psql.cpp.

1224 {
1225  QString r;
1226  if (field.isNull()) {
1227  r = QLatin1String("NULL");
1228  } else {
1229  switch (field.type()) {
1230  case QVariant::DateTime:
1231 #ifndef QT_NO_DATESTRING
1232  if (field.value().toDateTime().isValid()) {
1233  QDate dt = field.value().toDateTime().date();
1234  QTime tm = field.value().toDateTime().time();
1235  // msecs need to be right aligned otherwise psql
1236  // interpretes them wrong
1237  r = QLatin1Char('\'') + QString::number(dt.year()) + QLatin1Char('-')
1238  + QString::number(dt.month()) + QLatin1Char('-')
1239  + QString::number(dt.day()) + QLatin1Char(' ')
1240  + tm.toString() + QLatin1Char('.')
1241  + QString::number(tm.msec()).rightJustified(3, QLatin1Char('0'))
1242  + QLatin1Char('\'');
1243  } else {
1244  r = QLatin1String("NULL");
1245  }
1246 #else
1247  r = QLatin1String("NULL");
1248 #endif // QT_NO_DATESTRING
1249  break;
1250  case QVariant::Time:
1251 #ifndef QT_NO_DATESTRING
1252  if (field.value().toTime().isValid()) {
1253  r = QLatin1Char('\'') + field.value().toTime().toString(QLatin1String("hh:mm:ss.zzz")) + QLatin1Char('\'');
1254  } else
1255 #endif
1256  {
1257  r = QLatin1String("NULL");
1258  }
1259  break;
1260  case QVariant::String:
1261  r = QSqlDriver::formatValue(field, trimStrings);
1262  if (d->hasBackslashEscape)
1263  r.replace(QLatin1String("\\"), QLatin1String("\\\\"));
1264  break;
1265  case QVariant::Bool:
1266  if (field.value().toBool())
1267  r = QLatin1String("TRUE");
1268  else
1269  r = QLatin1String("FALSE");
1270  break;
1271  case QVariant::ByteArray: {
1272  QByteArray ba(field.value().toByteArray());
1273  size_t len;
1274 #if defined PG_VERSION_NUM && PG_VERSION_NUM-0 >= 80200
1275  unsigned char *data = PQescapeByteaConn(d->connection, (unsigned char*)ba.constData(), ba.size(), &len);
1276 #else
1277  unsigned char *data = PQescapeBytea((unsigned char*)ba.constData(), ba.size(), &len);
1278 #endif
1279  r += QLatin1Char('\'');
1280  r += QLatin1String((const char*)data);
1281  r += QLatin1Char('\'');
1282  qPQfreemem(data);
1283  break;
1284  }
1285  case QVariant::Double: {
1286  double val = field.value().toDouble();
1287  if (isnan(val))
1288  r = QLatin1String("'NaN'");
1289  else {
1290  int res = isinf(val);
1291  if (res == 1)
1292  r = QLatin1String("'Infinity'");
1293  else if (res == -1)
1294  r = QLatin1String("'-Infinity'");
1295  else
1296  r = QSqlDriver::formatValue(field, trimStrings);
1297  }
1298  break;
1299  }
1300  default:
1301  r = QSqlDriver::formatValue(field, trimStrings);
1302  break;
1303  }
1304  }
1305  return r;
1306 }
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
QVariant value() const
Returns the value of the field as a QVariant.
Definition: qsqlfield.h:71
QString & replace(int i, int len, QChar after)
Definition: qstring.cpp:2005
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
int month() const
Returns the number corresponding to the month of this date, using the following convention: ...
Definition: qdatetime.cpp:382
QDateTime toDateTime() const
Returns the variant as a QDateTime if the variant has type() DateTime , Date , or String ; otherwise ...
Definition: qvariant.cpp:2349
#define isinf(x)
Definition: qsql_psql.cpp:74
int day() const
Returns the day of the month (1 to 31) of this date.
Definition: qdatetime.cpp:395
bool isValid() const
Returns true if both the date and the time are valid; otherwise returns false.
Definition: qdatetime.cpp:2346
The QDate class provides date functions.
Definition: qdatetime.h:55
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
bool toBool() const
Returns the variant as a bool if the variant has type() Bool.
Definition: qvariant.cpp:2691
int msec() const
Returns the millisecond part (0 to 999) of the time.
Definition: qdatetime.cpp:1611
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define isnan(x)
Definition: qsql_psql.cpp:64
QByteArray toByteArray() const
Returns the variant as a QByteArray if the variant has type() ByteArray or String (converted using QS...
Definition: qvariant.cpp:2383
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
void qPQfreemem(void *buffer)
Definition: qsql_psql.cpp:115
The QTime class provides clock time functions.
Definition: qdatetime.h:148
static const char * data(const QByteArray &arr)
QVariant::Type type() const
Returns the field&#39;s type as stored in the database.
Definition: qsqlfield.cpp:394
QDate date() const
Returns the date part of the datetime.
Definition: qdatetime.cpp:2357
QString toString(Qt::DateFormat f=Qt::TextDate) const
Returns the time as a string.
Definition: qdatetime.cpp:1653
bool isNull() const
Returns true if the field&#39;s value is NULL; otherwise returns false.
Definition: qsqlfield.cpp:428
virtual QString formatValue(const QSqlField &field, bool trimStrings=false) const
Returns a string representation of the field value for the database.
Definition: qsqldriver.cpp:597
double toDouble(bool *ok=0) const
Returns the variant as a double if the variant has type() Double , QMetaType::Float ...
Definition: qvariant.cpp:2710
int year() const
Returns the year of this date.
Definition: qdatetime.cpp:353
QTime time() const
Returns the time part of the datetime.
Definition: qdatetime.cpp:2368
QTime toTime() const
Returns the variant as a QTime if the variant has type() Time , DateTime , or String ; otherwise retu...
Definition: qvariant.cpp:2330
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
bool isValid() const
Returns true if the time is valid; otherwise returns false.
Definition: qdatetime.cpp:1566

◆ handle()

QVariant QPSQLDriver::handle ( ) const
virtual

Returns the low-level database handle wrapped in a QVariant or an invalid variant if there is no handle.

Warning
Use this with uttermost care and only if you know what you're doing.
The handle returned here can become a stale pointer if the connection is modified (for example, if you close the connection).
The handle can be NULL if the connection is not open yet.

The handle returned here is database-dependent, you should query the type name of the variant before accessing it.

This example retrieves the handle for a connection to sqlite:

QSqlDatabase db = ...;
QVariant v = db.driver()->handle();
if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*") == 0) {
// v.data() returns a pointer to the handle
sqlite3 *handle = *static_cast<sqlite3 **>(v.data());
if (handle != 0) { // check that it is not NULL
...
}
}

This snippet returns the handle for PostgreSQL or MySQL:

if (qstrcmp(v.typeName(), "PGconn*") == 0) {
PGconn *handle = *static_cast<PGconn **>(v.data());
if (handle != 0) ...
}
if (qstrcmp(v.typeName(), "MYSQL*") == 0) {
MYSQL *handle = *static_cast<MYSQL **>(v.data());
if (handle != 0) ...
}
See also
QSqlResult::handle()

Reimplemented from QSqlDriver.

Definition at line 791 of file qsql_psql.cpp.

792 {
794 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
static QVariant fromValue(const T &value)
Returns a QVariant containing a copy of value.
Definition: qvariant.h:336

◆ hasFeature()

bool QPSQLDriver::hasFeature ( DriverFeature  feature) const
virtual

Returns true if the driver supports feature feature; otherwise returns false.

Note that some databases need to be open() before this can be determined.

See also
DriverFeature

Implements QSqlDriver.

Definition at line 796 of file qsql_psql.cpp.

Referenced by QPSQLResult::QPSQLResult().

797 {
798  switch (f) {
799  case Transactions:
800  case QuerySize:
801  case LastInsertId:
802  case LowPrecisionNumbers:
803  case EventNotifications:
804  return true;
805  case PreparedQueries:
807  return d->pro >= QPSQLDriver::Version82;
808  case BatchOperations:
809  case NamedPlaceholders:
810  case SimpleLocking:
811  case FinishQuery:
812  case MultipleResultSets:
813  return false;
814  case BLOB:
815  return d->pro >= QPSQLDriver::Version71;
816  case Unicode:
817  return d->isUtf8;
818  }
819  return false;
820 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136

◆ init()

void QPSQLDriver::init ( )
private

Definition at line 779 of file qsql_psql.cpp.

Referenced by QPSQLDriver().

780 {
781  d = new QPSQLDriverPrivate(this);
782 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152

◆ isOpen()

bool QPSQLDriver::isOpen ( ) const
virtual

Returns true if the database connection is open; otherwise returns false.

Reimplemented from QSqlDriver.

Definition at line 1319 of file qsql_psql.cpp.

Referenced by beginTransaction(), close(), commitTransaction(), open(), primaryIndex(), record(), rollbackTransaction(), subscribeToNotificationImplementation(), tables(), and unsubscribeFromNotificationImplementation().

1320 {
1321  return PQstatus(d->connection) == CONNECTION_OK;
1322 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152

◆ open()

bool QPSQLDriver::open ( const QString db,
const QString user,
const QString password,
const QString host,
int  port,
const QString options 
)
virtual

Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options.

The function must return true on success and false on failure.

See also
setOpen()

Implements QSqlDriver.

Definition at line 836 of file qsql_psql.cpp.

842 {
843  if (isOpen())
844  close();
845  QString connectString;
846  if (!host.isEmpty())
847  connectString.append(QLatin1String("host=")).append(qQuote(host));
848  if (!db.isEmpty())
849  connectString.append(QLatin1String(" dbname=")).append(qQuote(db));
850  if (!user.isEmpty())
851  connectString.append(QLatin1String(" user=")).append(qQuote(user));
852  if (!password.isEmpty())
853  connectString.append(QLatin1String(" password=")).append(qQuote(password));
854  if (port != -1)
855  connectString.append(QLatin1String(" port=")).append(qQuote(QString::number(port)));
856 
857  // add any connect options - the server will handle error detection
858  if (!connOpts.isEmpty()) {
859  QString opt = connOpts;
861  connectString.append(QLatin1Char(' ')).append(opt);
862  }
863 
864  d->connection = PQconnectdb(connectString.toLocal8Bit().constData());
865  if (PQstatus(d->connection) == CONNECTION_BAD) {
866  setLastError(qMakeError(tr("Unable to connect"), QSqlError::ConnectionError, d));
867  setOpenError(true);
868  PQfinish(d->connection);
869  d->connection = 0;
870  return false;
871  }
872 
873  d->pro = d->getPSQLVersion();
875  d->isUtf8 = d->setEncodingUtf8();
876  d->setDatestyle();
877 
878  setOpen(true);
879  setOpenError(false);
880  return true;
881 }
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
QString & replace(int i, int len, QChar after)
Definition: qstring.cpp:2005
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
void detectBackslashEscape()
Definition: qsql_psql.cpp:650
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
static QString qQuote(QString s)
Definition: qsql_psql.cpp:828
QPSQLDriver::Protocol getPSQLVersion()
Definition: qsql_psql.cpp:711
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
QString & append(QChar c)
Definition: qstring.cpp:1777
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
void close()
Derived classes must reimplement this pure virtual function in order to close the database connection...
Definition: qsql_psql.cpp:883

◆ primaryIndex()

QSqlIndex QPSQLDriver::primaryIndex ( const QString tableName) const
virtual

Returns the primary index for table tableName.

Returns an empty QSqlIndex if the table doesn't have a primary index. The default implementation returns an empty index.

Reimplemented from QSqlDriver.

Definition at line 1005 of file qsql_psql.cpp.

1006 {
1007  QSqlIndex idx(tablename);
1008  if (!isOpen())
1009  return idx;
1010  QSqlQuery i(createResult());
1011  QString stmt;
1012 
1013  QString tbl = tablename;
1014  QString schema;
1015  qSplitTableName(tbl, schema);
1016 
1019  else
1020  tbl = tbl.toLower();
1021 
1023  schema = stripDelimiters(schema, QSqlDriver::TableName);
1024  else
1025  schema = schema.toLower();
1026 
1027  switch(d->pro) {
1028  case QPSQLDriver::Version6:
1029  stmt = QLatin1String("select pg_att1.attname, int(pg_att1.atttypid), pg_cl.relname "
1030  "from pg_attribute pg_att1, pg_attribute pg_att2, pg_class pg_cl, pg_index pg_ind "
1031  "where pg_cl.relname = '%1_pkey' "
1032  "and pg_cl.oid = pg_ind.indexrelid "
1033  "and pg_att2.attrelid = pg_ind.indexrelid "
1034  "and pg_att1.attrelid = pg_ind.indrelid "
1035  "and pg_att1.attnum = pg_ind.indkey[pg_att2.attnum-1] "
1036  "order by pg_att2.attnum");
1037  break;
1038  case QPSQLDriver::Version7:
1040  stmt = QLatin1String("select pg_att1.attname, pg_att1.atttypid::int, pg_cl.relname "
1041  "from pg_attribute pg_att1, pg_attribute pg_att2, pg_class pg_cl, pg_index pg_ind "
1042  "where pg_cl.relname = '%1_pkey' "
1043  "and pg_cl.oid = pg_ind.indexrelid "
1044  "and pg_att2.attrelid = pg_ind.indexrelid "
1045  "and pg_att1.attrelid = pg_ind.indrelid "
1046  "and pg_att1.attnum = pg_ind.indkey[pg_att2.attnum-1] "
1047  "order by pg_att2.attnum");
1048  break;
1051  case QPSQLDriver::Version8:
1056  case QPSQLDriver::Version9:
1057  stmt = QLatin1String("SELECT pg_attribute.attname, pg_attribute.atttypid::int, "
1058  "pg_class.relname "
1059  "FROM pg_attribute, pg_class "
1060  "WHERE %1 pg_class.oid IN "
1061  "(SELECT indexrelid FROM pg_index WHERE indisprimary = true AND indrelid IN "
1062  " (SELECT oid FROM pg_class WHERE relname = '%2')) "
1063  "AND pg_attribute.attrelid = pg_class.oid "
1064  "AND pg_attribute.attisdropped = false "
1065  "ORDER BY pg_attribute.attnum");
1066  if (schema.isEmpty())
1067  stmt = stmt.arg(QLatin1String("pg_table_is_visible(pg_class.oid) AND"));
1068  else
1069  stmt = stmt.arg(QString::fromLatin1("pg_class.relnamespace = (select oid from "
1070  "pg_namespace where pg_namespace.nspname = '%1') AND ").arg(schema));
1071  break;
1073  qFatal("PSQL version is unknown");
1074  break;
1075  }
1076 
1077  i.exec(stmt.arg(tbl));
1078  while (i.isActive() && i.next()) {
1079  QSqlField f(i.value(0).toString(), qDecodePSQLType(i.value(1).toInt()));
1080  idx.append(f);
1081  idx.setName(i.value(2).toString());
1082  }
1083  return idx;
1084 }
The QSqlIndex class provides functions to manipulate and describe database indexes.
Definition: qsqlindex.h:55
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isIdentifierEscaped(const QString &identifier, IdentifierType type) const
Returns whether identifier is escaped according to the database rules.
Definition: qsqldriver.cpp:429
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136
static QVariant::Type qDecodePSQLType(int t)
Definition: qsql_psql.cpp:239
Q_CORE_EXPORT void qFatal(const char *,...)
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const Q_REQUIRED_RESULT
Definition: qstring.cpp:7186
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
QString toLower() const Q_REQUIRED_RESULT
Returns a lowercase copy of the string.
Definition: qstring.cpp:5389
QSqlResult * createResult() const
Creates an empty SQL result on the database.
Definition: qsql_psql.cpp:902
The QSqlField class manipulates the fields in SQL database tables and views.
Definition: qsqlfield.h:56
static void qSplitTableName(QString &tablename, QString &schema)
Definition: qsql_psql.cpp:996
QString stripDelimiters(const QString &identifier, IdentifierType type) const
Returns the identifier with the leading and trailing delimiters removed, identifier can either be a t...
Definition: qsqldriver.cpp:455

◆ protocol()

QPSQLDriver::Protocol QPSQLDriver::protocol ( ) const

Definition at line 1324 of file qsql_psql.cpp.

1325 {
1326  return d->pro;
1327 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136

◆ record()

QSqlRecord QPSQLDriver::record ( const QString tableName) const
virtual

Returns a QSqlRecord populated with the names of the fields in table tableName.

Use query.

If no such table exists, an empty record is returned. The default implementation returns an empty record.

record() instead.

Reimplemented from QSqlDriver.

Definition at line 1086 of file qsql_psql.cpp.

1087 {
1088  QSqlRecord info;
1089  if (!isOpen())
1090  return info;
1091 
1092  QString tbl = tablename;
1093  QString schema;
1094  qSplitTableName(tbl, schema);
1095 
1098  else
1099  tbl = tbl.toLower();
1100 
1102  schema = stripDelimiters(schema, QSqlDriver::TableName);
1103  else
1104  schema = schema.toLower();
1105 
1106  QString stmt;
1107  switch(d->pro) {
1108  case QPSQLDriver::Version6:
1109  stmt = QLatin1String("select pg_attribute.attname, int(pg_attribute.atttypid), "
1110  "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
1111  "int(pg_attribute.attrelid), pg_attribute.attnum "
1112  "from pg_class, pg_attribute "
1113  "where pg_class.relname = '%1' "
1114  "and pg_attribute.attnum > 0 "
1115  "and pg_attribute.attrelid = pg_class.oid ");
1116  break;
1117  case QPSQLDriver::Version7:
1118  stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
1119  "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
1120  "pg_attribute.attrelid::int, pg_attribute.attnum "
1121  "from pg_class, pg_attribute "
1122  "where pg_class.relname = '%1' "
1123  "and pg_attribute.attnum > 0 "
1124  "and pg_attribute.attrelid = pg_class.oid ");
1125  break;
1127  stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
1128  "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
1129  "pg_attrdef.adsrc "
1130  "from pg_class, pg_attribute "
1131  "left join pg_attrdef on (pg_attrdef.adrelid = "
1132  "pg_attribute.attrelid and pg_attrdef.adnum = pg_attribute.attnum) "
1133  "where pg_class.relname = '%1' "
1134  "and pg_attribute.attnum > 0 "
1135  "and pg_attribute.attrelid = pg_class.oid "
1136  "order by pg_attribute.attnum ");
1137  break;
1140  case QPSQLDriver::Version8:
1145  case QPSQLDriver::Version9:
1146  stmt = QLatin1String("select pg_attribute.attname, pg_attribute.atttypid::int, "
1147  "pg_attribute.attnotnull, pg_attribute.attlen, pg_attribute.atttypmod, "
1148  "pg_attrdef.adsrc "
1149  "from pg_class, pg_attribute "
1150  "left join pg_attrdef on (pg_attrdef.adrelid = "
1151  "pg_attribute.attrelid and pg_attrdef.adnum = pg_attribute.attnum) "
1152  "where %1 "
1153  "and pg_class.relname = '%2' "
1154  "and pg_attribute.attnum > 0 "
1155  "and pg_attribute.attrelid = pg_class.oid "
1156  "and pg_attribute.attisdropped = false "
1157  "order by pg_attribute.attnum ");
1158  if (schema.isEmpty())
1159  stmt = stmt.arg(QLatin1String("pg_table_is_visible(pg_class.oid)"));
1160  else
1161  stmt = stmt.arg(QString::fromLatin1("pg_class.relnamespace = (select oid from "
1162  "pg_namespace where pg_namespace.nspname = '%1')").arg(schema));
1163  break;
1165  qFatal("PSQL version is unknown");
1166  break;
1167  }
1168 
1169  QSqlQuery query(createResult());
1170  query.exec(stmt.arg(tbl));
1171  if (d->pro >= QPSQLDriver::Version71) {
1172  while (query.next()) {
1173  int len = query.value(3).toInt();
1174  int precision = query.value(4).toInt();
1175  // swap length and precision if length == -1
1176  if (len == -1 && precision > -1) {
1177  len = precision - 4;
1178  precision = -1;
1179  }
1180  QString defVal = query.value(5).toString();
1181  if (!defVal.isEmpty() && defVal.at(0) == QLatin1Char('\''))
1182  defVal = defVal.mid(1, defVal.length() - 2);
1183  QSqlField f(query.value(0).toString(), qDecodePSQLType(query.value(1).toInt()));
1184  f.setRequired(query.value(2).toBool());
1185  f.setLength(len);
1186  f.setPrecision(precision);
1187  f.setDefaultValue(defVal);
1188  f.setSqlType(query.value(1).toInt());
1189  info.append(f);
1190  }
1191  } else {
1192  // Postgres < 7.1 cannot handle outer joins
1193  while (query.next()) {
1194  QString defVal;
1195  QString stmt2 = QLatin1String("select pg_attrdef.adsrc from pg_attrdef where "
1196  "pg_attrdef.adrelid = %1 and pg_attrdef.adnum = %2 ");
1197  QSqlQuery query2(createResult());
1198  query2.exec(stmt2.arg(query.value(5).toInt()).arg(query.value(6).toInt()));
1199  if (query2.isActive() && query2.next())
1200  defVal = query2.value(0).toString();
1201  if (!defVal.isEmpty() && defVal.at(0) == QLatin1Char('\''))
1202  defVal = defVal.mid(1, defVal.length() - 2);
1203  int len = query.value(3).toInt();
1204  int precision = query.value(4).toInt();
1205  // swap length and precision if length == -1
1206  if (len == -1 && precision > -1) {
1207  len = precision - 4;
1208  precision = -1;
1209  }
1210  QSqlField f(query.value(0).toString(), qDecodePSQLType(query.value(1).toInt()));
1211  f.setRequired(query.value(2).toBool());
1212  f.setLength(len);
1213  f.setPrecision(precision);
1214  f.setDefaultValue(defVal);
1215  f.setSqlType(query.value(1).toInt());
1216  info.append(f);
1217  }
1218  }
1219 
1220  return info;
1221 }
static mach_timebase_info_data_t info
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
int toInt(bool *ok=0, int base=10) const
Returns the string converted to an int using base base, which is 10 by default and must be between 2 ...
Definition: qstring.cpp:6090
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isIdentifierEscaped(const QString &identifier, IdentifierType type) const
Returns whether identifier is escaped according to the database rules.
Definition: qsqldriver.cpp:429
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
QPSQLDriver::Protocol pro
Definition: qsql_psql.cpp:136
static QVariant::Type qDecodePSQLType(int t)
Definition: qsql_psql.cpp:239
QString mid(int position, int n=-1) const Q_REQUIRED_RESULT
Returns a string that contains n characters of this string, starting at the specified position index...
Definition: qstring.cpp:3706
Q_CORE_EXPORT void qFatal(const char *,...)
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const Q_REQUIRED_RESULT
Definition: qstring.cpp:7186
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
QString toLower() const Q_REQUIRED_RESULT
Returns a lowercase copy of the string.
Definition: qstring.cpp:5389
QSqlResult * createResult() const
Creates an empty SQL result on the database.
Definition: qsql_psql.cpp:902
void append(const QSqlField &field)
Append a copy of field field to the end of the record.
Definition: qsqlrecord.cpp:312
The QSqlField class manipulates the fields in SQL database tables and views.
Definition: qsqlfield.h:56
static void qSplitTableName(QString &tablename, QString &schema)
Definition: qsql_psql.cpp:996
QString stripDelimiters(const QString &identifier, IdentifierType type) const
Returns the identifier with the leading and trailing delimiters removed, identifier can either be a t...
Definition: qsqldriver.cpp:455
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ rollbackTransaction()

bool QPSQLDriver::rollbackTransaction ( )
protectedvirtual

This function is called to rollback a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
beginTransaction(), commitTransaction()

Reimplemented from QSqlDriver.

Definition at line 957 of file qsql_psql.cpp.

958 {
959  if (!isOpen()) {
960  qWarning("QPSQLDriver::rollbackTransaction: Database not open");
961  return false;
962  }
963  PGresult* res = d->exec("ROLLBACK");
964  if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
965  setLastError(qMakeError(tr("Could not rollback transaction"),
967  PQclear(res);
968  return false;
969  }
970  PQclear(res);
971  return true;
972 }
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
Q_CORE_EXPORT void qWarning(const char *,...)
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
struct pg_result PGresult
Definition: qsql_psql.h:57
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
PGresult * exec(const char *stmt) const
Definition: qsql_psql.cpp:175

◆ subscribedToNotificationsImplementation

QStringList QPSQLDriver::subscribedToNotificationsImplementation ( ) const
protectedslot

Definition at line 1397 of file qsql_psql.cpp.

1398 {
1399  return d->seid;
1400 }
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
QStringList seid
Definition: qsql_psql.cpp:138

◆ subscribeToNotificationImplementation

bool QPSQLDriver::subscribeToNotificationImplementation ( const QString name)
protectedslot

Definition at line 1329 of file qsql_psql.cpp.

1330 {
1331  if (!isOpen()) {
1332  qWarning("QPSQLDriver::subscribeToNotificationImplementation: database not open.");
1333  return false;
1334  }
1335 
1336  if (d->seid.contains(name)) {
1337  qWarning("QPSQLDriver::subscribeToNotificationImplementation: already subscribing to '%s'.",
1338  qPrintable(name));
1339  return false;
1340  }
1341 
1342  int socket = PQsocket(d->connection);
1343  if (socket) {
1344  // Add the name to the list of subscriptions here so that QSQLDriverPrivate::exec knows
1345  // to check for notifications immediately after executing the LISTEN
1346  d->seid << name;
1347  QString query = QLatin1String("LISTEN ") + escapeIdentifier(name, QSqlDriver::TableName);
1348  PGresult *result = d->exec(query);
1349  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1350  setLastError(qMakeError(tr("Unable to subscribe"), QSqlError::StatementError, d, result));
1351  return false;
1352  }
1353 
1354  if (!d->sn) {
1355  d->sn = new QSocketNotifier(socket, QSocketNotifier::Read);
1356  connect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
1357  }
1358  } else {
1359  qWarning("QPSQLDriver::subscribeToNotificationImplementation: PQsocket didn't return a valid socket to listen on");
1360  return false;
1361  }
1362 
1363  return true;
1364 }
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
#define SLOT(a)
Definition: qobjectdefs.h:226
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
The QSocketNotifier class provides support for monitoring activity on a file descriptor.
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
#define SIGNAL(a)
Definition: qobjectdefs.h:227
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
const char * name
Q_CORE_EXPORT void qWarning(const char *,...)
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
struct pg_result PGresult
Definition: qsql_psql.h:57
QSocketNotifier * sn
Definition: qsql_psql.cpp:137
void _q_handleNotification(int)
Definition: qsql_psql.cpp:1402
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
QStringList seid
Definition: qsql_psql.cpp:138
#define qPrintable(string)
Definition: qglobal.h:1750
PGresult * exec(const char *stmt) const
Definition: qsql_psql.cpp:175
QString escapeIdentifier(const QString &identifier, IdentifierType type) const
Returns the identifier escaped according to the database rules.
Definition: qsql_psql.cpp:1308

◆ tables()

QStringList QPSQLDriver::tables ( QSql::TableType  tableType) const
virtual

Returns a list of the names of the tables in the database.

The default implementation returns an empty list.

The tableType argument describes what types of tables should be returned. Due to binary compatibility, the string contains the value of the enum QSql::TableTypes as text. An empty string should be treated as QSql::Tables for backward compatibility.

Reimplemented from QSqlDriver.

Definition at line 974 of file qsql_psql.cpp.

975 {
976  QStringList tl;
977  if (!isOpen())
978  return tl;
979  QSqlQuery t(createResult());
980  t.setForwardOnly(true);
981 
982  if (type & QSql::Tables)
983  d->appendTables(tl, t, QLatin1Char('r'));
984  if (type & QSql::Views)
985  d->appendTables(tl, t, QLatin1Char('v'));
986  if (type & QSql::SystemTables) {
987  t.exec(QLatin1String("select relname from pg_class where (relkind = 'r') "
988  "and (relname like 'pg_%') "));
989  while (t.next())
990  tl.append(t.value(0).toString());
991  }
992 
993  return tl;
994 }
int type
Definition: qmetatype.cpp:239
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
void appendTables(QStringList &tl, QSqlQuery &t, QChar type)
Definition: qsql_psql.cpp:151
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QSqlResult * createResult() const
Creates an empty SQL result on the database.
Definition: qsql_psql.cpp:902
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ unsubscribeFromNotificationImplementation

bool QPSQLDriver::unsubscribeFromNotificationImplementation ( const QString name)
protectedslot

Definition at line 1366 of file qsql_psql.cpp.

1367 {
1368  if (!isOpen()) {
1369  qWarning("QPSQLDriver::unsubscribeFromNotificationImplementation: database not open.");
1370  return false;
1371  }
1372 
1373  if (!d->seid.contains(name)) {
1374  qWarning("QPSQLDriver::unsubscribeFromNotificationImplementation: not subscribed to '%s'.",
1375  qPrintable(name));
1376  return false;
1377  }
1378 
1379  QString query = QLatin1String("UNLISTEN ") + escapeIdentifier(name, QSqlDriver::TableName);
1380  PGresult *result = d->exec(query);
1381  if (PQresultStatus(result) != PGRES_COMMAND_OK) {
1382  setLastError(qMakeError(tr("Unable to unsubscribe"), QSqlError::StatementError, d, result));
1383  return false;
1384  }
1385 
1386  d->seid.removeAll(name);
1387 
1388  if (d->seid.isEmpty()) {
1389  disconnect(d->sn, SIGNAL(activated(int)), this, SLOT(_q_handleNotification(int)));
1390  delete d->sn;
1391  d->sn = 0;
1392  }
1393 
1394  return true;
1395 }
bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsql_psql.cpp:1319
#define SLOT(a)
Definition: qobjectdefs.h:226
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
QPSQLDriverPrivate * d
Definition: qsql_psql.h:152
#define SIGNAL(a)
Definition: qobjectdefs.h:227
Q_CORE_EXPORT void qWarning(const char *,...)
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QPSQLDriverPrivate *p, PGresult *result=0)
Definition: qsql_psql.cpp:205
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
struct pg_result PGresult
Definition: qsql_psql.h:57
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895
QSocketNotifier * sn
Definition: qsql_psql.cpp:137
void _q_handleNotification(int)
Definition: qsql_psql.cpp:1402
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
QStringList seid
Definition: qsql_psql.cpp:138
#define qPrintable(string)
Definition: qglobal.h:1750
PGresult * exec(const char *stmt) const
Definition: qsql_psql.cpp:175
QString escapeIdentifier(const QString &identifier, IdentifierType type) const
Returns the identifier escaped according to the database rules.
Definition: qsql_psql.cpp:1308
int removeAll(const T &t)
Removes all occurrences of value in the list and returns the number of entries removed.
Definition: qlist.h:770

Properties

◆ d

QPSQLDriverPrivate* QPSQLDriver::d
private

The documentation for this class was generated from the following files: