--
-- TRIGGERS
--
create table pkeys (pkey1 int4 not null, pkey2 text not null);
create table fkeys (fkey1 int4, fkey2 text, fkey3 int);
create table fkeys2 (fkey21 int4, fkey22 text, pkey23 int not null);
create index fkeys_i on fkeys (fkey1, fkey2);
create index fkeys2_i on fkeys2 (fkey21, fkey22);
create index fkeys2p_i on fkeys2 (pkey23);
insert into pkeys values (10, '1');
insert into pkeys values (20, '2');
insert into pkeys values (30, '3');
insert into pkeys values (40, '4');
insert into pkeys values (50, '5');
insert into pkeys values (60, '6');
create unique index pkeys_i on pkeys (pkey1, pkey2);
--
-- For fkeys:
-- 	(fkey1, fkey2)	--> pkeys (pkey1, pkey2)
-- 	(fkey3)		--> fkeys2 (pkey23)
--
create trigger check_fkeys_pkey_exist 
	before insert or update on fkeys 
	for each row 
	execute procedure 
	check_primary_key ('fkey1', 'fkey2', 'pkeys', 'pkey1', 'pkey2');
create trigger check_fkeys_pkey2_exist 
	before insert or update on fkeys 
	for each row 
	execute procedure check_primary_key ('fkey3', 'fkeys2', 'pkey23');
--
-- For fkeys2:
-- 	(fkey21, fkey22)	--> pkeys (pkey1, pkey2)
--
create trigger check_fkeys2_pkey_exist 
	before insert or update on fkeys2 
	for each row 
	execute procedure 
	check_primary_key ('fkey21', 'fkey22', 'pkeys', 'pkey1', 'pkey2');
-- Test comments
COMMENT ON TRIGGER check_fkeys2_pkey_bad ON fkeys2 IS 'wrong';
ERROR:  trigger "check_fkeys2_pkey_bad" for table "fkeys2" does not exist
COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS 'right';
COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS NULL;
--
-- For pkeys:
-- 	ON DELETE/UPDATE (pkey1, pkey2) CASCADE:
-- 		fkeys (fkey1, fkey2) and fkeys2 (fkey21, fkey22)
--
create trigger check_pkeys_fkey_cascade
	before delete or update on pkeys 
	for each row 
	execute procedure 
	check_foreign_key (2, 'cascade', 'pkey1', 'pkey2', 
	'fkeys', 'fkey1', 'fkey2', 'fkeys2', 'fkey21', 'fkey22');
--
-- For fkeys2:
-- 	ON DELETE/UPDATE (pkey23) RESTRICT:
-- 		fkeys (fkey3)
--
create trigger check_fkeys2_fkey_restrict 
	before delete or update on fkeys2
	for each row 
	execute procedure check_foreign_key (1, 'restrict', 'pkey23', 'fkeys', 'fkey3');
