[DB-SIG] conn.close() idempotence

Daniele Varrazzo daniele.varrazzo at gmail.com
Wed Oct 19 02:53:07 CEST 2011


in a discussion on the psycopg mailing list, an user has been
surprised by the fact that .close() called on a closed connection
raised error. I thought this was an implementation accident in the
driver and a more robust semantics should allow for close to be called
on a closed object without effect. But going to code a forgiving
double close, I found a test failing in the Stuart Bishop DBAPI unit

        # connection.close should raise an Error if called more than once

I see no reason to require this, and it actually creates some problem.
For example, if the connection is dropped for a network problem, the
driver may detect the invalid connection and put the connection in
closed status. But at this point any guard such as:

    conn = connection()
        # work

risks to become a problem, with the close() that may raise an error
because the connection has been implicitly closed by a communication
error. Note that close() in itself often is a quite safe operation,
not involving database communication, so it is not expected to fail
and may not be well guarded.

The DBAPI says about conn.close():

    The connection will be unusable from this point
    forward; an Error (or subclass) exception will be raised
    if any operation is attempted with the connection.

now, is conn.close() an "operation" on the connection? Even if it
doesn't involve server communication? I don't think an idempotent
close() violates this rule, so I'm really asking about an
interpretation of the DBAPI, not a change.

Another user in the ML pointed out that an idempotent close is also
the behaviour of the Python file objects.

My opinion is that the DBAPI test suite can be relaxed and
conn.close() should have no effect on a closed connection. What do you

-- Daniele

More information about the DB-SIG mailing list