Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1iMvZ0-0005wx-Gj for pgsql-general@arkaria.postgresql.org; Tue, 22 Oct 2019 14:55:11 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1iMvYw-0001Dt-R0 for pgsql-general@arkaria.postgresql.org; Tue, 22 Oct 2019 14:55:06 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1iMvYw-0001Dm-D2 for pgsql-general@lists.postgresql.org; Tue, 22 Oct 2019 14:55:06 +0000 Received: from post.visena.com ([46.226.10.50]) by magus.postgresql.org with esmtps (TLS1.2:DHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1iMvYp-0005gs-O3 for pgsql-general@lists.postgresql.org; Tue, 22 Oct 2019 14:55:05 +0000 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=visena.com; s=20141101.wh; h=Content-Type:MIME-Version:Subject:Message-ID:To:From:Date; bh=lrboTg4LWXDZ6whcRS3pUwlxxAfVdSxMiYVEFUtRYoY=; b=JoXa4xlv7uQ6HE9ly9JfVWHjrqrItXG6ysA93L+DG7IrGnO/uujoMiVbVC/qvVy4LE9AwIHQzAoyRTBnUQqiu+hXKz1u5J/xf43OScYj4AFtM/f6ELC10ZRzt3qKnjyPye3/caT/9+9CsLFA7uqXjU4Uoe0WtKiZUAzD/t2R75c=; Received: from [10.0.1.10] (helo=tc7-visena.wh.internal.visena.com) by post.visena.com with esmtp (Exim 4.82) (envelope-from ) id 1iMvYk-0008VF-VD for pgsql-general@lists.postgresql.org; Tue, 22 Oct 2019 16:54:58 +0200 Received: from localhost ([127.0.0.1] helo=tc7-visena.wh.internal.visena.com) by tc7-visena.wh.internal.visena.com with esmtp (Exim 4.90_1) (envelope-from ) id 1iMvYk-0002l1-Rn for pgsql-general@lists.postgresql.org; Tue, 22 Oct 2019 16:54:54 +0200 Date: Tue, 22 Oct 2019 16:54:54 +0200 (CEST) From: Andreas Joseph Krogh To: pgsql-general@lists.postgresql.org Message-ID: Subject: Having more than one constraint trigger on a table MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_Part_150_1557768671.1571756094714" X-Mailer: Visena Mail 2.2.150 X-Spam-Score: -1.0 X-Spam-Report: SpamAssasin (score=-1.0, required 5.0 ALL_TRUSTED=-1,HTML_MESSAGE=0.001) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk ------=_Part_150_1557768671.1571756094714 Content-Type: multipart/related; boundary="----=_Part_151_1259888269.1571756094714" ------=_Part_151_1259888269.1571756094714 Content-Type: multipart/alternative; boundary="----=_Part_152_1604304911.1571756094741" ------=_Part_152_1604304911.1571756094741 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit Hi. I have the following schema (question at bottom): ============================== CREATE TABLE company(id SERIAL PRIMARY KEY, parent_id INTEGER REFERENCES company(id) DEFERRABLE INITIALLY DEFERRED , name VARCHAR NOT NULL, duns_number VARCHAR, fts_all tsvector, t_updated BOOLEAN); CREATE or replace FUNCTION update_company_fts(p_company_id integer) RETURNS VOID AS $$ BEGIN UPDATE companycomp SET fts_all = to_tsvector('simple' , comp.name || ' ' || coalesce (comp.duns_number,'') ) WHERE comp.id = p_company_id; raise notice 'Running update of %', p_company_id; END; $$ LANGUAGE plpgsql; -- re-index all: CREATE OR REPLACE FUNCTIONindex_company() RETURNS VOID AS $$ DECLARE v_company_id INTEGER; begin FOR v_company_id IN (SELECT id FROM company) LOOP perform update_company_fts(v_company_id); END LOOP; END; $$ LANGUAGE plpgsql; create or replace functionupdate_company_fts_tf() returns TRIGGER AS $$ declare v_company_idINTEGER; BEGIN v_company_id := NEW.id; perform update_company_fts (v_company_id);RETURN NULL; END; $$ LANGUAGE plpgsql; -- General cleanup functions for constraint triggersCREATE OR REPLACE FUNCTION trigger_function_set_updated() returns TRIGGER AS $$ BEGIN update company set t_updated =TRUE WHERE id = NEW.id; RETURN NULL; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTIONtrigger_function_clear_updated() returns TRIGGER AS $$ BEGIN update company set t_updated = NULL WHERE id = NEW.id; RETURN NULL; END; $$LANGUAGE plpgsql; CREATE CONSTRAINT TRIGGER trigger_1_update_fts AFTER INSERT OR UPDATE of name, duns_number ON company DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.t_updated IS NULL) EXECUTE PROCEDURE update_company_fts_tf(); CREATE CONSTRAINT TRIGGERtrigger_2 AFTER INSERT OR UPDATE of name, duns_number, parent_idON company -- NOT DEFERRED FOR EACH ROW WHEN (NEW.t_updated IS NULL) EXECUTE PROCEDUREtrigger_function_set_updated(); CREATE CONSTRAINT TRIGGER trigger_3AFTER INSERT OR UPDATE OF t_updated ON company DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.t_updated) EXECUTE PROCEDURE trigger_function_clear_updated(); CREATE OR REPLACE FUNCTION company_parent_no_cycle() returns TRIGGER AS $$ BEGIN IF (WITH recursive tr (id, parent_id, all_ids,cycle) AS ( SELECT id, parent_id, ARRAY [id], false FROMcompany tr WHERE id = NEW.id UNION ALL SELECT t.id, t.parent_id, all_ids || t.id, t.id =ANY (all_ids) FROM company t JOIN tr ON t.parent_id = tr.id AND NOT cycle) SELECT count(*) FROM tr where cycle = true) > 0 THEN RAISE EXCEPTION 'Cannot have cyclic parent relations for company' USING SCHEMA = TG_TABLE_SCHEMA,TABLE = TG_TABLE_NAME, CONSTRAINT = TG_NAME , ERRCODE = '23514' /*check_violation*/, COLUMN = 'parent_id'; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql;CREATE CONSTRAINT TRIGGER trigger_1_check_nocycle AFTER INSERT OR UPDATE ofparent_id ON company DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.t_updated IS NULL) EXECUTE PROCEDURE company_parent_no_cycle(); ============================== What I'm after is to have 2 "logical constraint-triggers" perform logic only once (each) on the "company"-table. To make constraint-triggers fire only once (in PostgreSQL) a common method is to have a schema with 3 triggers, and a "magic" t_updated column, and they must be named so they (the triggers, not the trigger-functions) are fired in lexical order (alphabetically). And it's important that the 2nd. trigger (here "trigger_2") is NOT deferred. In my schema above I have 2 "logical chuchks" which each perform some stuff and shall only do it once per row at commit-time. The first "main" trigger-function is update_company_fts_tf() and it updates a column (fts_all) of type tsvector. This is done in a trigger so that it may add stuff (customer-number etc.) from other tables as needed (which is not possible with PG-12's new STORED-columns). The second "main" trigger-function is company_parent_no_cycle() and assures there are no parent/child-cycles. Question: 1. I have "re-used" trigger_2 and trigger_3, and trigger_2's "...OR UPDATE OF"-list is the sum of all columns updated(used) in the 2 main-triggers, that is "name", "duns_number" and parent_id. trigger_3 only checks t_updated. Is this correct usage, can I assume this will work correctly? 2. If I need a 3rd "logical trigger", is it enough to add another trigger named accordingly, for instance "trigger_1_someotherstuff", and add it's column to the "UPDATE OF"-list of "trigger_2" (it it uses a column not already listed there)? 3. Is there some easier way to do this? Is it clear what I'm asking about? :-) Thanks. -- Andreas Joseph Krogh ------=_Part_152_1604304911.1571756094741 Content-Type: text/html;charset=UTF-8 Content-Transfer-Encoding: quoted-printable
Hi.
=C2=A0
I have the following schema (question at bottom):
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D
CREATE TABLE company(id SERIAL PRIMARY KEY, parent_id INTEGER REFERENCES company(id) DEFERRABLE INITIALLY DEFERRED , name VARCHAR NOT NULL, =
duns_number VARCHAR,=
 fts_all tsvector, t=
_updated BOOLEAN);

CREATE or replace FUNCTION =
update_company_fts(p_compa=
ny_id integer) RETURNS VOID AS
$$
BEGIN
    UPDATE company comp
    SET fts_all =3D =
to_tsvector('simple'
        , com=
p.name
              || ' ' || coalesce(comp.duns_number, '')
        )
    WHERE comp.id =
=3D p_company_id;

    raise notice 'Running update of %', =
p_company_id;
END;
$$ LANGUAGE plpgsql;

-- re-index all:
CREATE OR REPLACE FU=
NCTION index_company() RETURNS VOID AS
$$
DECLARE
    v_company=
_id INTEGER;
begin
    FOR v_com=
pany_id IN (SELECT id FROM company)
        LOOP
            perform =
update_company_fts(v_compa=
ny_id);
        END LOOP;
END;
$$ LANGUAGE plpgsql;

create or replace function =
update_company_fts_tf() returns TRIGGER AS
$$
declare
    v_company=
_id INTEGER;
BEGIN
    v_company=
_id :=3D NEW.id;
    perform update_company_fts(v_company_id);
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;


-- General cleanup functio=
ns for constraint triggers
CREATE OR REPLACE FU=
NCTION trigger_function_set_updat=
ed() returns TRIGGER=
 AS
$$
BEGIN
    update company set t_updated =3D TRUE WHERE id =3D NEW.id;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION =
trigger_function_clear_updated() returns TRIGGER AS
$$
BEGIN
    update company set t_updated =3D NULL WHERE id =3D NEW.id;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE CONSTRAINT TRIGGER <=
/span>trigger_1_update_fts
    AFTER INSERT OR UPDATE =
of name, duns_number
    ON company DEFERRABLE INITIALLY DEFERRED
    FOR EACH ROW
    WHEN (NEW.t_updated IS NULL)
EXECUTE PROCEDURE update_company_fts_tf();

CREATE CONSTRAINT TRIGGER <=
/span>trigger_2
    AFTER INSERT OR UPDATE =
of name, duns_number, parent_id
    ON company -- NOT DEFERRED
    FOR EACH ROW
    WHEN (NEW.t_updated IS NULL)
EXECUTE PROCEDURE trigger_function_set_updated();

CREATE CONSTRAINT TRIGGER <=
/span>trigger_3
    AFTER INSERT OR UPDATE =
OF t_updated
    ON company DEFERRABLE INITIALLY DEFERRED
    FOR EACH ROW
    WHEN (NEW.t_updated)
EXECUTE PROCEDURE trigger_function_clear_updated();

CREATE OR REPLACE FUNCTION =
company_parent_no_cycle() =
returns TRIGGER AS
$$
BEGIN
    IF (WITH recursive tr (id, pa=
rent_id, all_ids, cycle) AS (
        SELECT id, p=
arent_id, ARRAY [id]=
, false
        FROM =
company tr
        WHERE id =3D=
 NEW.id
        UNION ALL
        SELECT t.id, t.parent_id, all_ids || t.id, t.id =3D =
ANY (all_ids)
        FROM company t
                 JOIN tr ON t.parent_id =
=3D tr.id AND NOT cycle)
        SELECT count(*)
        FROM tr
        where cycle =
=3D true) > 0 THEN
        RAISE EXCEPT=
ION 'Cannot have cyc=
lic parent relations for company'
            <=
span style=3D"color:#000080;font-weight:bold;">USING SCHEMA =3D TG_T=
ABLE_SCHEMA, TABLE =
=3D TG_TABLE_NAME, CONSTRAI=
NT =3D TG_NAME
                , ERRCODE <=
/span>=3D '23514'/*check_violation*/, <=
span style=3D"color:#000080;font-weight:bold;">COLUMN =3D 'parent_id';
    END IF;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE CONSTRAINT TRIGGER <=
/span>trigger_1_check_nocycle
    AFTER INSERT OR UPDATE =
of parent_id
    ON company DEFERRABLE INITIALLY DEFERRED
    FOR EACH ROW
    WHEN (NEW.t_updated IS NULL)
EXECUTE PROCEDURE company_parent_no_cycle();
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D
=C2=A0
What I'm after is to have 2 "logical constraint-triggers" pe= rform logic only once (each)=C2=A0on the "company"-table= .
To make constraint-triggers fire only once (in PostgreSQL)=C2=A0a comm= on method is to have a schema=C2=A0with 3 triggers, and a "magic"= t_updated column, and they must be named so they (the triggers, not the tr= igger-functions) are fired in lexical order (alphabetically).=C2=A0 And it'= s important that the 2nd. trigger (here "trigger_2") is NOT defer= red.
=C2=A0
In my schema above I have 2 "logical chuchks" which each per= form some stuff and shall only do it once per row at commit-time.
The first "main"=C2=A0trigger-function is=C2=A0update_co= mpany_fts_tf()=C2=A0and it updates a column (fts_all) of type tsvector= . This is done in a trigger so that it may add stuff (customer-number etc.)= from other tables as needed (which is not possible with PG-12's new STORED= -columns).
The second "main" trigger-function is=C2=A0company_paren= t_no_cycle() and=C2=A0=C2=A0assures there are no parent/child-cycles.<= /div>
=C2=A0
Question:
1. I have "re-used"=C2=A0trigger_2 and=C2=A0trigger_3, and t= rigger_2's "...OR UPDATE OF"-list is the sum of all columns updat= ed(used) in the 2 main-triggers, that is "name", "duns_numbe= r" and parent_id. trigger_3 only checks t_updated.
Is this correct usage, can I assume this will work correctly?
2. If I need a 3rd "logical trigger", is it enough to add an= other trigger named accordingly, for instance "trigger_1_someotherstuf= f", and add it's column to the "UPDATE OF"-list of "tri= gger_2" (it it uses a column not already listed there)?
3. Is there some easier way to do this?
=C2=A0
Is it clear what I'm asking about? :-)
=C2=A0
Thanks.
=C2=A0
">
--
Andreas Joseph Krogh
------=_Part_152_1604304911.1571756094741-- ------=_Part_151_1259888269.1571756094714-- ------=_Part_150_1557768671.1571756094714--