Get constraint name from IntegrityError in SQLAlchemy + Postgres

Some types of restrictions are best checked by the database, as attempting to check them manually can lead to race conditions. You might think that these database drivers will make this simple, right?

The pq database driver for postgres for golang parses the whole error, including the name of the constraint . Knowing the name of the constraint makes it easy to correlate this with what went wrong.

Is there a postgres driver for Python that gives you the name of a constraint without having to parse it from a string yourself?

+4
source share
1 answer

, . :

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']
+9

Source: https://habr.com/ru/post/1525143/


All Articles