insert into fkeys2 values (10, '1', 1);
insert into fkeys2 values (30, '3', 2);
insert into fkeys2 values (40, '4', 5);
insert into fkeys2 values (50, '5', 3);
-- no key in pkeys
insert into fkeys2 values (70, '5', 3);
ERROR:  tuple references non-existent key
DETAIL:  Trigger "check_fkeys2_pkey_exist" found tuple referencing non-existent key in "pkeys".
insert into fkeys values (10, '1', 2);
insert into fkeys values (30, '3', 3);
insert into fkeys values (40, '4', 2);
insert into fkeys values (50, '5', 2);
-- no key in pkeys
insert into fkeys values (70, '5', 1);
ERROR:  tuple references non-existent key
DETAIL:  Trigger "check_fkeys_pkey_exist" found tuple referencing non-existent key in "pkeys".
-- no key in fkeys2
insert into fkeys values (60, '6', 4);
ERROR:  tuple references non-existent key
DETAIL:  Trigger "check_fkeys_pkey2_exist" found tuple referencing non-existent key in "fkeys2".
delete from pkeys where pkey1 = 30 and pkey2 = '3';
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys are deleted
ERROR:  "check_fkeys2_fkey_restrict": tuple is referenced in "fkeys"
CONTEXT:  SQL statement "delete from fkeys2 where fkey21 = $1 and fkey22 = $2 "
delete from pkeys where pkey1 = 40 and pkey2 = '4';
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys are deleted
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys2 are deleted
update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 50 and pkey2 = '5';
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys are deleted
ERROR:  "check_fkeys2_fkey_restrict": tuple is referenced in "fkeys"
CONTEXT:  SQL statement "delete from fkeys2 where fkey21 = $1 and fkey22 = $2 "
update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 10 and pkey2 = '1';
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys are deleted
NOTICE:  check_pkeys_fkey_cascade: 1 tuple(s) of fkeys2 are deleted
DROP TABLE pkeys;
DROP TABLE fkeys;
DROP TABLE fkeys2;
-- -- I've disabled the funny_dup17 test because the new semantics
-- -- of AFTER ROW triggers, which get now fired at the end of a
-- -- query always, cause funny_dup17 to enter an endless loop.
-- --
-- --      Jan
--
-- create table dup17 (x int4);
-- 
-- create trigger dup17_before 
-- 	before insert on dup17
-- 	for each row 
-- 	execute procedure 
-- 	funny_dup17 ()
-- ;
-- 
-- insert into dup17 values (17);
-- select count(*) from dup17;
-- insert into dup17 values (17);
-- select count(*) from dup17;
-- 
-- drop trigger dup17_before on dup17;
-- 
-- create trigger dup17_after
-- 	after insert on dup17
-- 	for each row 
-- 	execute procedure 
-- 	funny_dup17 ()
-- ;
-- insert into dup17 values (13);
-- select count(*) from dup17 where x = 13;
-- insert into dup17 values (13);
-- select count(*) from dup17 where x = 13;
-- 
-- DROP TABLE dup17;
create sequence ttdummy_seq increment 10 start 0 minvalue 0;
create table tttest (
	price_id	int4, 
	price_val	int4, 
	price_on	int4,
	price_off	int4 default 999999
);
create trigger ttdummy 
	before delete or update on tttest
	for each row 
	execute procedure 
	ttdummy (price_on, price_off);
create trigger ttserial 
	before insert or update on tttest
	for each row 
	execute procedure 
	autoinc (price_on, ttdummy_seq);
insert into tttest values (1, 1, null);
insert into tttest values (2, 2, null);
insert into tttest values (3, 3, 0);
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        2 |         2 |       20 |    999999
        3 |         3 |       30 |    999999
(3 rows)

delete from tttest where price_id = 2;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        3 |         3 |       30 |    999999
        2 |         2 |       20 |        40
(3 rows)

-- what do we see ?
-- get current prices
select * from tttest where price_off = 999999;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        3 |         3 |       30 |    999999
(2 rows)

-- change price for price_id == 3
update tttest set price_val = 30 where price_id = 3;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        2 |         2 |       20 |        40
        3 |        30 |       50 |    999999
        3 |         3 |       30 |        50
(4 rows)

-- now we want to change pric_id in ALL tuples
-- this gets us not what we need
update tttest set price_id = 5 where price_id = 3;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        2 |         2 |       20 |        40
        3 |         3 |       30 |        50
        5 |        30 |       60 |    999999
        3 |        30 |       50 |        60
(5 rows)

-- restore data as before last update:
select set_ttdummy(0);
 set_ttdummy 
-------------
           1
(1 row)

delete from tttest where price_id = 5;
update tttest set price_off = 999999 where price_val = 30;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        2 |         2 |       20 |        40
        3 |         3 |       30 |        50
        3 |        30 |       50 |    999999
(4 rows)

-- and try change price_id now!
update tttest set price_id = 5 where price_id = 3;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        1 |         1 |       10 |    999999
        2 |         2 |       20 |        40
        5 |         3 |       30 |        50
        5 |        30 |       50 |    999999
(4 rows)

-- isn't it what we need ?
select set_ttdummy(1);
 set_ttdummy 
-------------
           0
(1 row)

-- we want to correct some "date"
update tttest set price_on = -1 where price_id = 1;
ERROR:  ttdummy (tttest): you cannot change price_on and/or price_off columns (use set_ttdummy)
-- but this doesn't work
-- try in this way
select set_ttdummy(0);
 set_ttdummy 
-------------
           1
(1 row)

update tttest set price_on = -1 where price_id = 1;
select * from tttest;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        2 |         2 |       20 |        40
        5 |         3 |       30 |        50
        5 |        30 |       50 |    999999
        1 |         1 |       -1 |    999999
(4 rows)

-- isn't it what we need ?
-- get price for price_id == 5 as it was @ "date" 35
select * from tttest where price_on <= 35 and price_off > 35 and price_id = 5;
 price_id | price_val | price_on | price_off 
