HSQLDB Trigger Syntax - is it impossible to make subqueries inside a trigger? - sql

I have a weird problem with a trigger in HSQLDB. I've checked the syntax several times but I haven't found any mistakes. I now think that it may be impossible to create a subquery inside a trigger.
This is the code:
create trigger activate_member after update on member
REFERENCING OLD AS old NEW AS new
for each row
begin atomic
IF new.active = FALSE AND old.active = TRUE then
insert into member_inactive
(
member,
since,
until
)
values (
new.id,
(select since from member_active where
member = new.id AND since = (select max(since) from member_active where
member = new.id group by member)),
curdate()
);
ELSEIF new.active = TRUE AND old.active = FALSE then
insert into member_active (member, since) values
(new.id, curdate());
end if;
end;
I think I've made everything correct: I have semicolons on every query inside the IF and ELSIEF statements, and trailing semicolon after end if.
But I still get this error message:
SEVERE SQL Error at 'database.sql' line 125:
"create trigger activate_member after update on member
REFERENCING OLD AS old NEW AS new
for each row
begin atomic
IF new.active = FALSE AND old.active = TRUE then
insert into member_inactive
(
member,
since,
until
)
values (
new.id,
(select since from member_active where member = new.id AND since = (select max(since) from member_active where member = new.id group by member)),
curdate()
)"
unexpected end of statement: required: ; : line: 17
org.hsqldb.cmdline.SqlTool$SqlToolException
But where I should add a semicolon? I think the problem is the subquery inside the insert, but that makes no sense.
Probably the begin atomic is problematic. But I see no other way to have an if-else statement inside a trigger without it!

Have you tried adding the ";" after "curdate()"?
Hopefully that helps you with that problem.

You may get a problem related to the use of new.id in the nested subquery in the VALUES clause of the INSERT statements.
Create a variable and assign the computed "SINCE" column to this, then use this variable in the VALUES list.
But at second glance, it looks the issue may relate to the software you use to execute the script, which cuts off the statement when it finds a semicolon. If you are using SqlTool, please use the latest version of the software and check the Guide on using RAW mode to avoid this issue.

i found now whats caused this problem: hsqldb only has begin atomic blocks inside a trigger.
Inside a begin atomic block i cannot use insert statements...
i now changed it to two triggers with where (statement) clauses, this works also

Related

exists condition in a trigger

I'm quite new to PL/SQL, sorry if the question is obvious
According to the TRIGGER documentation, there is a WHEN ( condition ) for triggers. I wanted to use an exists condition, which requires a subquery, however, I have the following error :
ORA-02251
00000 - "subquery not allowed here"
*Cause: Subquery is not allowed here in the statement.
*Action: Remove the subquery from the statement.
What did I miss?
My condition is the following :
CREATE OR REPLACE TRIGGER mytrigger AFTER UPDATE OF column ON THIS_TABLE
FOR EACH ROW
WHEN (NEW.status = 'approved' AND EXISTS (
SELECT * FROM JUNCTION_TABLE WHERE THIS_TABLE_ID=NEW.this_table_id AND OTHER_TABLE_ID = 'SOMETHING'))
DECLARE
BEGIN
END;
I want to check whether the row is associated to a given value, which I can only find in a junction table.
I could surely do this in the PL/SQL part of the trigger, but :
it is related to the trigger rather than the business logic in itself
I'd like to understand what I missed in the documentation and why it is not possible.
If another condition might do this, I'm also interested.
I would write this with the conditional element within the trigger itself, something like
CREATE OR REPLACE TRIGGER mytrigger AFTER UPDATE OF column ON THIS_TABLE
FOR EACH ROW
WHEN (NEW.status = 'approved')
DECLARE
BEGIN
IF EXISTS (
SELECT * FROM JUNCTION_TABLE WHERE THIS_TABLE_ID=NEW.this_table_id AND OTHER_TABLE_ID = 'SOMETHING'))
...
END;
I don't know which Oracle documentation was used. Though the Oracle 10.2 documentation doesn't mention this, in the Oracle 11.1 documentation the limitation is mentioned:
The expression in a WHEN clause must be a SQL expression, and it cannot include a subquery. You cannot use a PL/SQL expression (including user-defined functions) in the WHEN clause.
There's no alternative I can think of at the moment to checking the condition inside the trigger code, as mentioned.

