c - PostgreSQL:我的 C (libpq) 程序如何检测哪个表约束触发了错误?

标签 c postgresql libpq

我正在尝试以编程方式将大型数据集从旧的 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/

相关文章:

使用 DFS 计算 SCC

c - 在 windows Visual C++ Express 中调用 Free 时出错

ruby-on-rails - Ruby on Rails/PostgreSQL - 启动服务器时库未加载错误

postgresql - 如何在安装时修复 Rust 柴油 cli 链接 libpq.lib 错误

postgresql - 如何从 SQL 语法错误或从 libpq 执行异常中获取错误行/列号?

c++ - 如何调用带参数的外部程序?

postgresql - 插入整数列时不要静默舍入浮点输入

ruby-on-rails - HOW TO:使用OS X 10.10+上运行Ruby on Rails 4,Postgres,Unicorn,Nginx和端口转发的VirtualBox设置Vagrant

postgresql - 使用临时表的函数的物化 View

c - scanf 段错误和 while 循环内的各种其他异常