在 PostgreSQL 中更新引用 table 时如何违反重复键约束 (Unique_Violation)?

How to violate duplicate key constraint (Unique_Violation) when updating reference table in PostgreSQL?

在 PostgreSQL 9.1 版中,我有两个 table:ICD9 和 Dx。我现在希望通过将现有记录更改为不同的键值(在 cdesc 中)来更新父 table、ICD9。

如果新密钥 (cicd9,cdesc) 在 ICD9 table 中不存在,则新值将级联到子 table,Dx :-)

但是,如果ICD9table中已经存在新值为cdesc的"new"键,那么由于

,记录不会被更新

错误 23505:重复键值违反唯一约束 "constraint_cdesc"。

我需要做的是更新父 table,ICD9,将旧记录更新为新值,并且此更新级联到 DX 中使用旧密钥的所有子记录然后从 ICD9 table.

中删除现在未使用的 "old" 记录

非常感谢对这位新手的任何帮助。 TIA

CREATE TABLE icd9
(
 cicd9 character varying(8),
 cdesc character varying(80) NOT NULL,
 CONSTRAINT constraint_cdesc UNIQUE (cicd9, cdesc),
 CONSTRAINT desccheck CHECK (cdesc::text <> ''::text)
)

CREATE TABLE dx
(
  cicd9 character varying(8),
  cdesc character varying(80) NOT NULL,
  CONSTRAINT fk_icd9 FOREIGN KEY (cicd9, cdesc)
      REFERENCES icd9 (cicd9, cdesc) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED 
)

编辑 #1:我想我简化了这些 table 结构以澄清我的观点,这里是完整的结构。非常感谢任何对此的帮助。

