trigger to silently preempt insertion in a table - postgresql

Is it possible for a trigger to be defined in such a way that the row that was to be inserted is not inserted, without raising an exception? My use case is that I want to simplify the exception handling for the client library: the client library will just execute a statement to insert a row in a table and I was hoping that the trigger could be defined, more or less using the below syntax:
CREATE TRIGGER control_tr AFTER INSERT ON tableFoo
FOR EACH ROW
EXECUTE PROCEDURE control_tr_fun();
CREATE OR REPLACE FUNCTION control_tr_fun() RETURNS TRIGGER AS $$
BEGIN
IF (NOT condition_is_met(NEW.a, NEW.b, NEW.c)) THEN
DO NOTHING INSTEAD OF INSERT // syntax I am hoping for instead of RAISE EXCEPTION
ELSE
RETURN NEW;
END IF;
END
$$ LANGUAGE plpgsql;
I appreciate that I can ask the client library to call a PL/pgSQL function or make a trigger that RAISEs an exception and ask the client library to catch the exception (if raised) and just ignore it, but I am looking for a way to implement this as transparently for the client as possible.

If you RETURN NULL then nothing will happen, the INSERT will fail silently. But you need to define the trigger as BEFORE INSERT, and not AFTER INSERT as it is in your example.
If you RAISE EXCEPTION, then the entire transaction will fail.
You can also RAISE NOTICE without failing the transaction and catch it in the client library, but only if it was the last notice produced. You cannot stack notices.

Related

PL/pgSQL procedures and transaction control

