Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I recover from error in a transaction with psycopg2?

I have a script that imports data from old database. Somewhere along the way I run into unique constraint violation. I want to amend the query and execute it again, but it says, "psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block":

try:
    pcur.execute(sql, values)
except psycopg2.IntegrityError:
    value = ...
    pcur.execute(sql, values)

How do I do that without switching to autocommit mode?

like image 964
x-yuri Avatar asked Nov 30 '25 06:11

x-yuri


1 Answers

Inspired by this answer:

pcur.execute('SAVEPOINT sp1')
try:
    pcur.execute(sql, values)
except psycopg2.IntegrityError:
    pcur.execute('ROLLBACK TO SAVEPOINT sp1')
    value = ...
    pcur.execute(sql, values)
else:
    pcur.execute('RELEASE SAVEPOINT sp1')
like image 128
x-yuri Avatar answered Dec 02 '25 20:12

x-yuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!