我正在尝试以编程方式将大型数据集从旧的 MySQL 数据库迁移到 PostgreSQL。源数据一团糟,所以我的 pgsql 表有一堆约束来捕获进入的不良数据。
当插入由于这些约束之一而失败时,我的 C 程序如何发现阻止插入的约束?
例如,其中一个更简单的表格如下所示:
create table glue (
product_id int not null references product(id),
history_id int not null references history(id),
constraint glue_idx unique (product_id,history_id)
);
现在,我的程序最终执行了一个触发约束之一的插入,PQresultStatus 只告诉我 PGRES_FATAL_ERROR,而 PQerrorMessage 告诉我:
ERROR: duplicate key value violates unique constraint "glue_idx"
DETAIL: Key (product_id, history_id)=(413, 1762) already exists.
这对我这个人来说是完全可读的。我的问题是,我的 C 程序如何辨别错误是由 glue_idx 约束捕获的?
最佳答案
使用函数
char *PQresultErrorField(const PGresult *res, int fieldcode)
根据 fieldcode
返回详细信息。可能的代码之一是 PG_DIAG_CONSTRAINT_NAME
。
在the documentation.中找到功能描述
关于c - PostgreSQL:我的 C (libpq) 程序如何检测哪个表约束触发了错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663265/