【发布时间】:2021-11-07 02:31:26
【问题描述】:
我正在使用 SQLAlchemy + psycopg2 构建一个公开数据库的 API。
我想在违反唯一或外键约束的情况下生成有用的错误消息。就像错误中涉及的字段的名称一样。
AFAIU,我应该能够从 PostgreSQL 获取约束名称。这将使我从约束名称中获取字段的工作。我现在关注的部分是获取该约束名称。
我捕获sqla.exc.IntegrityError,然后通过orig 属性访问底层的psycopg2 异常。例如,它可能是 psycopg2.errors.UniqueViolation 或 psycopg2.errors.ForeignKeyViolation。
我不知道如何获得有关错误的额外信息。
This answer指向this PostgreSQL doc page,涉及SQL语句。
有没有办法让 psycopg2 为我执行此操作并将这些额外信息添加到异常中?
还有其他获取信息的方法吗?
我需要访问一些错误消息并对其进行解析吗?
编辑:
感谢@Ian Wilson's answer,我想出了这个(以下示例仅详细说明违反唯一约束):
if isinstance(exc, sqla.exc.IntegrityError):
if isinstance(exc.orig, ppe.UniqueViolation):
# Get table and constraint name from diag info
table_name = exc.orig.diag.table_name
constraint_name = exc.orig.diag.constraint_name
# Inspect DB to get constraint object
inspector = sqla.inspect(db_engine)
unique_constraints = inspector.get_unique_constraints(table_name)
constraint = next(
c for c in unique_constraints
if c['name'] == constraint_name
)
# Get column names from object
column_names = constraint['column_names']
【问题讨论】:
标签: python postgresql sqlalchemy psycopg2