From c2f284cd3b7d3b33f4de348aaac62590feda8c78 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Mon, 3 Dec 2012 03:18:51 +0000 Subject: [PATCH] Added documentation for the with statement --- doc/src/connection.rst | 8 ++++++++ doc/src/cursor.rst | 5 +++++ doc/src/usage.rst | 24 ++++++++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/doc/src/connection.rst b/doc/src/connection.rst index 997f96e9..f7ff4b19 100644 --- a/doc/src/connection.rst +++ b/doc/src/connection.rst @@ -74,6 +74,10 @@ The ``connection`` class automatically open, commands have immediate effect. See :ref:`transactions-control` for details. + .. versionchanged:: 2.5 if the connection is used in a ``with`` + statement, the method is automatically called if no exception is + raised in the ``with`` block. + .. index:: pair: Transaction; Rollback @@ -84,6 +88,10 @@ The ``connection`` class connection without committing the changes first will cause an implicit rollback to be performed. + .. versionchanged:: 2.5 if the connection is used in a ``with`` + statement, the method is automatically called if an exception is + raised in the ``with`` block. + .. method:: close() diff --git a/doc/src/cursor.rst b/doc/src/cursor.rst index 204fce21..62be5e3c 100644 --- a/doc/src/cursor.rst +++ b/doc/src/cursor.rst @@ -83,6 +83,11 @@ The ``cursor`` class The cursor will be unusable from this point forward; an `~psycopg2.InterfaceError` will be raised if any operation is attempted with the cursor. + + .. versionchanged:: 2.5 if the cursor is used in a ``with`` statement, + the method is automatically called at the end of the ``with`` + block. + .. attribute:: closed diff --git a/doc/src/usage.rst b/doc/src/usage.rst index a2c9b3fe..2586d7d8 100644 --- a/doc/src/usage.rst +++ b/doc/src/usage.rst @@ -548,6 +548,30 @@ change the isolation level. See the `~connection.set_session()` method for all the details. +.. index:: + single: with statement + +``with`` statement +^^^^^^^^^^^^^^^^^^ + +Starting from version 2.5, psycopg2's connections and cursors are *context +managers* and can be used with the ``with`` statement:: + + with psycopg2.connect(DSN) as conn: + with conn.cursor() as curs: + curs.execute(SQL) + +When a connection exits the ``with`` block, if no exception has been raised by +the block, the transaction is committed. In case of exception the transaction +is rolled back. In no case the connection is closed: a connection can be used +in more than a ``with`` statement and each ``with`` block is effectively +wrapped in a transaction. + +When a cursor exits the ``with`` block it is closed, releasing any resource +eventually associated with it. The state of the transaction is not affected. + + + .. index:: pair: Server side; Cursor pair: Named; Cursor