从SQLAlchemy + Postgres中的IntegrityError中获取约束名称

时间:2014-02-04 00:27:37

标签: python postgresql error-handling unique-constraint

数据库最好检查某些类型的约束,因为尝试手动检查它们可能会导致竞争条件。那么,您认为数据库驱动程序会让这很简单,对吧?

golang的postgres的数据库驱动程序pq解析了整个错误,包括the name of the constraint。知道约束的名称可以很容易地将其映射到出错的地方。

是否有Python的postgres驱动程序为您提供约束名称而不需要您自己从字符串中解析它?

1 个答案:

答案 0 :(得分:10)

哦,我找到了。就在这里:

try:
    db.session.commit()
except sqlalchemy.exc.IntegrityError, e:
    constraint = e.orig.diag.constraint_name

事实上,diag对象中有很多有用的东西:

>>> dir(e.orig.diag)[15:]
['column_name', 'constraint_name', 'context', 'datatype_name', 'internal_position', 'internal_query', 'message_detail', 'message_hint', 'message_primary', 'schema_name', 'severity', 'source_file', 'source_function', 'source_line', 'sqlstate', 'statement_position', 'table_name']