Re: psycopg2: proper positioning of .commit() within try: except: blocks

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net>
Cc: psycopg(at)lists(dot)postgresql(dot)org
Subject: Re: psycopg2: proper positioning of .commit() within try: except: blocks
Date: 2024-09-07 22:09:28
Message-ID: 75723bad-7914-4728-a567-a061e4d3c7d6@aklaver.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: psycopg

On 9/7/24 14:59, Karsten Hilbert wrote:
> Am Sat, Sep 07, 2024 at 02:47:49PM -0700 schrieb Adrian Klaver:
>
>>> It is also insufficient because the .commit() itself may
>>> elicit exceptions (from the database).
>>
>> Yeah with Serializable that is part of the package:
>
> No complaints :-)
>
>
>>> try:
>>> do something
>>> except:
>>> log something
>>> try:
>>> .commit()
>>> except:
>>> log something
>>>
>>> I eventually opted for the last version, except for factoring
>>> out the second try: except: block.
>>
>> I'm not following, if you do that then you won't have a commit.
>
> Perhaps my pseudo-code was to abbreviated.
>
> conn = psycopg2.connection()
> curs = conn.cursor()
> curs.execute(SQL)
> curs.close()
> conn.commit()
> conn.close()
>
> Written more safely:
>
> conn = psycopg2.connection()
> curs = conn.cursor()
> try:
> curs.execute(SQL)
> except SOME_PG_EXCEPTION_VIA_PSYCOPG2:
> some_panicstricken_logging()
> curs.close()
> try:
> conn.commit()
> except SOME_PG_EXCEPTION_VIA_PSYCOPG2__SUCH_AS_SERIALIZATION_ERROR:
> some_more_of_the_panicstricken_logging()
> conn.close()
>
> now factored out:
>
> def __commit_me_logging_errors(commit_func):
> try:
> commit_func()
> except SOME_PG_EXCEPTION_VIA_PSYCOPG2__SUCH_AS_SERIALIZATION_ERROR:
> some_more_of_the_panicstricken_logging()
> return
>
> conn = psycopg2.connection()
> curs = conn.cursor()
> try:
> curs.execute(SQL)
> except SOME_PG_EXCEPTION_VIA_PSYCOPG2:
> some_panicstricken_logging()
> curs.close()
> __commit_me_logging_errors(conn.commit)
> conn.close()
>
> More clear ?

Yes.

>
> Karsten
> --
> GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse psycopg by date

  From Date Subject
Next Message thiemo 2024-11-01 10:17:47 TypeError: dict is not a sequence
Previous Message Karsten Hilbert 2024-09-07 21:59:41 Re: psycopg2: proper positioning of .commit() within try: except: blocks