CREATE TABLE dx
(
recid serial NOT NULL,
cpatient character varying(33) NOT NULL,
cicd9 character varying(8),
cdesc character varying(80) NOT NULL,
tposted timestamp without time zone NOT NULL,
"timestamp" timestamp without time zone DEFAULT now(),
modified timestamp without time zone DEFAULT now(),
resolved boolean DEFAULT false,
treated boolean DEFAULT false,
chronic boolean DEFAULT false,
groupid character varying(33) NOT NULL,
service integer DEFAULT 0,
pmh boolean DEFAULT false,
explanation text,
CONSTRAINT pk_dx_recid PRIMARY KEY (recid),
CONSTRAINT dx_cpatient_fkey FOREIGN KEY (cpatient)
  REFERENCES patients (cpatient) MATCH SIMPLE
  ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT dx_groupid_fkey FOREIGN KEY (groupid)
  REFERENCES charts (groupid) MATCH SIMPLE
  ON UPDATE CASCADE ON DELETE RESTRICT,
CONSTRAINT fk_icd9 FOREIGN KEY (cicd9, cdesc)
  REFERENCES icd9 (cicd9, cdesc) MATCH SIMPLE
  ON UPDATE CASCADE ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED,
CONSTRAINT noduplicate_dx UNIQUE (cicd9, cdesc, groupid, tposted),
CONSTRAINT desccheck CHECK (cdesc::text <> ''::text),
CONSTRAINT groupcheck CHECK (groupid::bpchar <> ''::bpchar),
CONSTRAINT patientcheck CHECK (cpatient::bpchar <> ''::bpchar)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE dx
OWNER TO postgres;


  CREATE TABLE icd9
  (
   recid serial NOT NULL,
   cicd9 character varying(8),
   cdesc character varying(80) NOT NULL,
   "timestamp" timestamp without time zone DEFAULT now(),
   modified timestamp without time zone DEFAULT now(),
 chronic boolean NOT NULL DEFAULT false,
 common boolean NOT NULL DEFAULT false,
 CONSTRAINT pk_icd9_recid PRIMARY KEY (recid),
 CONSTRAINT constraint_cdesc UNIQUE (cicd9, cdesc),
 CONSTRAINT desccheck CHECK (cdesc::text <> ''::text)
)
  WITH (
   OIDS=FALSE
 );
 ALTER TABLE icd9
  OWNER TO postgres;

除了 table 设计中可能存在的错误外,我找不到暂时中止 "unique_violation" 的方法,它来自将记录的键值更新为另一条记录保存的值。在上面的设计中,ICD9 文件旨在作为一个库,其中的记录可能会或可能不会在系统的其他地方使用。

这个问题的解决方法是从引用库的table中移动子记录,然后删除会引起冲突的记录。大部分代码来自 Finding Foreign Keys with No Indexes,特别感谢@Patrick 提供了完成这项工作所需的最终密钥。下面是执行这项工作的代码(对我有用)。希望对大家有帮助。

CREATE OR REPLACE FUNCTION g_saveicd9(ocicd9 text, ocdesc text, ncicd9 text, ncdesc text, nchronic boolean, ncommon boolean)
  RETURNS void AS
$BODY$
DECLARE
    -- Declare row format
    o ICD9%rowtype;
    n ICD9%rowtype;

BEGIN
    -- Existing key values
    o.cicd9 := ocicd9;
    o.cdesc := ocdesc;

    -- New record values
    n.cicd9 := ncicd9;
    n.cdesc := ncdesc;
    n.chronic := nchronic;
    n.common := ncommon;

    -- Must set contraints all immediate to trigger constraints immediately for exceptions.
    SET CONSTRAINTS ALL IMMEDIATE; 

    BEGIN
        -- Edit ICD9 record. 
        UPDATE icd9 SET 
            cicd9 = n.cicd9, cdesc = n.cdesc, chronic = n.chronic, common = n.common
        WHERE 
            cicd9 = o.cicd9 and cdesc = o.cdesc;

        IF FOUND THEN
        -- Successfully changed an existing record to new values. (The new value did not already exist). Exit function.
            RETURN;
        END IF;

        EXCEPTION                   

            WHEN unique_violation THEN

                -- The new key already exists, so need to manually move all children to the "new" key.
                PERFORM merge_children_of_icd9(o.cicd9, o.cdesc, n.cicd9, n.cdesc);

                -- Remove the old key values from ICD9
                DELETE FROM icd9
                    WHERE cicd9 = o.cicd9 and cdesc = o.cdesc;

                -- Update existing record.
                UPDATE icd9 SET 
                        chronic = n.chronic, common = n.common
                        WHERE 
                        cicd9 = n.cicd9 and cdesc = n.cdesc;

                RETURN; -- Exit function.
    END;    

    -- No record found to update, so create new record.     
    BEGIN   
        INSERT INTO icd9(
            cicd9, cdesc, chronic, common)
        VALUES ( 
            n.cicd9, n.cdesc, n.chronic, n.common);

        -- Successfully inserted a new icd9 record, so exit function. This line is not reached if INSERT throws an exception.
        RETURN;  

        EXCEPTION                   

            WHEN unique_violation THEN

                -- Key (o.cicd9,o.cdesc) not found for update, but target key (n.cicd9,n.cdesc) already exists.
                -- Update target record with non-key values.
                UPDATE icd9 SET 
                        chronic = n.chronic, common = n.common
                    WHERE 
                        cicd9 = n.cicd9 and cdesc = n.cdesc;

                RETURN;                 

    END;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION g_saveicd9(text, text, text, text, boolean, boolean)
  OWNER TO postgres;


CREATE OR REPLACE FUNCTION merge_children_of_icd9(ocicd9 text, ocdesc text, ncicd9 text, ncdesc text)
  RETURNS void AS
$BODY$

DECLARE
    r RECORD;

BEGIN
    FOR r IN

        WITH fk_actions ( code, action ) AS (
            VALUES  ( 'a', 'error' ),
                ( 'r', 'restrict' ),
                ( 'c', 'cascade' ),
                ( 'n', 'set null' ),
                ( 'd', 'set default' )
        ),
        fk_list AS (
            SELECT pg_constraint.oid as fkoid, conrelid, confrelid::regclass as parentid,
            conname, relname, nspname,
            fk_actions_update.action as update_action,
            fk_actions_delete.action as delete_action,
            conkey as key_cols
            FROM pg_constraint
            JOIN pg_class ON conrelid = pg_class.oid
            JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
            JOIN fk_actions AS fk_actions_update ON confupdtype = fk_actions_update.code
            JOIN fk_actions AS fk_actions_delete ON confdeltype = fk_actions_delete.code
            WHERE contype = 'f'
        ),
        fk_attributes AS (
            SELECT fkoid, conrelid, attname, attnum
            FROM fk_list
            JOIN pg_attribute
                ON conrelid = attrelid
                AND attnum = ANY( key_cols )
            ORDER BY fkoid, attnum
        ),
        fk_cols_list AS (
            SELECT fkoid, array_agg(attname) as cols_list
            FROM fk_attributes
            GROUP BY fkoid
        )
        SELECT fk_list.fkoid, fk_list.conrelid, fk_list.parentid, fk_list.conname, fk_list.relname, fk_cols_list.cols_list 
        FROM fk_list
        JOIN fk_cols_list USING (fkoid)
        WHERE parentid = 'icd9'::regclass

    LOOP

        -- In an UPDATE statement in PL/pgSQL, the table name has to be given as a literal. If you want to dynamically set the
        -- table name and the columns, use the EXECUTE command and paste the query string together.
        -- The USING clause can only be used for substituting data values.
        -- cols_list[1] is cicd9. cols_list[2] is cdesc.

        EXECUTE 'UPDATE ' || quote_ident(r.relname) ||
            ' SET '   || quote_ident(r.cols_list[1]) || ' = , ' 
                      || quote_ident(r.cols_list[2]) || ' = ' ||
            ' WHERE ' || quote_ident(r.cols_list[1]) || ' =  AND ' 
                      || quote_ident(r.cols_list[2]) || ' = '
        USING ncicd9, ncdesc, ocicd9, ocdesc;

    END LOOP;       

RETURN;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION merge_children_of_icd9(text, text, text, text)
  OWNER TO postgres;