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 21:47:49
Message-ID: a663dfcf-3ca4-41d0-9022-1ad01d6b6d5f@aklaver.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: psycopg

On 9/7/24 14:20, Karsten Hilbert wrote:
> Am Sat, Sep 07, 2024 at 02:09:28PM -0700 schrieb Adrian Klaver:
>
>>> Right, and this was suggested elsewhere ;)
>>>
>>> And, yeah, the actual code is much more involved :-D
>>>
>>
>> I see that.
>>
>> The question is does the full code you show fail?
>>
>> The code sample you show in your original post is doing something very different then
>> what you show in your latest post. At this point I do not understand the exact problem
>> we are dealing with.
>
> We are not dealing with an unsolved problem. I had been
> asking for advice where to best place that .commit() call in
> case I am overlooking benefits and drawbacks of choices.
>
> The
>
> try:
> do something
> except:
> log something
> finally:
> .commit()
>
> cadence is fairly Pythonic and elegant in that it ensures the
> the .commit() will always be reached regardless of exceptions
> being thrown or not and them being handled or not.

Elegant is nice, but correct is better:)

>
> It is also insufficient because the .commit() itself may
> elicit exceptions (from the database).

Yeah with Serializable that is part of the package:

"While PostgreSQL's Serializable transaction isolation level only allows
concurrent transactions to commit if it can prove there is a serial
order of execution that would produce the same effect ..."

> Boring and repetitive and safe(r):
>
> 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.

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

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

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Karsten Hilbert 2024-09-07 21:59:41 Re: psycopg2: proper positioning of .commit() within try: except: blocks
Previous Message Karsten Hilbert 2024-09-07 21:20:57 Re: psycopg2: proper positioning of .commit() within try: except: blocks