Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is psycopg2 IntegrityError not being caught?

I have some code where I try to write to a database, and in some cases get an (expected) integrityerror due to a uniqueness constraint. I am trying to catch the error, but for some mysterious reason I cannot. My code looks like this (running in a loop, simplified for clarity):

from psycopg2 import IntegrityError
try:
    data = {
            'one': val1,
            'two': val2
        }

    query=tablename.insert().values(data)
    target_engine.execute(query)
except IntegrityError as e:
    print "caught"
except Exception as e:
    print "uncaught"
    print e
    break

The output when I run the script looks like this:

uncaught
(psycopg2.IntegrityError) duplicate key value violates unique constraint "companies_x_classifications_pkey"
DETAIL:  Key (company_id, classification_id)=(37802, 304) already exists.
 [SQL: 'INSERT INTO companies_x_classifications (company_id, classification_id) VALUES (%(company_id)s, %(classification_id)s)'] [parameters: {'classification_id': 304, 'company_id': 37802L}]

It never even prints "caught", so it doesnt think I have an integrityerror. Yet when I print the error, it is an integrity error. Any help will be appreciated!

like image 274
Leo Avatar asked Aug 06 '15 08:08

Leo


1 Answers

Since you are using sqlalchemy, try:

from sqlalchemy.exc import IntegrityError

try:
...
except IntegrityError as e:
    print "caught"

The sqlalchemy wraps the psycopg2 exception to its own exception

like image 124
JuniorCompressor Avatar answered Oct 05 '22 08:10

JuniorCompressor