Connection classes#
The Connection and AsyncConnection classes are the main wrappers for a
PostgreSQL database session. You can imagine them similar to a psql
session.
One of the differences compared to psql is that a Connection
usually handles a transaction automatically: other sessions will not be able
to see the changes until you have committed them, more or less explicitly.
Take a look to Transactions management for the details.
The Connection class#
- class psycopg.Connection#
Wrapper for a connection to the database.
This class implements a DBAPI-compliant interface. It is what you want to use if you write a “classic”, blocking program (eventually using threads or Eventlet/gevent for concurrency). If your program uses
asyncioyou might want to useAsyncConnectioninstead.Connections behave as context managers: on block exit, the current transaction will be committed (or rolled back, in case of exception) and the connection will be closed.
- classmethod connect(conninfo: str = '', *, autocommit: bool = False, prepare_threshold: int | None = 5, context: Optional[AdaptContext] = None, row_factory: Optional[RowFactory[Row]] = None, cursor_factory: Cursor[+Row]]] = None, **kwargs: Optional[Union[str, int]]) Self#
Connect to a database server and return a new
Connectioninstance.- Parameters:
conninfo – The connection string (a
postgresql://url or a list ofkey=valuepairs) to specify where and how to connect.kwargs – Further parameters specifying the connection string. They override the ones specified in
conninfo.autocommit – If
Truedon’t start transactions automatically. See Transactions management for details.row_factory – The row factory specifying what type of records to create fetching data (default:
tuple_row()). See Row factories for details.cursor_factory – Initial value for the
cursor_factoryattribute of the connection (new in Psycopg 3.1).prepare_threshold – Initial value for the
prepare_thresholdattribute of the connection (new in Psycopg 3.1).
More specialized use:
- Parameters:
context – A context to copy the initial adapters configuration from. It might be an
AdaptersMapwith customized loaders and dumpers, used as a template to create several connections. See Data adaptation configuration for further details.
This method is also aliased as
psycopg.connect().See also
the list of the accepted connection parameters
the environment variables affecting connection
Changed in version 3.1: added
prepare_thresholdandcursor_factoryparameters.
- adapters: AdaptersMap#
The adapters configuration used to convert Python parameters and PostgreSQL results for the queries executed on this cursor.
It affects all the cursors created by this connection afterwards.
- close() None#
Close the database connection.
Note
You can use:
with psycopg.connect() as conn: ...
to close the connection automatically when the block is exited. See Connection context.
- closed#
Trueif the connection is closed.
- broken#
Trueif the connection was interrupted.A broken connection is always
closed, but wasn’t closed in a clean way, such as usingclose()or awithblock.
- cursor(*, binary: bool = False, row_factory: Optional[RowFactory] = None) Cursor#
- cursor(name: str, *, binary: bool = False, row_factory: Optional[RowFactory] = None, scrollable: Optional[bool] = None, withhold: bool = False) ServerCursor
Return a new cursor to send commands and queries to the connection.
- Parameters:
name – If not specified create a client-side cursor, if specified create a server-side cursor. See Cursor types for details.
binary – If
Truereturn binary values from the database. All the types returned by the query must have a binary loader. See Binary parameters and results for details.row_factory – If specified override the
row_factoryset on the connection. See Row factories for details.scrollable – Specify the
scrollableproperty of the server-side cursor created.withhold – Specify the
withholdproperty of the server-side cursor created.
- Returns:
A cursor of the class specified by
cursor_factory(orserver_cursor_factoryifnameis specified).
Note
You can use:
with conn.cursor() as cur: ...
to close the cursor automatically when the block is exited.
- cursor_factory: type[Cursor[Row]]#
The type, or factory function, returned by
cursor()andexecute().Default is
psycopg.Cursor.
- server_cursor_factory: type[ServerCursor[Row]]#
The type, or factory function, returned by
cursor()when a name is specified.Default is
psycopg.ServerCursor.
- row_factory: RowFactory[Row]#
The row factory defining the type of rows returned by
fetchone()and the other cursor fetch methods.The default is
tuple_row, which means that the fetch methods will return simple tuples.See also
See Row factories for details about defining the objects returned by cursors.
- execute(query: QueryNoTemplate, params: Optional[Union[Sequence[Any], Mapping[str, Any]]] = None, *, prepare: bool | None = None, binary: bool = False) Cursor[Row]#
- execute(query: Template, *, prepare: bool | None = None, binary: bool = False) Cursor[Row]
Execute a query and return a cursor to read its results.
- Parameters:
query (
LiteralString,bytes,sql.SQL,sql.Composed, orTemplate) – The query to execute.params (Sequence or Mapping) – The parameters to pass to the query, if any. Can’t be specified if
queryis aTemplate.prepare – Force (
True) or disallow (False) preparation of the query. By default (None) prepare automatically. See Prepared statements.binary – If
Truethe cursor will return binary values from the database. All the types returned by the query must have a binary loader. See Binary parameters and results for details.
The method simply creates a
Cursorinstance,execute()the query requested, and returns it.See Passing parameters to SQL queries for all the details about executing queries.
- pipeline() Iterator[Pipeline]#
Context manager to switch the connection into pipeline mode.
The method is a context manager: you should call it using:
with conn.pipeline() as p: ...
At the end of the block, a synchronization point is established and the connection returns in normal mode.
You can call the method recursively from within a pipeline block. Innermost blocks will establish a synchronization point on exit, but pipeline mode will be kept until the outermost block exits.
See Pipeline mode support for details.
New in version 3.1.
Transaction management methods
For details see Transactions management.
- transaction(savepoint_name: str | None = None, force_rollback: bool = False) Iterator[Transaction]#
Start a context block with a new transaction or nested transaction.
- Parameters:
savepoint_name – Name of the savepoint used to manage a nested transaction. If
None, one will be chosen automatically.force_rollback – Roll back the transaction at the end of the block even if there were no error (e.g. to try a no-op process).
- Return type:
Note
The method must be called with a syntax such as:
with conn.transaction(): ... with conn.transaction() as tx: ...
The latter is useful if you need to interact with the
Transactionobject. See Transaction contexts for details.Inside a transaction block it will not be possible to call
commit()orrollback().
- autocommit#
The autocommit state of the connection.
The property is writable for sync connections, read-only for async ones: you should call
awaitset_autocommit(value)instead.
- set_autocommit(value: bool) None#
Method version of the
autocommitsetter.New in version 3.2.
The following three properties control the characteristics of new transactions. See Transaction characteristics for details.
- isolation_level#
The isolation level of the new transactions started on the connection.
Nonemeans use the default set in the default_transaction_isolation configuration parameter of the server.
- set_isolation_level(value: psycopg.IsolationLevel | None) None#
Method version of the
isolation_levelsetter.New in version 3.2.
- read_only#
The read-only state of the new transactions started on the connection.
Nonemeans use the default set in the default_transaction_read_only configuration parameter of the server.
- deferrable#
The deferrable state of the new transactions started on the connection.
Nonemeans use the default set in the default_transaction_deferrable configuration parameter of the server.
- set_deferrable(value: bool | None) None#
Method version of the
deferrablesetter.New in version 3.2.
Checking and configuring the connection state
- pgconn: psycopg.pq.PGconn#
The
PGconnlibpq connection wrapper underlying theConnection.It can be used to send low level commands to PostgreSQL and access features not currently wrapped by Psycopg.
- info#
A
ConnectionInfoattribute to inspect connection properties.
- prepare_threshold#
Number of times a query is executed before it is prepared.
If it is set to 0, every query is prepared the first time it is executed.
If it is set to
None, prepared statements are disabled on the connection.
Default value: 5
See Prepared statements for details.
- prepared_max#
Maximum number of prepared statements on the connection.
Nonemeans no max number of prepared statements. The default value is 100.If more queries need to be prepared, old ones are deallocated.
Specifying
Nonecan be useful for middleware that don’t support deallocation; see prepared statements notes.Changed in version 3.2: Added support for the
Nonevalue.
Methods you can use to do something cool
- cancel_safe(*, timeout: float = 30.0) None#
Cancel the current operation on the connection.
- Parameters:
timeout – raise a
CancellationTimeoutif the cancellation request does not succeed withintimeoutseconds.
Note that a successful cancel attempt on the client is not a guarantee that the server will successfully manage to cancel the operation.
This is a non-blocking version of
cancel()which leverages a more secure and improved cancellation feature of the libpq, which is only available from version 17.If the underlying libpq is older than version 17, the method will fall back to using the same implementation of
cancel().Note
You can use the
has_cancel_safecapability to check ifcancel_safe()will not fall back on the legacy libpq functions.Warning
The
timeoutparameter has no effect for libpq older than version 17.New in version 3.2.
- cancel() None#
Cancel the current operation on the connection.
Warning
The
cancel()method is implemented using thePQcancelfunction, which is deprecated since PostgreSQL 17, and has a few shortcomings:it is blocking even on async connections,
it might use an insecure connection even if the original connection was secure.
Therefore you should use the
cancel_safe()method whenever possible.Note
Unlike
cancel_safe(), it is safe to call this method as asignalhandler. This is pretty much the only case in which you might want to use this function.
- notifies(*, timeout: Optional[float] = None, stop_after: Optional[int] = None) Generator[Notify]#
Yield
Notifyobjects as soon as they are received from the database.- Parameters:
timeout – maximum amount of time to wait for notifications.
Nonemeans no timeout.stop_after – stop after receiving this number of notifications. You might actually receive more than this number if more than one notifications arrives in the same packet.
Notifies are received after using
LISTENin a connection, when any sessions in the database generates aNOTIFYon one of the listened channels.Changed in version 3.2: Added
timeoutandstop_afterparameters.
- add_notify_handler(callback: Callable[[Notify], None]) None#
Register a callable to be invoked whenever a notification is received.
- Parameters:
callback (Callable[[Notify], None]) – the callback to call upon notification received.
See Asynchronous notifications for details.
- remove_notify_handler(callback: Callable[[Notify], None]) None#
Unregister a notification callable previously registered.
- Parameters:
callback (Callable[[Notify], None]) – the callback to remove.
- add_notice_handler(callback: Callable[[Diagnostic], None]) None#
Register a callable to be invoked when a notice message is received.
- Parameters:
callback (Callable[[Diagnostic], None]) – the callback to call upon message received.
See Server messages for details.
- remove_notice_handler(callback: Callable[[Diagnostic], None]) None#
Unregister a notice message callable previously registered.
- Parameters:
callback (Callable[[Diagnostic], None]) – the callback to remove.
- fileno() int#
Return the file descriptor of the connection.
This function allows to use the connection as file-like object in functions waiting for readiness, such as the ones defined in the
selectorsmodule.
Two-Phase Commit support methods
New in version 3.1.
See also
Two-Phase Commit protocol support for an introductory explanation of these methods.
- xid(format_id: int, gtrid: str, bqual: str) Xid#
Returns a
Xidto pass to thetpc_*()methods of this connection.The argument types and constraints are explained in Two-Phase Commit protocol support.
The values passed to the method will be available on the returned object as the members
format_id,gtrid,bqual.
- tpc_begin(xid: psycopg.Xid | str) None#
Begin a TPC transaction with the given transaction ID
xid.This method should be called outside of a transaction (i.e. nothing may have executed since the last
commit()orrollback()andtransaction_statusisIDLE).Furthermore, it is an error to call
commit()orrollback()within the TPC transaction: in this case aProgrammingErroris raised.The
xidmay be either an object returned by thexid()method or a plain string: the latter allows to create a transaction using the provided string as PostgreSQL transaction id. See alsotpc_recover().
- tpc_prepare() None#
Perform the first phase of a transaction started with
tpc_begin().A
ProgrammingErroris raised if this method is used outside of a TPC transaction.After calling
tpc_prepare(), no statements can be executed untiltpc_commit()ortpc_rollback()will be called.See also
The
PREPARE TRANSACTIONPostgreSQL command.
- tpc_commit(xid: Optional[Union[Xid, str]] = None) None#
Commit a prepared two-phase transaction.
When called with no arguments,
tpc_commit()commits a TPC transaction previously prepared withtpc_prepare().If
tpc_commit()is called prior totpc_prepare(), a single phase commit is performed. A transaction manager may choose to do this if only a single resource is participating in the global transaction.When called with a transaction ID
xid, the database commits the given transaction. If an invalid transaction ID is provided, aProgrammingErrorwill be raised. This form should be called outside of a transaction, and is intended for use in recovery.On return, the TPC transaction is ended.
See also
The
COMMIT PREPAREDPostgreSQL command.
- tpc_rollback(xid: Optional[Union[Xid, str]] = None) None#
Roll back a prepared two-phase transaction.
When called with no arguments,
tpc_rollback()rolls back a TPC transaction. It may be called before or aftertpc_prepare().When called with a transaction ID
xid, it rolls back the given transaction. If an invalid transaction ID is provided, aProgrammingErroris raised. This form should be called outside of a transaction, and is intended for use in recovery.On return, the TPC transaction is ended.
See also
The
ROLLBACK PREPAREDPostgreSQL command.
- tpc_recover() list[psycopg.Xid]#
Returns a list of
Xidrepresenting pending transactions, suitable for use withtpc_commit()ortpc_rollback().If a transaction was not initiated by Psycopg, the returned Xids will have attributes
format_idandbqualset toNoneand thegtridset to the PostgreSQL transaction ID: such Xids are still usable for recovery. Psycopg uses the same algorithm of the PostgreSQL JDBC driver to encode a XA triple in a string, so transactions initiated by a program using such driver should be unpacked correctly.Xids returned by
tpc_recover()also have extra attributesprepared,owner,databasepopulated with the values read from the server.See also
the
pg_prepared_xactssystem view.
The AsyncConnection class#
- class psycopg.AsyncConnection#
Wrapper for a connection to the database.
This class implements a DBAPI-inspired interface, with all the blocking methods implemented as coroutines. Unless specified otherwise, non-blocking methods are shared with the
Connectionclass.The following methods have the same behaviour of the matching
Connectionmethods, but should be called using theawaitkeyword.- async classmethod connect(conninfo: str = '', *, autocommit: bool = False, prepare_threshold: int | None = 5, context: Optional[AdaptContext] = None, row_factory: Optional[AsyncRowFactory[Row]] = None, cursor_factory: AsyncCursor[+Row]]] = None, **kwargs: Optional[Union[str, int]]) Self#
Connect to a database server and return a new
AsyncConnectioninstance.Changed in version 3.1: Automatically resolve domain names asynchronously. In previous versions, name resolution blocks, unless the
hostaddrparameter is specified, or theresolve_hostaddr_async()function is used.
- async close() None#
Close the database connection.
Note
You can use
async withto close the connection automatically when the block is exited, but be careful about the async quirkness: see with async connections for details.
- cursor(*, binary: bool = False, row_factory: Optional[RowFactory] = None) AsyncCursor#
- cursor(name: str, *, binary: bool = False, row_factory: Optional[RowFactory] = None, scrollable: Optional[bool] = None, withhold: bool = False) AsyncServerCursor
Note
You can use:
async with conn.cursor() as cur: ...
to close the cursor automatically when the block is exited.
- cursor_factory: type[AsyncCursor[Row]]#
Default is
psycopg.AsyncCursor.
- server_cursor_factory: type[AsyncServerCursor[Row]]#
Default is
psycopg.AsyncServerCursor.
- row_factory: AsyncRowFactory[Row]#
- async execute(query: QueryNoTemplate, params: Optional[Union[Sequence[Any], Mapping[str, Any]]] = None, *, prepare: bool | None = None, binary: bool = False) AsyncCursor[Row]#
- async execute(query: Template, *, prepare: bool | None = None, binary: bool = False) AsyncCursor[Row]
Execute a query and return a cursor to read its results.
- pipeline() AsyncIterator[AsyncPipeline]#
Context manager to switch the connection into pipeline mode.
Note
It must be called as:
async with conn.pipeline() as p: ...
- transaction(savepoint_name: str | None = None, force_rollback: bool = False) AsyncIterator[AsyncTransaction]#
Start a context block with a new transaction or nested transaction.
- Parameters:
savepoint_name – Name of the savepoint used to manage a nested transaction. If
None, one will be chosen automatically.force_rollback – Roll back the transaction at the end of the block even if there were no error (e.g. to try a no-op process).
- Return type:
Note
It must be called as:
async with conn.transaction() as tx: ...
- async cancel_safe(*, timeout: float = 30.0) None#
Cancel the current operation on the connection.
- Parameters:
timeout – raise a
CancellationTimeoutif the cancellation request does not succeed withintimeoutseconds.
Note that a successful cancel attempt on the client is not a guarantee that the server will successfully manage to cancel the operation.
This is a non-blocking version of
cancel()which leverages a more secure and improved cancellation feature of the libpq, which is only available from version 17.If the underlying libpq is older than version 17, the method will fall back to using the same implementation of
cancel().New in version 3.2.
- async notifies(*, timeout: Optional[float] = None, stop_after: Optional[int] = None) AsyncGenerator[Notify]#
Yield
Notifyobjects as soon as they are received from the database.- Parameters:
timeout – maximum amount of time to wait for notifications.
Nonemeans no timeout.stop_after – stop after receiving this number of notifications. You might actually receive more than this number if more than one notifications arrives in the same packet.
Changed in version 3.2: Added
timeoutandstop_afterparameters.
- async set_autocommit(value: bool) None#
Method version of the
autocommitsetter.
- async set_isolation_level(value: psycopg.IsolationLevel | None) None#
Method version of the
isolation_levelsetter.
- async set_deferrable(value: bool | None) None#
Method version of the
deferrablesetter.
- async tpc_commit(xid: Optional[Union[Xid, str]] = None) None#
Commit a prepared two-phase transaction.
- async tpc_rollback(xid: Optional[Union[Xid, str]] = None) None#
Roll back a prepared two-phase transaction.
- async tpc_recover() list[psycopg.Xid]#