Clone wiki

sqlalchemy / UsageRecipes / UniqueConstraintExceptionHandling

Example how you can handle DBE constraint exception:

import sqlalchemy
import sqlalchemy.ext.declarative
import sqlalchemy.orm.interfaces
import sqlalchemy.exc


Base = sqlalchemy.ext.declarative.declarative_base(mapper=sqlalchemy.orm.mapper)

class Category(Base):
    __tablename__ = 'category'
    category_id = sqlalchemy.Column(sqlalchemy.Integer, autoincrement=True,primary_key=True)
    category_name = sqlalchemy.Column(sqlalchemy.Unicode(255), unique=True, nullable=False)


engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=False)
Base.metadata.bind=engine
Base.metadata.create_all()

Session = sqlalchemy.orm.scoped_session( sqlalchemy.orm.sessionmaker( bind = engine ) )
sess = Session()

cat = Category(category_name=u'foo')
sess.add(cat)
sess.commit()

cat2 = Category(category_name=u'foo')
try:
        sess.add(cat2)
        sess.commit()
except sqlalchemy.exc.IntegrityError, exc:
        reason = exc.message
        if reason.endswith('is not unique'):
                print "%s already exists" % exc.params[0]
                sess.rollback()

Updated