数据库
首页 > 数据库> > PostgreSQL UNIQUE约束错误消息

PostgreSQL UNIQUE约束错误消息

作者:互联网

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)
);

标签:php,postgresql,error-handling,unique-constraint
来源: https://codeday.me/bug/20190806/1598233.html