.. __: https://www.postgresql.org/docs/current/libpq-envars.html
.. automethod:: close
+
+ .. note:: you can use :ref:`with connect(): ...<with-statement>` to
+ close the connection automatically when the block is exited.
+
+ .. autoattribute:: closed
+ :annotation: bool
+
.. automethod:: cursor
+ .. note:: you can use :ref:`with conn.cursor(): ...<with-statement>`
+ to close the cursor automatically when the block is exited.
+
.. rubric:: Transaction management methods
.. rubric:: Checking and configuring the connection state
- .. autoattribute:: closed
- :annotation: bool
-
.. autoattribute:: client_encoding
:annotation: str
.. automethod:: connect
.. automethod:: close
+
+ .. note:: you can use `!async with` to close the connection
+ automatically when the block is exited, but be careful about
+ the async quirkness: see :ref:`with-statement` for details.
+
.. automethod:: cursor
+
+ .. note:: you can use `!async with` to close the cursor
+ automatically when the block is exited, but be careful about
+ the async quirkness: see :ref:`with-statement` for details.
+
.. automethod:: commit
.. automethod:: rollback
terminate a transaction or a session though.
.. automethod:: close
- .. autoproperty:: closed
+
+ .. note:: you can use :ref:`with conn.cursor(): ...<with-statement>`
+ to close the cursor automatically when the block is exited.
+
+ .. autoattribute:: closed
+ :annotation: bool
.. rubric:: Methods to send commands
methods, but have an `async` interface.
.. automethod:: close
+
+ .. note:: you can use `!async with` to close the cursor
+ automatically when the block is exited, but be careful about
+ the async quirkness: see :ref:`with-statement` for details.
+
.. automethod:: execute
.. automethod:: executemany
.. automethod:: copy
.. index:: with
+.. _with-statement:
+
``with`` connections and cursors
--------------------------------
-The connections and cursors act as context managers, so you can run:
+Connections and cursors act as context managers, so you can run:
.. code:: python
# the transaction is committed on successful exit of the context
# and the connection closed
+For asynchronous connections and cursor it's *almost* what you'd expect, but
+not quite. Please note that `!connect()` and `!cursor()` *don't return a
+context*: they are both factory methods which return *an object which can be
+used as a context*. So you cannot use ``async with connect()``: you have to do
+it in two steps instead, as in
+
+.. code:: python
+
+ aconn = await psycopg3.AsyncConnection.connect():
+ async with aconn:
+ cur = await aconn.cursor()
+ async with as cur:
+ await cur.execute(...)
+
+which can be condensed as:
+
+.. code:: python
+
+ async with (await psycopg3.AsyncConnection.connect()) as aconn:
+ async with (await aconn.cursor()) as cur:
+ await cur.execute(...)
+
+...but no less than that: you still need to do the double async thing.
.. index::