Am Sat, Sep 07, 2024 at 09:46:03AM -0700 schrieb Adrian Klaver:
> >unto now I had been thinking this is a wise idiom (in code
> >that needs not care whether it fails to do what it tries to
> >do^1):
> >
> > conn = psycopg2.connection(...)
>
> In the above do you have:
>
> https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE
>
> psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE
I do indeed.
> Or is that in some other concurrent transaction?
In fact in that codebase all transactions -- running
concurrently or not -- are set to SERIALIZABLE.
They are not psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT,
for that matter.
> > curs = conn.cursor()
> > try:
> > curs.execute(SOME_SQL)
> > except PSYCOPG2-Exception:
> > some logging being done, and, yes, I
> > can safely inhibit propagation^1
> > finally:
> > conn.commit() # will rollback, if SOME_SQL failed
>
> It will if you use with conn:, otherwise it up to you to do the rollback()
>
> Are you are doing a rollback() in except PSYCOPG2-Exception: ?
No I don't but - to my understanding - an ongoing transaction
is being closed upon termination of the hosting connection.
Unless .commit() is explicitely being issued somewhere in the
code that closing of a transaction will amount to a ROLLBACK.
In case of SQL having failed within a given transaction a
COMMIT will fail-but-rollback, too (explicit ROLLBACK would
succeed while a COMMIT would fail and, in-effect, roll back).
IOW, when SOME_SQL has failed it won't matter that I close
the connection with conn.commit() and it won't matter that
conn.commit() runs a COMMIT on the database -- an open
transaction having run that failed SQL will still roll back
as if ROLLBACK had been issued. Or else my mental model is
wrong.
https://www.psycopg.org/docs/connection.html#connection.close
In the particular case I was writing about the SQL itself
succeeded but then the COMMIT failed due to serialization. I
was wondering about where to best place any needed
conn.commit(). My knee-jerk reaction was to then put it last
in the try: block...
All this is probably more related to Python than to PostgreSQL.
Thanks,
Karsten
--
GPG 40BE 5B0E C98E 1713 AFA6 5BC0 3BEA AC80 7D4F C89B