The module contains a few objects and function extending the minimum set of functionalities defined by the DB API 2.0.
Is the class usually returned by the connect() function. It is exposed by the extensions module in order to allow subclassing to extend its behaviour: the subclass should be passed to the connect() function using the connection_factory parameter. See also Connection and cursor factories.
For a complete description of the class, see connection.
It is the class usually returned by the connection.cursor() method. It is exposed by the extensions module in order to allow subclassing to extend its behaviour: the subclass should be passed to the cursor() method using the cursor_factory parameter. See also Connection and cursor factories.
For a complete description of the class, see cursor.
Wrapper for a PostgreSQL large object. See Access to PostgreSQL large objects for an overview.
The class can be subclassed: see the connection.lobject() to know how to specify a lobject subclass.
New in version 2.0.8.
Database OID of the object.
The mode the database was open. See connection.lobject() for a description of the available modes.
Read a chunk of data from the current file position. If -1 (default) read all the remaining data.
The result is an Unicode string (decoded according to connection.encoding) if the file was open in t mode, a bytes string for b mode.
Changed in version 2.4: added Unicode support.
Write a string to the large object. Return the number of bytes written. Unicode strings are encoded in the connection.encoding before writing.
Changed in version 2.4: added Unicode support.
Export the large object content to the file system.
The method uses the efficient lo_export() libpq function.
Set the lobject current position.
Changed in version 2.6.0: added support for offset > 2GB.
Return the lobject current position.
New in version 2.2.0.
Changed in version 2.6.0: added support for return value > 2GB.
Truncate the lobject to the given size.
The method will only be available if Psycopg has been built against libpq from PostgreSQL 8.3 or later and can only be used with PostgreSQL servers running these versions. It uses the lo_truncate() libpq function.
New in version 2.2.0.
Changed in version 2.6.0: added support for len > 2GB.
If Psycopg is built with lo_truncate() support or with the 64 bits API support (resp. from PostgreSQL versions 8.3 and 9.3) but at runtime an older version of the dynamic library is found, the psycopg2 module will fail to import. See the lo_truncate FAQ about the problem.
Close the object.
Boolean attribute specifying if the object is closed.
Close the object and remove it from the database.
A notification received from the backend.
Notify instances are made available upon reception on the notifies member of the listening connection. The object can be also accessed as a 2 items tuple returning the members (pid,channel) for backward compatibility.
See Asynchronous notifications for details.
New in version 2.3.
The name of the channel to which the notification was sent.
The payload message of the notification.
Attaching a payload to a notification is only available since PostgreSQL 9.0: for notifications received from previous versions of the server this member is always the empty string.
A transaction identifier used for two-phase commit.
Usually returned by the connection methods xid() and tpc_recover(). Xid instances can be unpacked as a 3-item tuples containing the items (format_id,gtrid,bqual). The str() of the object returns the transaction ID used in the commands sent to the server.
See Two-Phase Commit protocol support for an introduction.
New in version 2.3.
Create a Xid object from a string representation. Static method.
If s is a PostgreSQL transaction ID produced by a XA transaction, the returned object will have format_id, gtrid, bqual set to the values of the preparing XA id. Otherwise only the gtrid is populated with the unparsed string. The operation is the inverse of the one performed by str(xid).
Branch qualifier of the transaction.
In a XA transaction every resource participating to a transaction receives a distinct branch qualifier. None if the transaction doesn’t follow the XA standard.
Database the recovered transaction belongs to.
Format ID in a XA transaction.
A non-negative 32 bit integer. None if the transaction doesn’t follow the XA standard.
Global transaction ID in a XA transaction.
If the transaction doesn’t follow the XA standard, it is the plain transaction ID used in the server commands.
Name of the user who prepared a recovered transaction.
Timestamp (with timezone) in which a recovered transaction was prepared.
Details from a database error report.
The object is returned by the diag attribute of the Error object. All the information available from the PQresultErrorField() function are exposed as attributes by the object, e.g. the severity attribute returns the PG_DIAG_SEVERITY code. Please refer to the PostgreSQL documentation for the meaning of all the attributes.
New in version 2.5.
The attributes currently available are:
A string with the error field if available; None if not available. The attribute value is available only if the error sent by the server: not all the fields are available for all the errors and for all the server versions.
Register a callback function to block waiting for data.
The callback should have signature fun(conn) and is called to wait for data available whenever a blocking function from the libpq is called. Use set_wait_callback(None) to revert to the original behaviour (i.e. using blocking libpq functions).
See wait_select() for an example of a wait callback implementation.
New in version 2.2.0.
Return the currently registered wait callback.
Return None if no callback is currently registered.
New in version 2.2.0.
Psycopg provides a flexible system to adapt Python objects to the SQL syntax (inspired to the PEP 246), allowing serialization in PostgreSQL. See Adapting new Python types to SQL syntax for a detailed description. The following objects deal with Python objects adaptation:
Return the SQL representation of obj as an ISQLQuote. Raise a ProgrammingError if how to adapt the object is unknown. In order to allow new objects to be adapted, register a new adapter for it using the register_adapter() function.
The function is the entry point of the adaptation mechanism: it can be used to write adapters for complex objects by recursively calling adapt() on its components.
Register a new adapter for the objects of class class.
adapter should be a function taking a single argument (the object to adapt) and returning an object conforming to the ISQLQuote protocol (e.g. exposing a getquoted() method). The AsIs is often useful for this task.
Once an object is registered, it can be safely used in SQL queries and by the adapt() function.
Adapters may subclass ISQLQuote, but is not necessary: it is enough to expose a getquoted() method to be conforming.
The wrapped object passes to the constructor
Subclasses or other conforming objects should return a valid SQL string representing the wrapped object. In Python 3 the SQL must be returned in a bytes object. The ISQLQuote implementation does nothing.
Prepare the adapter for a connection. The method is optional: if implemented, it will be invoked before getquoted() with the connection to adapt for as argument.
A conform object can implement this method if the SQL representation depends on any server parameter, such as the server version or the standard_conforming_string setting. Container objects may store the connection and use it to recursively prepare contained objects: see the implementation for psycopg2.extensions.SQL_IN for a simple example.
Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.
Return the str() conversion of the wrapped object.
>>> AsIs(42).getquoted() '42'
Adapter conform to the ISQLQuote protocol for string-like objects.
Return the string enclosed in single quotes. Any single quote appearing in the the string is escaped by doubling it according to SQL string constants syntax. Backslashes are escaped too.
>>> QuotedString(r"O'Reilly").getquoted() "'O''Reilly'"
Adapter conform to the ISQLQuote protocol for binary objects.
Return the string enclosed in single quotes. It performs the same escaping of the QuotedString adapter, plus it knows how to escape non-printable chars.
>>> Binary("\x00\x08\x0F").getquoted() "'\\\\000\\\\010\\\\017'"
Changed in version 2.0.14: previously the adapter was not exposed by the extensions module. In older versions it can be imported from the implementation module psycopg2._psycopg.
Specialized adapters for builtin objects.
Specialized adapters for Python datetime objects.
Specialized adapters for mx.DateTime objects.
These functions are used to manipulate type casters to convert from PostgreSQL types to Python objects. See Type casting of SQL types into Python objects for details.
Create a new type caster to convert from a PostgreSQL type to a Python object. The object created must be registered using register_type() to be used.
The object OID can be read from the cursor.description attribute or by querying from the PostgreSQL catalog.
adapter should have signature fun(value, cur) where value is the string representation returned by PostgreSQL and cur is the cursor from which data are read. In case of NULL, value will be None. The adapter should return the converted object.
See Type casting of SQL types into Python objects for an usage example.
Create a new type caster to convert from a PostgreSQL array type to a list of Python object. The object created must be registered using register_type() to be used.
New in version 2.4.3.
The function can be used to create a generic array typecaster, returning a list of strings: just use psycopg2.STRING as base typecaster. For instance, if you want to receive an array of macaddr from the database, each address represented by string, you can use:
# select typarray from pg_type where typname = 'macaddr' -> 1040 psycopg2.extensions.register_type( psycopg2.extensions.new_array_type( (1040,), 'MACADDR', psycopg2.STRING))
Register a type caster created using new_type().
The global register of type casters.
Error related to SQL query cancellation. It can be trapped specifically to detect a timeout.
New in version 2.0.7.
Psycopg2 connection objects hold informations about the PostgreSQL transaction isolation level. The current transaction level can be read from the isolation_level attribute. The default isolation level is READ COMMITTED. A different isolation level con be set through the set_isolation_level() method. The level can be set to one of the following constants:
No transaction is started when command are issued and no commit() or rollback() is required. Some PostgreSQL command such as CREATE DATABASE or VACUUM can’t run into a transaction: to run such command use:
See also Transactions control.
The READ UNCOMMITTED isolation level is defined in the SQL standard but not available in the MVCC model of PostgreSQL: it is replaced by the stricter READ COMMITTED.
This is usually the the default PostgreSQL value, but a different default may be set in the database configuration.
A new transaction is started at the first execute() command on a cursor and at each new execute() after a commit() or a rollback(). The transaction runs in the PostgreSQL READ COMMITTED isolation level: a SELECT query sees only data committed before the query began; it never sees either uncommitted data or changes committed during query execution by concurrent transactions.
Read Committed Isolation Level in PostgreSQL documentation.
As in ISOLATION_LEVEL_READ_COMMITTED, a new transaction is started at the first execute() command. Transactions run at a REPEATABLE READ isolation level: all the queries in a transaction see a snapshot as of the start of the transaction, not as of the start of the current query within the transaction. However applications using this level must be prepared to retry transactions due to serialization failures.
While this level provides a guarantee that each transaction sees a completely stable view of the database, this view will not necessarily always be consistent with some serial (one at a time) execution of concurrent transactions of the same level.
Changed in version 2.4.2: The value was an alias for ISOLATION_LEVEL_SERIALIZABLE before. The two levels are distinct since PostgreSQL 9.1
Repeatable Read Isolation Level in PostgreSQL documentation.
As in ISOLATION_LEVEL_READ_COMMITTED, a new transaction is started at the first execute() command. Transactions run at a SERIALIZABLE isolation level. This is the strictest transactions isolation level, equivalent to having the transactions executed serially rather than concurrently. However applications using this level must be prepared to retry transactions due to serialization failures.
Starting from PostgreSQL 9.1, this mode monitors for conditions which could make execution of a concurrent set of serializable transactions behave in a manner inconsistent with all possible serial (one at a time) executions of those transaction. In previous version the behaviour was the same of the REPEATABLE READ isolation level.
Serializable Isolation Level in PostgreSQL documentation.
These values represent the possible status of a transaction: the current value can be read using the connection.get_transaction_status() method.
The session is idle and there is no current transaction.
A command is currently in progress.
The session is idle in a valid transaction block.
The session is idle in a failed transaction block.
Reported if the connection with the server is bad.
These values represent the possible status of a connection: the current value can be read from the status attribute.
It is possible to find the connection in other status than the one shown below. Those are the only states in which a working connection is expected to be found during the execution of regular Python client code: other states are for internal usage and Python code should not rely on them.
Connection established. No transaction in progress.
Connection established. A transaction is currently in progress.
New in version 2.2.0.
These values can be returned by connection.poll() during asynchronous connection and communication. They match the values in the libpq enum PostgresPollingStatusType. See Asynchronous support and Support for coroutine libraries.
The data being read is available, or the file descriptor is ready for writing: reading or writing will not block.
Some data is being read from the backend, but it is not available yet on the client and reading would block. Upon receiving this value, the client should wait for the connection file descriptor to be ready for reading. For example:
select.select([conn.fileno()], , )
Some data is being sent to the backend but the connection file descriptor can’t currently accept new data. Upon receiving this value, the client should wait for the connection file descriptor to be ready for writing. For example:
select.select(, [conn.fileno()], )
There was a problem during connection polling. This value should actually never be returned: in case of poll error usually an exception containing the relevant details is raised.
The extensions module includes typecasters for many standard PostgreSQL types. These objects allow the conversion of returned data into Python objects. All the typecasters are automatically registered, except UNICODE and UNICODEARRAY: you can register them using register_type() in order to receive Unicode objects instead of strings from the database. See Unicode handling for details.
Typecasters to convert arrays of sql types into Python lists.
Typecasters to convert time-related data types to Python datetime objects.
Typecasters to convert time-related data types to mx.DateTime objects. Only available if Psycopg was compiled with mx support.
Changed in version 2.2.0: previously the DECIMAL typecaster and the specific time-related typecasters (PY* and MX*) were not exposed by the extensions module. In older versions they can be imported from the implementation module psycopg2._psycopg.