----------+-----------+----------+-----------
        5 |         3 |       30 |        50
(1 row)

drop table tttest;
drop sequence ttdummy_seq;
--
-- tests for per-statement triggers
--
CREATE TABLE log_table (tstamp timestamp default timeofday()::timestamp);
CREATE TABLE main_table (a int, b int);
COPY main_table (a,b) FROM stdin;
CREATE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS '
BEGIN
	RAISE NOTICE ''trigger_func() called: action = %, when = %, level = %'', TG_OP, TG_WHEN, TG_LEVEL;
	RETURN NULL;
END;';
CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_table
FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func();
CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_table
FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func();
--
-- if neither 'FOR EACH ROW' nor 'FOR EACH STATEMENT' was specified,
-- CREATE TRIGGER should default to 'FOR EACH STATEMENT'
--
CREATE TRIGGER before_upd_stmt_trig AFTER UPDATE ON main_table
EXECUTE PROCEDURE trigger_func();
CREATE TRIGGER before_upd_row_trig AFTER UPDATE ON main_table
FOR EACH ROW EXECUTE PROCEDURE trigger_func();
INSERT INTO main_table DEFAULT VALUES;
NOTICE:  trigger_func() called: action = INSERT, when = BEFORE, level = STATEMENT
NOTICE:  trigger_func() called: action = INSERT, when = AFTER, level = STATEMENT
UPDATE main_table SET a = a + 1 WHERE b < 30;
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = ROW
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = ROW
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = ROW
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = ROW
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = STATEMENT
-- UPDATE that effects zero rows should still call per-statement trigger
UPDATE main_table SET a = a + 2 WHERE b > 100;
NOTICE:  trigger_func() called: action = UPDATE, when = AFTER, level = STATEMENT
-- COPY should fire per-row and per-statement INSERT triggers
COPY main_table (a, b) FROM stdin;
NOTICE:  trigger_func() called: action = INSERT, when = BEFORE, level = STATEMENT
NOTICE:  trigger_func() called: action = INSERT, when = AFTER, level = STATEMENT
SELECT * FROM main_table ORDER BY a, b;
 a  | b  
----+----
  6 | 10
 21 | 20
 30 | 40
 31 | 10
 50 | 35
 50 | 60
 81 | 15
    |   
(8 rows)

-- Test enable/disable triggers
create table trigtest (i serial primary key);
NOTICE:  CREATE TABLE will create implicit sequence "trigtest_i_seq" for serial column "trigtest.i"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "trigtest_pkey" for table "trigtest"
-- test that disabling RI triggers works
create table trigtest2 (i int references trigtest(i) on delete cascade);
create function trigtest() returns trigger as $$
begin
	raise notice '% % % %', TG_RELNAME, TG_OP, TG_WHEN, TG_LEVEL;
	return new;
end;$$ language plpgsql;
create trigger trigtest_b_row_tg before insert or update or delete on trigtest
for each row execute procedure trigtest();
create trigger trigtest_a_row_tg after insert or update or delete on trigtest
for each row execute procedure trigtest();
create trigger trigtest_b_stmt_tg before insert or update or delete on trigtest
for each statement execute procedure trigtest();
create trigger trigtest_a_stmt_tg after insert or update or delete on trigtest
for each statement execute procedure trigtest();
insert into trigtest default values;
NOTICE:  trigtest INSERT BEFORE STATEMENT
NOTICE:  trigtest INSERT BEFORE ROW
NOTICE:  trigtest INSERT AFTER ROW
NOTICE:  trigtest INSERT AFTER STATEMENT
alter table trigtest disable trigger trigtest_b_row_tg;
insert into trigtest default values;
NOTICE:  trigtest INSERT BEFORE STATEMENT
NOTICE:  trigtest INSERT AFTER ROW
NOTICE:  trigtest INSERT AFTER STATEMENT
alter table trigtest disable trigger user;
insert into trigtest default values;
alter table trigtest enable trigger trigtest_a_stmt_tg;
insert into trigtest default values;
NOTICE:  trigtest INSERT AFTER STATEMENT
insert into trigtest2 values(1);
insert into trigtest2 values(2);
delete from trigtest where i=2;
NOTICE:  trigtest DELETE AFTER STATEMENT
select * from trigtest2;
 i 
---
 1
(1 row)