sql query inside if stage with exists

I want to check if the id I want to insert into tableA exists in tableB into an if statement
Can I do something like this
if new.id exists (select id from tableB where stat = '0' ) then
some code here
end if;
When I try this I get an error message, any thoughts?
Why not do it like this? I'm not very knowledgeable about PostgreSQL but this would work in T-SQL.
INSERT INTO TargetTable(ID)
SELECT ID
FROM TableB
WHERE ID NOT IN (SELECT DISTINCT ID FROM TargetTable)
This is usually done with a trigger. A trigger function does the trick:
CREATE FUNCTION "trf_insert_tableA"() RETURNS trigger AS $$
BEGIN
PERFORM * FROM "tableB" WHERE id = NEW.id AND stat = '0';
IF FOUND THEN
-- Any additional code to go here, optional
RETURN NEW;
ELSE
RETURN NULL;
END IF;
END; $$ LANGUAGE plpgsql;
CREATE TRIGGER "tr_insert_tableA"
BEFORE INSERT ON "tableA"
FOR EACH ROW EXECUTE PROCEDURE "trf_insert_tableA"();
A few notes:
Identifiers in PostgreSQL are case-insensitive. PostgreSQL by default makes them lower-case. To maintain the case, use double-quotes. To make your life easy, use lower-case only.
A trigger needs a trigger function, this is always a two-step affair.
In an INSERT trigger, you can use the NEW implicit parameter to access the column values that are attempted to be inserted. In the trigger function you can modify these values and those values are then inserted. This only works in a BEFORE INSERT trigger, obviously; AFTER INSERT triggers are used for side effects such as logging, auditing or cascading inserts to other tables.
The PERFORM statement is a special form of a SELECT statement to test for the presence of data; it does not return any data, but it does set the FOUND implicit parameter that you can use in a conditional statement.
Depending on your logic, you may want the insert to succeed or to fail. RETURN NEW to make the insert succeed, RETURN NULL to make it fail.
After you defined the trigger, you can simply issue an INSERT statement: the trigger function is invoked automatically.
Presumably, you want something like this:
if exists (select 1 from tableB b where stat = '0' and b.id = new.id) then
some code here
end if;

Prevent insert if condition is met

