63
76
.. method:: close()
65
Close the connection now (rather than whenever `__del__()` is
66
called). The connection will be unusable from this point forward; an
78
Close the connection now (rather than whenever `del` is executed).
79
The connection will be unusable from this point forward; an
67
80
`~psycopg2.InterfaceError` will be raised if any operation is
68
81
attempted with the connection. The same applies to all cursor objects
69
82
trying to use the connection. Note that closing a connection without
70
committing the changes first will cause an implicit rollback to be
71
performed (unless a different isolation level has been selected: see
83
committing the changes first will cause any pending change to be
84
discarded as if a :sql:`ROLLBACK` was performed (unless a different
85
isolation level has been selected: see
72
86
`~connection.set_isolation_level()`).
89
single: PgBouncer; unclean server
91
.. versionchanged:: 2.2
92
previously an explicit :sql:`ROLLBACK` was issued by Psycopg on
93
`!close()`. The command could have been sent to the backend at an
94
inappropriate time, so Psycopg currently relies on the backend to
95
implicitly discard uncommitted changes. Some middleware are known
96
to behave incorrectly though when the connection is closed during
97
a transaction (when `~connection.status` is
98
`~psycopg2.extensions.STATUS_IN_TRANSACTION`), e.g. PgBouncer_
99
reports an ``unclean server`` and discards the connection. To
100
avoid this problem you can ensure to terminate the transaction
101
with a `~connection.commit()`/`~connection.rollback()` before
104
.. _PgBouncer: http://pgbouncer.projects.postgresql.org/
76
108
single: Exceptions; In the connection class
78
.. rubric:: Excetptions as connection class attributes
110
.. rubric:: Exceptions as connection class attributes
80
112
The `!connection` also exposes as attributes the same exceptions
81
113
available in the `psycopg2` module. See :ref:`dbapi-exceptions`.
118
single: Two-phase commit; methods
120
.. rubric:: Two-phase commit support methods
122
.. versionadded:: 2.3
124
.. seealso:: :ref:`tpc` for an introductory explanation of these methods.
126
Note that PostgreSQL supports two-phase commit since release 8.1: these
127
methods raise `~psycopg2.NotSupportedError` if used with an older version
133
.. method:: xid(format_id, gtrid, bqual)
135
Returns a `~psycopg2.extensions.Xid` instance to be passed to the
136
`!tpc_*()` methods of this connection. The argument types and
137
constraints are explained in :ref:`tpc`.
139
The values passed to the method will be available on the returned
140
object as the members `~psycopg2.extensions.Xid.format_id`,
141
`~psycopg2.extensions.Xid.gtrid`, `~psycopg2.extensions.Xid.bqual`.
142
The object also allows accessing to these members and unpacking as a
146
.. method:: tpc_begin(xid)
148
Begins a TPC transaction with the given transaction ID *xid*.
150
This method should be called outside of a transaction (i.e. nothing
151
may have executed since the last `~connection.commit()` or
152
`~connection.rollback()` and `connection.status` is
153
`~psycopg2.extensions.STATUS_READY`).
155
Furthermore, it is an error to call `!commit()` or `!rollback()`
156
within the TPC transaction: in this case a `~psycopg2.ProgrammingError`
159
The *xid* may be either an object returned by the `~connection.xid()`
160
method or a plain string: the latter allows to create a transaction
161
using the provided string as PostgreSQL transaction id. See also
162
`~connection.tpc_recover()`.
166
pair: Transaction; Prepare
168
.. method:: tpc_prepare()
170
Performs the first phase of a transaction started with
171
`~connection.tpc_begin()`. A `~psycopg2.ProgrammingError` is raised if
172
this method is used outside of a TPC transaction.
174
After calling `!tpc_prepare()`, no statements can be executed until
175
`~connection.tpc_commit()` or `~connection.tpc_rollback()` will be
176
called. The `~connection.reset()` method can be used to restore the
177
status of the connection to `~psycopg2.extensions.STATUS_READY`: the
178
transaction will remain prepared in the database and will be
179
possible to finish it with `!tpc_commit(xid)` and
180
`!tpc_rollback(xid)`.
182
.. seealso:: the |PREPARE TRANSACTION|_ PostgreSQL command.
184
.. |PREPARE TRANSACTION| replace:: :sql:`PREPARE TRANSACTION`
185
.. _PREPARE TRANSACTION: http://www.postgresql.org/docs/9.0/static/sql-prepare-transaction.html
189
pair: Commit; Prepared
191
.. method:: tpc_commit([xid])
193
When called with no arguments, `!tpc_commit()` commits a TPC
194
transaction previously prepared with `~connection.tpc_prepare()`.
196
If `!tpc_commit()` is called prior to `!tpc_prepare()`, a single phase
197
commit is performed. A transaction manager may choose to do this if
198
only a single resource is participating in the global transaction.
200
When called with a transaction ID *xid*, the database commits
201
the given transaction. If an invalid transaction ID is
202
provided, a `~psycopg2.ProgrammingError` will be raised. This form
203
should be called outside of a transaction, and is intended for use in
206
On return, the TPC transaction is ended.
208
.. seealso:: the |COMMIT PREPARED|_ PostgreSQL command.
210
.. |COMMIT PREPARED| replace:: :sql:`COMMIT PREPARED`
211
.. _COMMIT PREPARED: http://www.postgresql.org/docs/9.0/static/sql-commit-prepared.html
215
pair: Rollback; Prepared
217
.. method:: tpc_rollback([xid])
219
When called with no arguments, `!tpc_rollback()` rolls back a TPC
220
transaction. It may be called before or after
221
`~connection.tpc_prepare()`.
223
When called with a transaction ID *xid*, it rolls back the given
224
transaction. If an invalid transaction ID is provided, a
225
`~psycopg2.ProgrammingError` is raised. This form should be called
226
outside of a transaction, and is intended for use in recovery.
228
On return, the TPC transaction is ended.
230
.. seealso:: the |ROLLBACK PREPARED|_ PostgreSQL command.
232
.. |ROLLBACK PREPARED| replace:: :sql:`ROLLBACK PREPARED`
233
.. _ROLLBACK PREPARED: http://www.postgresql.org/docs/9.0/static/sql-rollback-prepared.html
237
pair: Transaction; Recover
239
.. method:: tpc_recover()
241
Returns a list of `~psycopg2.extensions.Xid` representing pending
242
transactions, suitable for use with `tpc_commit()` or
245
If a transaction was not initiated by Psycopg, the returned Xids will
246
have attributes `~psycopg2.extensions.Xid.format_id` and
247
`~psycopg2.extensions.Xid.bqual` set to `!None` and the
248
`~psycopg2.extensions.Xid.gtrid` set to the PostgreSQL transaction ID: such Xids are still
249
usable for recovery. Psycopg uses the same algorithm of the
250
`PostgreSQL JDBC driver`__ to encode a XA triple in a string, so
251
transactions initiated by a program using such driver should be
254
.. __: http://jdbc.postgresql.org/
256
Xids returned by `!tpc_recover()` also have extra attributes
257
`~psycopg2.extensions.Xid.prepared`, `~psycopg2.extensions.Xid.owner`,
258
`~psycopg2.extensions.Xid.database` populated with the values read
261
.. seealso:: the |pg_prepared_xacts|_ system view.
263
.. |pg_prepared_xacts| replace:: `pg_prepared_xacts`
264
.. _pg_prepared_xacts: http://www.postgresql.org/docs/9.0/static/view-pg-prepared-xacts.html
86
270
The above methods are the only ones defined by the |DBAPI| protocol.
94
278
(0) or closed (1).
283
Cancel the current database operation.
285
The method interrupts the processing of the current operation. If no
286
query is being executed, it does nothing. You can call this function
287
from a different thread than the one currently executing a database
288
operation, for instance if you want to cancel a long running query if a
289
button is pushed in the UI. Interrupting query execution will cause the
290
cancelled method to raise a
291
`~psycopg2.extensions.QueryCanceledError`. Note that the termination
292
of the query is not guaranteed to succeed: see the documentation for
295
.. |PQcancel| replace:: `!PQcancel()`
296
.. _PQcancel: http://www.postgresql.org/docs/8.4/static/libpq-cancel.html#AEN34765
298
.. versionadded:: 2.3
99
303
Reset the connection to the default.
101
305
The method rolls back an eventual pending transaction and executes the
102
306
PostgreSQL |RESET|_ and |SET SESSION AUTHORIZATION|__ to revert the
103
session to the default values.
307
session to the default values. A two-phase commit transaction prepared
308
using `~connection.tpc_prepare()` will remain in the database
309
available for recover.
105
311
.. |RESET| replace:: :sql:`RESET`
106
.. _RESET: http://www.postgresql.org/docs/8.4/static/sql-reset.html
312
.. _RESET: http://www.postgresql.org/docs/9.0/static/sql-reset.html
108
314
.. |SET SESSION AUTHORIZATION| replace:: :sql:`SET SESSION AUTHORIZATION`
109
.. __: http://www.postgresql.org/docs/8.4/static/sql-set-session-authorization.html
315
.. __: http://www.postgresql.org/docs/9.0/static/sql-set-session-authorization.html
111
317
.. versionadded:: 2.0.12
121
327
pair: Transaction; Autocommit
122
328
pair: Transaction; Isolation level
330
.. method:: set_session([isolation_level,] [readonly,] [deferrable,] [autocommit])
332
Set one or more parameters for the next transactions or statements in
333
the current session. See |SET TRANSACTION|_ for further details.
335
.. |SET TRANSACTION| replace:: :sql:`SET TRANSACTION`
336
.. _SET TRANSACTION: http://www.postgresql.org/docs/9.1/static/sql-set-transaction.html
338
:param isolation_level: set the `isolation level`_ for the next
339
transactions/statements. The value can be one of the
340
:ref:`constants <isolation-level-constants>` defined in the
341
`~psycopg2.extensions` module or one of the literal values
342
``READ UNCOMMITTED``, ``READ COMMITTED``, ``REPEATABLE READ``,
344
:param readonly: if `!True`, set the connection to read only;
345
read/write if `!False`.
346
:param deferrable: if `!True`, set the connection to deferrable;
347
non deferrable if `!False`. Only available from PostgreSQL 9.1.
348
:param autocommit: switch the connection to autocommit mode: not a
349
PostgreSQL session setting but an alias for setting the
350
`autocommit` attribute.
352
The parameters *isolation_level*, *readonly* and *deferrable* also
353
accept the string ``DEFAULT`` as a value: the effect is to reset the
354
parameter to the server default.
357
http://www.postgresql.org/docs/9.1/static/transaction-iso.html
359
The function must be invoked with no transaction in progress. At every
360
function invocation, only the specified parameters are changed.
362
The default for the values are defined by the server configuration:
363
see values for |default_transaction_isolation|__,
364
|default_transaction_read_only|__, |default_transaction_deferrable|__.
366
.. |default_transaction_isolation| replace:: :sql:`default_transaction_isolation`
367
.. __: http://www.postgresql.org/docs/9.1/static/runtime-config-client.html#GUC-DEFAULT-TRANSACTION-ISOLATION
368
.. |default_transaction_read_only| replace:: :sql:`default_transaction_read_only`
369
.. __: http://www.postgresql.org/docs/9.1/static/runtime-config-client.html#GUC-DEFAULT-TRANSACTION-READ-ONLY
370
.. |default_transaction_deferrable| replace:: :sql:`default_transaction_deferrable`
371
.. __: http://www.postgresql.org/docs/9.1/static/runtime-config-client.html#GUC-DEFAULT-TRANSACTION-DEFERRABLE
375
There is currently no builtin method to read the current value for
376
the parameters: use :sql:`SHOW default_transaction_...` to read
377
the values from the backend.
379
.. versionadded:: 2.4.2
382
.. attribute:: autocommit
384
Read/write attribute: if `!True`, no transaction is handled by the
385
driver and every statement sent to the backend has immediate effect;
386
if `!False` a new transaction is started at the first command
387
execution: the methods `commit()` or `rollback()` must be manually
388
invoked to terminate the transaction.
390
The autocommit mode is useful to execute commands requiring to be run
391
outside a transaction, such as :sql:`CREATE DATABASE` or
394
The default is `!False` (manual commit) as per DBAPI specification.
398
By default, any query execution, including a simple :sql:`SELECT`
399
will start a transaction: for long-running programs, if no further
400
action is taken, the session will remain "idle in transaction", a
401
condition non desiderable for several reasons (locks are held by
402
the session, tables bloat...). For long lived scripts, either
403
ensure to terminate a transaction as soon as possible or use an
404
autocommit connection.
406
.. versionadded:: 2.4.2
126
409
.. attribute:: isolation_level
127
410
.. method:: set_isolation_level(level)
414
From version 2.4.2, `set_session()` and `autocommit`, offer
415
finer control on the transaction characteristics.
129
417
Read or set the `transaction isolation level`_ for the current session.
130
418
The level defines the different phenomena that can happen in the
131
419
database between concurrent transactions.
295
587
.. method:: lobject([oid [, mode [, new_oid [, new_file [, lobject_factory]]]]])
297
Return a new database large object. See :ref:`large-objects` for an
589
Return a new database large object as a `~psycopg2.extensions.lobject`
592
See :ref:`large-objects` for an overview.
300
594
:param oid: The OID of the object to read or write. 0 to create
301
595
a new large object and and have its OID assigned automatically.
302
:param mode: Access mode to the object: can be ``r``, ``w``,
303
``rw`` or ``n`` (meaning don't open it).
596
:param mode: Access mode to the object, see below.
304
597
:param new_oid: Create a new object using the specified OID. The
305
function raises `OperationalError` if the OID is already in
306
use. Default is 0, meaning assign a new one automatically.
598
function raises `~psycopg2.OperationalError` if the OID is already
599
in use. Default is 0, meaning assign a new one automatically.
307
600
:param new_file: The name of a file to be imported in the the database
308
601
(using the |lo_import|_ function)
309
602
:param lobject_factory: Subclass of
310
603
`~psycopg2.extensions.lobject` to be instantiated.
311
:rtype: `~psycopg2.extensions.lobject`
313
605
.. |lo_import| replace:: `!lo_import()`
314
.. _lo_import: http://www.postgresql.org/docs/8.4/static/lo-interfaces.html#AEN36307
606
.. _lo_import: http://www.postgresql.org/docs/9.0/static/lo-interfaces.html#LO-IMPORT
608
Available values for *mode* are:
613
``r`` Open for read only
614
``w`` Open for write only
615
``rw`` Open for read/write
616
``n`` Don't open the file
617
``b`` Don't decode read data (return data as `!str` in Python 2 or `!bytes` in Python 3)
618
``t`` Decode read data according to `connection.encoding` (return data as `!unicode` in Python 2 or `!str` in Python 3)
621
``b`` and ``t`` can be specified together with a read/write mode. If
622
neither ``b`` nor ``t`` is specified, the default is ``b`` in Python 2
623
and ``t`` in Python 3.
316
625
.. versionadded:: 2.0.8
627
.. versionchanged:: 2.4 added ``b`` and ``t`` mode and unicode
320
631
.. rubric:: Methods related to asynchronous support.