alter table trigtest disable trigger all;
delete from trigtest where i=1;
select * from trigtest2;
 i 
---
 1
(1 row)

-- ensure we still insert, even when all triggers are disabled
insert into trigtest default values;
select *  from trigtest;
 i 
---
 3
 4
 5
(3 rows)

drop table trigtest2;
drop table trigtest;
-- dump trigger data
CREATE TABLE trigger_test (
        i int,
        v varchar
);
CREATE OR REPLACE FUNCTION trigger_data()  RETURNS trigger 
LANGUAGE plpgsql AS $$

declare

	argstr text;
	relid text;

begin

	relid := TG_relid::regclass;

	-- plpgsql can't discover its trigger data in a hash like perl and python
	-- can, or by a sort of reflection like tcl can, 
	-- so we have to hard code the names.
	raise NOTICE 'TG_NAME: %', TG_name;
	raise NOTICE 'TG_WHEN: %', TG_when;
	raise NOTICE 'TG_LEVEL: %', TG_level;
	raise NOTICE 'TG_OP: %', TG_op;
	raise NOTICE 'TG_RELID::regclass: %', relid;
	raise NOTICE 'TG_RELNAME: %', TG_relname;
	raise NOTICE 'TG_TABLE_NAME: %', TG_table_name;
	raise NOTICE 'TG_TABLE_SCHEMA: %', TG_table_schema;
	raise NOTICE 'TG_NARGS: %', TG_nargs;

	argstr := '[';
	for i in 0 .. TG_nargs - 1 loop
		if i > 0 then
			argstr := argstr || ', ';
		end if;
		argstr := argstr || TG_argv[i];
	end loop;
	argstr := argstr || ']';
	raise NOTICE 'TG_ARGV: %', argstr;

	if TG_OP != 'INSERT' then
		raise NOTICE 'OLD: %', OLD;
	end if;

	if TG_OP != 'DELETE' then
		raise NOTICE 'NEW: %', NEW;
	end if;

	if TG_OP = 'DELETE' then
		return OLD;
	else
		return NEW;
	end if;

end;
$$;
CREATE TRIGGER show_trigger_data_trig 
BEFORE INSERT OR UPDATE OR DELETE ON trigger_test
FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');
insert into trigger_test values(1,'insert');
NOTICE:  TG_NAME: show_trigger_data_trig
NOTICE:  TG_WHEN: BEFORE
NOTICE:  TG_LEVEL: ROW
NOTICE:  TG_OP: INSERT
NOTICE:  TG_RELID::regclass: trigger_test
NOTICE:  TG_RELNAME: trigger_test
NOTICE:  TG_TABLE_NAME: trigger_test
NOTICE:  TG_TABLE_SCHEMA: public
NOTICE:  TG_NARGS: 2
NOTICE:  TG_ARGV: [23, skidoo]
NOTICE:  NEW: (1,insert)
update trigger_test set v = 'update' where i = 1;
NOTICE:  TG_NAME: show_trigger_data_trig
NOTICE:  TG_WHEN: BEFORE
NOTICE:  TG_LEVEL: ROW
NOTICE:  TG_OP: UPDATE
NOTICE:  TG_RELID::regclass: trigger_test
NOTICE:  TG_RELNAME: trigger_test
NOTICE:  TG_TABLE_NAME: trigger_test
NOTICE:  TG_TABLE_SCHEMA: public
NOTICE:  TG_NARGS: 2
NOTICE:  TG_ARGV: [23, skidoo]
NOTICE:  OLD: (1,insert)
NOTICE:  NEW: (1,update)
delete from trigger_test;
NOTICE:  TG_NAME: show_trigger_data_trig
NOTICE:  TG_WHEN: BEFORE
NOTICE:  TG_LEVEL: ROW
NOTICE:  TG_OP: DELETE
NOTICE:  TG_RELID::regclass: trigger_test
NOTICE:  TG_RELNAME: trigger_test
NOTICE:  TG_TABLE_NAME: trigger_test
NOTICE:  TG_TABLE_SCHEMA: public
NOTICE:  TG_NARGS: 2
NOTICE:  TG_ARGV: [23, skidoo]
NOTICE:  OLD: (1,update)
      
DROP TRIGGER show_trigger_data_trig on trigger_test;
      