I have a table Content like this:
id | text | date | idUser → User | contentType
And another table Answer:
idAnswer → Content | idQuestion → Content | isAccepted
I want to ensure that the Answer's date is bigger than the Question's date. A question is a Content with contentType = 'QUESTION'.
I tried to solve this with the following trigger, but when I try to insert an Answer there's an error:
ERROR: record "new" has no field "idanswer"
CONTEXT: SQL statement "SELECT (SELECT "Content".date FROM "Content" WHERE "Content".id = NEW.idAnswer) < (SELECT "Content".date FROM "Content" WHERE "Content".id = NEW.idQuestion)"
PL/pgSQL function "check_valid_date_answer" line 2 at IF
Trigger:
CREATE TRIGGER check_valid_answer
AFTER INSERT ON "Answer"
FOR EACH ROW EXECUTE PROCEDURE check_valid_date_answer();
Trigger function:
CREATE FUNCTION check_valid_date_answer() RETURNS trigger
LANGUAGE plpgsql
AS $$BEGIN
IF (SELECT "Content".date FROM "Content"
WHERE "Content".id = NEW.idAnswer)
< (SELECT "Content".date FROM "Content"
WHERE "Content".id = NEW.idQuestion)
THEN
RAISE NOTICE 'This Answer is an invalid date';
END IF;
RETURN NEW;
END;$$;
So, my question is: do I really need to create a trigger for this? I saw that I can't use a CHECK in Answer because I need to compare with an attribute of another table. Is there any other (easier/better) way to do this? If not, why the error and how can I solve it?
Your basic approach is sound. The trigger is a valid solution. It should work except for 3 problems:
1) Your naming convention:
We would need to see your exact table definition to be sure, but the evidence is there. The error message says: has no field "idanswer" - lower case. Doesn't say "idAnswer" - CaMeL case. If you create CaMeL case identifiers in Postgres, you are bound to double-quote them everywhere for the rest of their life.
Are PostgreSQL column names case-sensitive?
2) Abort violating insert
Either raise an EXCEPTION instead of a friendly NOTICE to actually abort the whole transaction.
Or RETURN NULL instead of RETURN NEW to just abort the inserted row silently without raising an exception and without rolling anything back.
I would do the first. This will probably fix the error at hand and work:
CREATE FUNCTION trg_answer_insbef_check()
RETURNS trigger AS
$func$
BEGIN
IF (SELECT c.date FROM "Content" c WHERE c.id = NEW."idAnswer")
< (SELECT c.date FROM "Content" c WHERE c.id = NEW."idQuestion") THEN
RAISE EXCEPTION 'This Answer is an invalid date';
END IF;
RETURN NEW;
END
$func$ LANGUAGE plpgsql;
The proper solution is to use legal, lower case names exclusively and avoid such problems altogether. That includes your unfortunate table names as well as the column name date, which is a reserved word in standard SQL and should not be used as identifier - even if Postgres allows it.
3) Should be a BEFORE trigger
CREATE TRIGGER insbef_check
BEFORE INSERT ON "Answer"
FOR EACH ROW EXECUTE PROCEDURE trg_answer_insbef_check();
You want to abort invalid inserts before you do anything else.
Of course you will have to make sure that the timestamps table Content cannot be changed or you need more triggers to make sure your conditions are met.
The same goes for the fk columns in Answer.
I would approach this in a different way.
Recommendation:
use a BEFORE INSERT trigger if you want to change data before
inserting it
use a AFTER INSERT trigger if you have to do additional
work
use a CHECK clause if you have additional data consistency requirements.
So write a sql function that checks the condition that one date be earlier than the other, and add the check constraint. Yes, you can select from other tables in your function.
I wrote something similar (complex check) in answer to this question on SO.

Disable Trigger for a particular DELETE Query

