Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Distinguish different types of IntegrityError

I'm using django + MySQL. Sometimes, I insert duplicate data into my database, which causes django to raise an IntegrityErrror.

The issue is, django/python use this same error for several of the different MySQL errors. The only way to differentiate between them is to look at the error code. For example,

try:
    # code that raises integrity error
except IntegrityError
    if e.args[0] == 1062:
        raise CustomCreatedDuplicateEntryError
    else:
        raise e

My question is: Is this safe to do? If so, why isn't this implemented at a lower level? It seems like I can't be the only one who wants more fine grained control over IntegrityError.

Thanks!

EDIT

Code to raise this error

class Foo(django.db.models.Model):
    guid = models.CharField(max_length=32, db_index=True, unique=True)

Foo(guid=a).save()
# this raises an IntegrityError with code 1062!
Foo(guid=a).save()
like image 499
djs22 Avatar asked May 15 '13 21:05

djs22


1 Answers

Is this safe to do?

This is not unsafe. Although by doing this you've created a coupling between your application and the database(MySQL). What if down the road you decide to replace MySQL with some other database solution? The error codes will be changed, and your code will raise inconsistent messages.

If so, why isn't this implemented at a lower level?

Probably for the same concern I am having.

like image 117
rubayeet Avatar answered Oct 01 '22 14:10

rubayeet