我正试图以编程方式将一个大型数据集从旧的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)
);

现在,我的程序执行一个insert来触发其中一个约束,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.中查找功能描述

10-08 08:18
查看更多