drop table testtrig if exists;
drop table triglog if exists;
create cached table testtrig(id integer, data varchar(20), updated date);
create cached table triglog(id integer generated by default as identity, data varchar(20), op varchar(10));
create trigger trigone after insert on testtrig referencing new row as newrow
 for each row when (newrow.id >1)
 insert into triglog values (newrow.id, newrow.data, 'inserted')
create trigger trigtwo before update on testtrig referencing old row as oldrow new row as newrow
 for each row when (oldrow.updated is null)
 set newrow.updated = date'2009-11-01'
insert into testtrig values(1,'one', null);
insert into testtrig values(2,'two', date'1999-11-01');
/*r2,two,inserted*/select * from triglog
update testtrig set data = data || ' ' || data
/*r
 1,one one,2009-11-01
 2,two two,1999-11-01
*/select * from testtrig


create trigger trigthree after delete on testtrig referencing old row as oldrow
 for each row
 insert into triglog values oldrow.id, oldrow.data, 'deleted'

delete from testtrig
/*c2*/select * from triglog where op = 'deleted'

create procedure proc_trig(in in_arg_one varchar(10))
  language sql parameter style sql deterministic modifies sql data
    label_one: begin atomic
        insert into triglog values default, in_arg_one, null;
     end label_one;

create cached table testtrig2(id integer, data varchar(20), updated date);
create trigger trigfour after insert on testtrig2 referencing new row as newrow
 for each row
 call proc_trig(newrow.data)

insert into testtrig2 values 10, 'felix', current_date
/*c1*/select * from triglog where data='felix'

drop trigger trigone;
drop trigger trigtwo;
drop trigger trigthree;
drop trigger trigfour;

drop table testtrig;
drop table testtrig2;

create cached table testtrig(id integer, data varchar(20), updated date);
create cached table testtrig2(id integer, data varchar(20), updated date);

CREATE PROCEDURE test_proc_three(pCount INT)
 NO SQL LANGUAGE JAVA
 EXTERNAL NAME 'CLASSPATH:org.hsqldb.test.TestStoredProcedure.procTest3'

CREATE TRIGGER trigfive AFTER INSERT ON testtrig
 referencing NEW ROW AS newrow
 FOR EACH ROW WHEN (newrow.data IS NOT NULL)
 BEGIN ATOMIC
 DECLARE cwExists int DEFAULT 0;
 SET cwExists = 0;
 select count(*) into cwExists from testtrig2 where data = 'action1';
 call test_proc_three(cwExists);
 insert into testtrig2 values cwExists, newrow.data, current_date;
 END

delete from testtrig;
create view vtrig as select id, data, updated, 'fixed string' fixed from testtrig;

create trigger triginstead instead of insert on vtrig
 referencing new row as newrow
 for each row
 insert into testtrig values newrow.id, newrow.data || ' added', newrow.updated - 1 day

insert into vtrig values 10, 'string', current_date, null
/*c1*/select * from vtrig where data = 'string added';
/*c1*/select * from testtrig;
