Coder Perfect

DatabaseError: the current transaction has been cancelled, and commands will be ignored until the transaction block is completed?

Problem

With the message, I got a lot of errors:

"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"

after switching the Django project’s database engine from python-psycopg to python-psycopg2.

The code is the same, but I’m not sure where the issues are coming from.

Asked by jack

Solution #1

When a query fails and you try to perform another query without first rolling back the transaction, postgres does this. (Think of it as a security feature that prevents your data from being corrupted.)

To remedy this, you’ll need to figure out where the faulty query is being executed in the code. Use the log statement and log min error statement parameters in your Postgresql server if necessary.

Answered by ʇsәɹoɈ

Solution #2

After you’ve corrected your code, roll back the previous (erroneous) transaction to get rid of the error:

from django.db import transaction
transaction.rollback()

To avoid the error from occuring, use try-except:

from django.db import transaction, DatabaseError
try:
    a.save()
except DatabaseError:
    transaction.rollback()

See the Django manual for further information.

Answered by Anuj Gupta

Solution #3

All you have to do in Flask is type:

curs = conn.cursor()
curs.execute("ROLLBACK")
conn.commit()

P.S. You can find the documentation at https://www.postgresql.org/docs/9.4/static/sql-rollback.html.

Answered by Dmytro Lopushanskyy

Solution #4

So, I had the same problem. My database wasn’t correctly synced, which was the issue I was encountering. The most angst always seems to be caused by simple situations…

To sync your Django database, type: from your app directory into terminal:

$ python manage.py syncdb

Note that if you’re using django-south, the command ‘$ python manage.py migrate’ may help you address the problem.

Happy coding!

Answered by Michael Merchant

Solution #5

These errors, in my experience, take the following form:

try:
    code_that_executes_bad_query()
    # transaction on DB is now bad
except:
    pass

# transaction on db is still bad
code_that_executes_working_query() # raises transaction error

There’s nothing wrong with the second query, but it’s the one that raises the (much less informative) error because the first one was caught.

edit: this only happens if the except clause catches IntegrityError (or any other low level database exception), If you catch something like DoesNotExist this error will not come up, because DoesNotExist does not corrupt the transaction.

The lesson here is to avoid using the try/except/pass method.

Answered by priestc

Post is based on https://stackoverflow.com/questions/2979369/databaseerror-current-transaction-is-aborted-commands-ignored-until-end-of-tra