DROP FUNCTION trigger_data();
DROP TABLE trigger_test;
--
-- Test use of row comparisons on OLD/NEW
--
CREATE TABLE trigger_test (f1 int, f2 text, f3 text);
-- this is the obvious (and wrong...) way to compare rows
CREATE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$
begin
	if row(old.*) = row(new.*) then
		raise notice 'row % not changed', new.f1;
	else
		raise notice 'row % changed', new.f1;
	end if;
	return new;
end$$;
CREATE TRIGGER t
BEFORE UPDATE ON trigger_test
FOR EACH ROW EXECUTE PROCEDURE mytrigger();
INSERT INTO trigger_test VALUES(1, 'foo', 'bar');
INSERT INTO trigger_test VALUES(2, 'baz', 'quux');
UPDATE trigger_test SET f3 = 'bar';
NOTICE:  row 1 not changed
NOTICE:  row 2 changed
UPDATE trigger_test SET f3 = NULL;
NOTICE:  row 1 changed
NOTICE:  row 2 changed
-- this demonstrates that the above isn't really working as desired:
UPDATE trigger_test SET f3 = NULL;
NOTICE:  row 1 changed
NOTICE:  row 2 changed
-- the right way when considering nulls is
CREATE OR REPLACE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$
begin
	if row(old.*) is distinct from row(new.*) then
		raise notice 'row % changed', new.f1;
	else
		raise notice 'row % not changed', new.f1;
	end if;
	return new;
end$$;
UPDATE trigger_test SET f3 = 'bar';
NOTICE:  row 1 changed
NOTICE:  row 2 changed
UPDATE trigger_test SET f3 = NULL;
NOTICE:  row 1 changed
NOTICE:  row 2 changed
UPDATE trigger_test SET f3 = NULL;
NOTICE:  row 1 not changed
NOTICE:  row 2 not changed
DROP TABLE trigger_test;
DROP FUNCTION mytrigger();
-- Test snapshot management in serializable transactions involving triggers
-- per bug report in 6bc73d4c0910042358k3d1adff3qa36f8df75198ecea@mail.gmail.com
CREATE FUNCTION serializable_update_trig() RETURNS trigger LANGUAGE plpgsql AS
$$
declare
	rec record;
begin
	new.description = 'updated in trigger';
	return new;
end;
$$;
CREATE TABLE serializable_update_tab (
	id int,
	filler  text,
	description text
);
CREATE TRIGGER serializable_update_trig BEFORE UPDATE ON serializable_update_tab
	FOR EACH ROW EXECUTE PROCEDURE serializable_update_trig();
INSERT INTO serializable_update_tab SELECT a, repeat('xyzxz', 100), 'new'
	FROM generate_series(1, 50) a;
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
UPDATE serializable_update_tab SET description = 'no no', id = 1 WHERE id = 1;
COMMIT;
SELECT description FROM serializable_update_tab WHERE id = 1;
    description     
--------------------
 updated in trigger
(1 row)

DROP TABLE serializable_update_tab;
-- minimal update trigger
CREATE TABLE min_updates_test (
	f1	text,
	f2 int,
	f3 int);
CREATE TABLE min_updates_test_oids (
	f1	text,
	f2 int,
	f3 int) WITH OIDS;
INSERT INTO min_updates_test VALUES ('a',1,2),('b','2',null);
INSERT INTO min_updates_test_oids VALUES ('a',1,2),('b','2',null);
CREATE TRIGGER z_min_update 
BEFORE UPDATE ON min_updates_test
FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
CREATE TRIGGER z_min_update 
BEFORE UPDATE ON min_updates_test_oids
FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
\set QUIET false
UPDATE min_updates_test SET f1 = f1;
UPDATE 0
UPDATE min_updates_test SET f2 = f2 + 1;
UPDATE 2
UPDATE min_updates_test SET f3 = 2 WHERE f3 is null;
UPDATE 1
UPDATE min_updates_test_oids SET f1 = f1;
UPDATE 0
UPDATE min_updates_test_oids SET f2 = f2 + 1;
UPDATE 2
UPDATE min_updates_test_oids SET f3 = 2 WHERE f3 is null;
UPDATE 1
\set QUIET true
SELECT * FROM min_updates_test;
 f1 | f2 | f3 
----+----+----
 a  |  2 |  2
 b  |  3 |  2
(2 rows)

SELECT * FROM min_updates_test_oids;
 f1 | f2 | f3 
----+----+----
 a  |  2 |  2
 b  |  3 |  2
(2 rows)

DROP TABLE min_updates_test;
DROP TABLE min_updates_test_oids;