I have a ruby app. The app is doing the insert,update and delete on a particular table.
It does 2 kinds of INSERT, one insert should insert a record in the table and also into trigger_logs table. Another insert is just to insert the record into the table and do nothing. Another way to put it is, one kind of insert should log that the 'insert' happened into another table and another kind of insert should just be a normal insert. Similarly, there are 2 kinds of UPDATE and DELETE also.
I have achieved the 2 types of INSERT and UPDATE using a trigger_disable. Please refer to the trigger code below.
So, when I do a INSERT, I will set the trigger_disable boolean to true if I don't want to log the trigger. Similarly I am doing for an UPDATE too.
But I am not able to differentiate between the 2 kinds of DELETE as I do for an INSERT or UPDATE. The DELETE action is logged for both kinds of DELETE.
NOTE: I am logging all the changes that are made under a certain condition, which will be determined by the ruby app. If the condition is not satisfied, I just need to do a normal INSERT, UPDATE or DELETE accordingly.
CREATE OR REPLACE FUNCTION notify_#{#table_name}()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
changed_row_id varchar(100);
BEGIN
IF TG_OP = 'DELETE' THEN
-- When the trigger is due to a delete
IF (OLD.trigger_disable IS NULL)
OR (OLD.trigger_disable = false) THEN
-- Prevent the trigger if trigger_disable is 'true'
-- The Problem is here: This insertion into the
-- trigger_logs table happens
-- for all the delete statements.
-- But during certain deletes I should not
-- insert into trigger_logs
INSERT INTO trigger_logs (table_name, action, row_id, dirty)
VALUES (
'#{#table_name}',
CAST(TG_OP AS Text),
OLD.id,
true
) RETURNING id into changed_row_id;
END IF;
RETURN OLD;
ELSE
-- The trigger is due to a Insert or Update
IF (NEW.trigger_disable IS NULL)
OR (NEW.trigger_disable = false) THEN
-- Prevent the trigger if trigger_disable is 'true'
INSERT INTO trigger_logs (table_name, action, row_id, dirty)
VALUES (
'#{#table_name}',
CAST(TG_OP AS Text),
NEW.id,
true
) RETURNING id into changed_row_id;
ELSE
NEW.trigger_disable := false;
END IF;
RETURN NEW;
END IF;
END
I'm going to take a stab in the dark here and guess that you're trying to contextually control whether triggers get fired.
If so, perhaps you can use a session variable?
BEGIN;
SET LOCAL myapp.fire_trigger = 'false';
DELETE FROM ...;
COMMIT;
and in your trigger, test it:
IF current_setting('myapp.fire_trigger') = 'true' THEN
Note, however, that if the setting is missing from a session you won't get NULL, you'll get an error:
regress=> SELECT current_setting('myapp.xx');
ERROR: unrecognized configuration parameter "myapp.xx"
so you'll want to:
ALTER DATABASE mydb SET myapp.fire_trigger = 'true';
Also note that the parameter is text not boolean.
Finally, there's no security on session variables. So it's not useful for security audit, since anybody can come along and just SET myapp.fire_trigger = 'false'.
(If this doesn't meet your needs, you might want to re-think whether you should be doing this with triggers at all, rather than at the application level).

Mutating table exception when selecting max(date column of TABLE_X) in an after update trigger for TABLE_X

I have a trigger somewhat like this (Sorry can't display actual sql because of company rules and this is from a different machine):
create or replace trigger TR_TABLE_X_AU
after update
on TABLE_X
for each row
declare
cursor cursor_select_fk is
select FK_FOR_ANOTHER_TABLE
from TABLE_Y Y, TABLE_Z Z
where :NEW.JOINING_COL = Y.JOINING_COL
and Y.JOINING_COL = Z.JOINING_COL
and :NEW.FILTER_CONDITION_1 = Y.FILTER_CONDITION_1
and :NEW.FILTER_CONDITION_2 = Y.FILTER_CONDITION_2
and :NEW.SOME_DATE_COL = (select max(SOME_DATE_COL)
from TABLE_X
where FILTER_CONDITION_1 = :NEW.FILTER_CONDITION_1
and FILTER_CONDITION_2 = :NEW.FILTER_CONDITION_2)
begin
for rec in cursor_select_fk loop
PCK_SOME_PACKAGE.SOME_PROC(rec.FK_FOR_ANOTHER_TABLE);
end loop;
end TR_TABLE_X_AU;
We resulted to triggers since it is an enhancement. The nested query selecting the max date seems to be the cause of the problem. Changing it to sysdate results to no exceptions. Any idea on how I can get the max date during the execution of the trigger for TABLE_X? Thanks!
EDIT:
Also, it seems similar functions such as count,sum,etc... produces the same error. Anyone knows a workaround to this?
A mutating table is a table that is being modified by an UPDATE,
DELETE, or INSERT statement, or a table that might be updated by the
effects of a DELETE CASCADE constraint.
The session that issued the triggering statement cannot query or
modify a mutating table. This restriction prevents a trigger from
seeing an inconsistent set of data.
Trigger Restrictions on Mutating Tables
Which means, you cannot issue max(some_date_col) on your TABLE_X in a row-level trigger.
Compound trigger could be a possible workaround.