I'm new to Postgres, but with experience from Oracle. Trying to create a stored procedure which is going to:
Insert a row
Handle exceptions and in case of an exception insert a row into a log table by calling dedicated procedure
Emit an audit log record into a log table in case the whole procedure ran successfully
By pseudo code:
CREATE OR REPLACE PROCEDURE test.p_insert(IN p_test_param character varying)
LANGUAGE 'plpgsql'
SECURITY DEFINER
AS $BODY$
DECLARE
-- some declarations
BEGIN
BEGIN
INSERT INTO test.a(a) VALUES (p_test_param);
EXCEPTION
WHEN OTHERS THEN
-- GET STACKED DIAGNOSTICS
CALL test.p_insert_log(...); -- Inserts a row into a log table, another COMMIT may be required?
RAISE;
END;
COMMIT; -- CAN'T DO
BEGIN
IF (SELECT test.f_debug()) THEN
CALL test.p_insert_log(...); -- Audit the execution
END IF;
END;
COMMIT; -- CAN'T DO EITHER
END;
$$BODY$$;
However when I try to test the procedure out from an anonymous block in PgAdmin such as:
BEGIN;
DO
LANGUAGE plpgsql
$$
BEGIN
CALL test.p_insert(
p_test_param => 'test'
);
END;
$$
I'm getting an error ERROR: invalid transaction termination. How can I get rid of it? My objective is to let the procedure carry out the transaction control, I don't want the caller to COMMIT or ROLLBACK anything. If I remove both COMMIT commands from the code of the procedure, it executes well, however the invoker must explicitly COMMIT or REVOKE the transaction afterwards, which is not desired. In Oracle the pseudo code with COMMIT statements would work, in Postgres it doesn't seem to work as I would like to. Could you please help me out? Thanks
Your code will work as intended. Perhaps you made some mistake in calling the code:
you cannot call the procedure from a function
you cannot call the procedure in an explicitly started transaction:
BEGIN;
CALL p_insert('something); -- will fail
COMMIT;

Postgres Exception handling in stored procedure to continue the process

Database is postgressql.
I want to call five stored procedure in on stored procedure that is master_call_all() and need to handle exception after every call. So if any error occur it raise the exception and not terminate the process.
Let say error occur in 3rd call scratch.sp_insert3() then after raising error next stored procedure will call. This thing I want to achieve after every call.
create or replace procedure scratch.master_call_all()
LANGUAGE plpgsql
AS $$
DECLARE
BEGIN
call scratch.sp_insert1();
call scratch.sp_insert2();
call scratch.sp_insert3();
call scratch.sp_insert4();
call scratch.sp_insert5();
commit;
END;
$$;
First off: In general this is an extremely bad plan. It is the anti-thesis of creating a Transaction (begin ... end).
Transactions are a fundamental concept of all database systems. The essential point of a transaction is that it bundles multiple steps
into a single, all-or-nothing operation. The intermediate states
between the steps are not visible to other concurrent transactions,
and if some failure occurs that prevents the transaction from
completing, then none of the steps affect the database at all.
Ref: Database Transactions
Now with that out of the way, what you are asking can be done, but it is not done cleanly. A code block in Postgres contains 3 sections declaration, execution, exception with declaration and exception optional. Further a block can be nested inside another and the nested block retains all 3 sections. So what you need is to place each ca;; statement into a nested block. Like:
create or replace procedure master_call_all()
language plpgsql
as $$
declare
begin
begin
call sp_insert1();
exception
when others then
raise notice 'Exception occurred calling sp_insert1()';
end ;
begin
call sp_insert2();
exception
when others then
raise notice 'Exception occurred calling sp_insert2()';
end ;
begin
call sp_insert3();
exception
when others then
raise notice 'Exception occurred calling sp_insert3()';
end ;
begin
call sp_insert4();
exception
when others then
raise notice 'Exception occured calling sp_insert4()';
end ;
begin
call sp_insert5();
exception
when others then
raise notice 'Exception occured calling sp_insert5()';
end ;
commit;
end;
$$;
See demo here. Unfortunately db<>fiddle does not show the messages from raise notice .... Clearly in the demo sp_insert1, and sp_insert3 will raise an exception. (To see the messages run in your environment.)

Persisting some changes before raising an exception in PL/pgSQL function

I'm trying to write a PL/pgSQL function in which I first validate parameters (mostly check whether the supplied ids exist).
When one of this validations fails, I raise an exception stating the reason so the client code can try again.
The problem I'm facing is that, for safety reasons (I can provide more context if needed, but basically I want to leave the app in a non-functional state until specialized intervention), I'd like to write some values to a table before raising the exception and rolling back the changes. It's only some of these changes that I'd like persisted (not rolled back).
I understand transactions cannot be used inside the function because there's no context, and I found that I could probably do what I want to do using dblink (which I just found out).
The thing is it really feels hackish, so I'd like to ask if this is a reasonable idea or not.
Here's some pseudocode to illustrate:
CREATE FUNCTION func(x_id INT) RETURNS INT AS $$
DECLARE
BEGIN
PERFORM * FROM x_table WHERE id = x_id;
IF NOT FOUND THEN
-- write persisting values that will prevent further
-- use, probably using dblink
RAISE EXCEPTION 'Invalid x_id: %', x_id
END IF;
-- function logic
END;
$$ LANGUAGE plpgsql;

Hot to use results from procedure calls as conditions

I have a procedure that checks for a condition (if a session is fully booked). I want to make a trigger that checks if the session is fully booked before inserting a new booking.
What I imagine it would be like is something like this.
CREATE OR REPLACE FUNCTION check_if_session_is_full_trigger()
RETURNS trigger AS
$BODY$
BEGIN
IF (EXECUTE session_is_full(NEW.session_id)) THEN
RAISE EXCEPTION 'SESSION IS FULLY BOOKED';
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
But I get this
ERROR: syntax error at or near "session_is_full"
LINE 5: IF (EXECUTE session_is_full(NEW.session_id) = TRUE) THE...
So obviously I'm not doing something right.
session_is_full(int) returns boolean.
Am I on the right track, and how to fix this?
IF (session_is_full(NEW.session_id)) should work – #a_horse_with_no_name

Commit the transaction after exception is raised

I tried looking up for the solution but failed to find one. I understand that postgres rollbacks all the transactions once an exception is raised. But my requirement is to log a certain exception into a database table.
Following is a sample code:
CREATE OR REPLACE FUNCTION fn_test(
in_var numeric DEFAULT NULL::numeric)
RETURNS numeric AS
$BODY$
DECLARE
BEGIN
IF in_var=0
THEN
RAISE EXCEPTION using errcode='INELG';
ELSE IF in_var=1
THEN
RAISE EXCEPTION using errcode='INVAL';
ELSE
RETURN in_var;
END IF;
begin
EXCEPTION
WHEN sqlstate 'INELG'
THEN
INSERT INTO LOG_TBL(in_par,error_reason)
VALUES(in_var,'VALUE INELGIBLE');
RAISE EXCEPTION 'Unable to Process: Parameter Not Eligible';
WHEN sqlstate 'INVAL'
THEN
INSERT INTO LOG_TBL(in_par,error_reason)
VALUES(in_var,'VALUE INValid');
RAISE EXCEPTION 'Unable to Process: Parameter Invalid';
end;
END;
$BODY$
LANGUAGE plpgsql VOLATILE SECURITY DEFINER
COST 100;
The problem I face is as soon as an exception is raised the records in LOG_TBL in the exception section gets rolled back. Is there an alternative solution where I can insert the record into database table as well as raise an application error?
In a simple way - you can't. Once you are inside a function, that's it.
You either have to do this in the client layer or loop back in on another connection to log the error. Traditionally you would loop back in via dblink, but it might be possible to use Foreign Data Wrappers too - I have to admit I'm not sure.
Edit: Nope, it looks like postgres_fdw syncs the transactions between local and remote. Not helpful in this case. Looks like dblink is the obvious choice.