PostgreSQL UNIQUE约束错误消息
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PostgreSQL UNIQUE约束错误消息,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2280字,纯文字阅读大概需要4分钟。
内容图文
在Appendix A: PostgreSQL error codes,它说:
For some types of errors, the server reports the name of a database object (a table, table column, data type, or constraint) associated with the error; for example, the name of the unique constraint that caused a unique_violation error. Such names are supplied in separate fields of the error report message so that applications need not try to extract them from the possibly-localized human-readable text of the message.
大胆强调我的.我有下表:
CREATE TABLE recipes (
id SERIAL,
title TEXT UNIQUE NOT NULL,
description TEXT NOT NULL,
instructions TEXT NOT NULL,
image BYTEA,
CONSTRAINT recipes_pk PRIMARY KEY(id),
CONSTRAINT title_unique UNIQUE(title)
);
当我尝试插入具有重复标题的新行时,我在pgAdmin3中收到以下错误消息:
ERROR: duplicate key value violates unique constraint "title_unique"
DETAIL: Key (title)=(mytitle) already exists.
或者,使用PHP:
["errorInfo"]=>
array(3) {
[0]=>
string(5) "23505"
[1]=>
int(7)
[2]=>
string(117) "ERROR: duplicate key value violates unique constraint "title_unique"
DETAIL: Key (title)=(mytitle) already exists."
}
根据PostgreSQL文档中的段落,不应该在错误信息的单独字段中找到约束名称title_unique吗?
我正在使用PostgreSQL 9.4.5.
解决方法:
例如,您可以在PL / pgSQL(as instructed in the manual,如@dezso评论)中的异常处理程序中读取引用中提到的这些单独字段:
DO
$$
DECLARE
err_constraint text;
BEGIN
INSERT INTO recipes (title) VALUES ('foo'), ('foo'); -- provoke unique violation
EXCEPTION
WHEN SQLSTATE '23000' THEN -- Class 23 — Integrity Constraint Violation
GET STACKED DIAGNOSTICS err_constraint = CONSTRAINT_NAME;
-- do something with it, for instance:
RAISE NOTICE '%', err_constraint;
RAISE; -- raise original error
END;
$$
结果:
NOTICE: title_unique ERROR: duplicate key value violates unique constraint "title_unique" DETAIL: Key (title)=(foo) already exists. CONTEXT: SQL statement "INSERT INTO recipes (title) VALUES ('foo')" PL/pgSQL function inline_code_block line 5 at SQL statement
另外:在DDL命令中声明两次唯一约束. (令我惊讶的是,这导致我在第9.5页的测试中出现了一个约束).无论哪种方式,只做一次.
CREATE TABLE recipes (
id SERIAL,
title TEXT NOT NULL, -- remove redundant clause
description TEXT NOT NULL,
instructions TEXT NOT NULL,
image BYTEA,
CONSTRAINT recipes_pk PRIMARY KEY(id),
CONSTRAINT title_unique UNIQUE(title)
);
内容总结
以上是互联网集市为您收集整理的PostgreSQL UNIQUE约束错误消息全部内容,希望文章能够帮你解决PostgreSQL UNIQUE约束错误消息所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。