psycopg2.extensions – Extensions to the DB API

The module contains a few objects and function extending the minimum set of functionalities defined by the DB API 2.0.

class psycopg2.extensions.connection

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.

class psycopg2.extensions.cursor

It is the class usually returnded 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.

class psycopg2.extensions.lobject(conn[, oid[, mode[, new_oid[, new_file]]]])

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.

oid
Database OID of the object.
mode
The mode the database was open (r, w, rw or n).
read(bytes=-1)
Read a chunk of data from the current file position. If -1 (default) read all the remaining data.
write(str)
Write a string to the large object. Return the number of bytes written.
export(file_name)

Export the large object content to the file system.

The method uses the efficient lo_export() libpq function.

seek(offset, whence=0)
Set the lobject current position.
tell()
Return the lobject current position.
close()
Close the object.
closed
Boolean attribute specifying if the object is closed.
Close the object and remove it from the database.

SQL adaptation protocol objects

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:

psycopg2.extensions.adapt(obj)

Return the SQL representation of obj as a string. 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.

psycopg2.extensions.register_adapter(class, adapter)

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 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.

class psycopg2.extensions.ISQLQuote(wrapped_object)

Represents the SQL adaptation protocol. Objects conforming this protocol should implement a getquoted() method.

Adapters may subclass ISQLQuote, but is not necessary: it is enough to expose a getquoted() method to be conforming.

_wrapped
The wrapped object passes to the constructor
getquoted()
Subclasses or other conforming objects should return a valid SQL string representing the wrapped object. The ISQLQuote implementation does nothing.
class psycopg2.extensions.AsIs

Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.

getquoted()

Return the str() conversion of the wrapped object.

>>> AsIs(42).getquoted()
'42'
class psycopg2.extensions.QuotedString

Adapter conform to the ISQLQuote protocol for string-like objects.

getquoted()

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'"
class psycopg2.extensions.Binary

Adapter conform to the ISQLQuote protocol for binary objects.

getquoted()

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 version it can be imported from the implementation module psycopg2._psycopg.

class psycopg2.extensions.Boolean
class psycopg2.extensions.Float
class psycopg2.extensions.SQL_IN
Specialized adapters for builtin objects.
class psycopg2.extensions.DateFromPy
class psycopg2.extensions.TimeFromPy
class psycopg2.extensions.TimestampFromPy
class psycopg2.extensions.IntervalFromPy
Specialized adapters for Python datetime objects.
class psycopg2.extensions.DateFromMx
class psycopg2.extensions.TimeFromMx
class psycopg2.extensions.TimestampFromMx
class psycopg2.extensions.IntervalFromMx
Specialized adapters for mx.DateTime objects.
psycopg2.extensions.adapters
Dictionary of the currently registered object adapters. Use register_adapter() to add an adapter for a new type.

Database types casting functions

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.

psycopg2.extensions.new_type(oids, name, adapter)

Create a new type caster to convert from a PostgreSQL type to a Python object. The created object must be registered using register_type() to be used.

Parameters:
  • oids – tuple of OIDs of the PostgreSQL type to convert.
  • name – the name of the new type adapter.
  • adapter – the adaptation function.

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.

psycopg2.extensions.register_type(obj[, scope])

Register a type caster created using new_type().

If scope is specified, it should be a connection or a cursor: the type caster will be effective only limited to the specified object. Otherwise it will be globally registered.

psycopg2.extensions.string_types
The global register of type casters.
psycopg2.extensions.encodings
Mapping from PostgreSQL encoding names to Python codec names. Used by Psycopg when adapting or casting unicode strings. See Unicode handling.

Additional exceptions

The module exports a few exceptions in addition to the standard ones defined by the DB API 2.0.

exception psycopg2.extensions.QueryCanceledError

(subclasses OperationalError)

Error related to SQL query cancelation. It can be trapped specifically to detect a timeout.

New in version 2.0.7.

exception psycopg2.extensions.TransactionRollbackError

(subclasses OperationalError)

Error causing transaction rollback (deadlocks, serialisation failures, etc). It can be trapped specifically to detect a deadlock.

New in version 2.0.7.

Isolation level constants

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:

psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT

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:

>>> conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)

See also Transactions control.

psycopg2.extensions.ISOLATION_LEVEL_READ_UNCOMMITTED
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.
psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED
This is the default value. 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.
psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ
The REPEATABLE READ isolation level is defined in the SQL standard but not available in the MVCC model of PostgreSQL: it is replaced by the stricter SERIALIZABLE.
psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE
Transactions are 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 reansactions due to serialization failures. See serializable isolation level in PostgreSQL documentation.

Transaction status constants

These values represent the possible status of a transaction: the current value can be read using the connection.get_transaction_status() method.

psycopg2.extensions.TRANSACTION_STATUS_IDLE
The session is idle and there is no current transaction.
psycopg2.extensions.TRANSACTION_STATUS_ACTIVE
A command is currently in progress.
psycopg2.extensions.TRANSACTION_STATUS_INTRANS
The session is idle in a valid transaction block.
psycopg2.extensions.TRANSACTION_STATUS_INERROR
The session is idle in a failed transaction block.
psycopg2.extensions.TRANSACTION_STATUS_UNKNOWN
Reported if the connection with the server is bad.

Connection status constants

These values represent the possible status of a connection: the current value can be read from the status attribute.

psycopg2.extensions.STATUS_SETUP
Used internally.
psycopg2.extensions.STATUS_READY
Connection established.
psycopg2.extensions.STATUS_BEGIN
Connection established. A transaction is in progress.
psycopg2.extensions.STATUS_IN_TRANSACTION
An alias for STATUS_BEGIN
psycopg2.extensions.STATUS_SYNC
Used internally.
psycopg2.extensions.STATUS_ASYNC
Used internally.

Additional database types

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.

psycopg2.extensions.BINARYARRAY
psycopg2.extensions.BOOLEAN
psycopg2.extensions.BOOLEANARRAY
psycopg2.extensions.DATE
psycopg2.extensions.DATEARRAY
psycopg2.extensions.DATETIMEARRAY
psycopg2.extensions.DECIMALARRAY
psycopg2.extensions.FLOAT
psycopg2.extensions.FLOATARRAY
psycopg2.extensions.INTEGER
psycopg2.extensions.INTEGERARRAY
psycopg2.extensions.INTERVAL
psycopg2.extensions.INTERVALARRAY
psycopg2.extensions.LONGINTEGER
psycopg2.extensions.LONGINTEGERARRAY
psycopg2.extensions.ROWIDARRAY
psycopg2.extensions.STRINGARRAY
psycopg2.extensions.TIME
psycopg2.extensions.TIMEARRAY
psycopg2.extensions.UNICODE
psycopg2.extensions.UNICODEARRAY