pythonpostgresqlpsycopg2

Is there any reason not to use autocommit?


I'm using psycopg2 to manage some Postgresql database connections.

As I have found here and in the docs, it seems psycopg2 simulates non-autocommit mode as default. Also PostgreSQL treats every statement as a transaction, basically autocommit mode.

My doubt is, which one of these cases happens if both psycopg and PostgreSQL stay in default mode? Or what exactly happens if it's neither one of these two? Any performance advice will be appreciated too.

     Code                  Psycopg2                   Postgresql

Some statements --> One big transaction --> Multiple simple transactions
or
Some statements --> One big transaction --> Big transaction

Solution

  • First, my interpretation of the two documents is that when running psycopg2 with postgresql you will be running by default in simulated non-autocommit mode by virtue of psycopg2 having started a transaction. You can, of course, override that default with autocommit=True. Now to answer your question:

    By default you will not be using autocommit=True and this will require you to do a commit anytime you do an update to the database that you wish to be permanent. That may seem inconvenient. But there are many instances when you need to do multiple updates and either they must all succeed or none must succeed. If you specified autocommit=True, then you would have to explicitly start a transaction for these cases. With autocommit=False, you are saved the trouble of having to ever start a transaction at the price of always having to do a commit or rollback. It seems to be question of preference. I personally prefer autocommit=False.

    As far as performance is concerned, specifying autocommit=True will save you the cost of starting a needless transaction in many instances. But I can't quantify how much of a performance savings that really is.