Commit the transaction after exception is raised - postgresql

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.

Related

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.)

Ignore an error that occurs in a redshift stored procedure

I need to ignore an error when running a procedure, but the error still seems to propagate. Is it possible to just swallow it somehow?
CREATE OR REPLACE PROCEDURE myproc()
AS $$
BEGIN
EXECUTE 'bad_statement;';
EXCEPTION WHEN OTHERS THEN
NULL;
END;
$$ LANGUAGE plpgsql;
Then
call myproc();
will result in:
[2021-01-06 17:08:42] [42601][500310] Amazon Invalid operation: syntax error at or near "bad_statement";
Tested it in postgres and it ignores the error correctly.
Unfortunately I don't think there is a way to do this. Amazon's documentation states
In an Amazon Redshift stored procedure, the only supported handler_statement is RAISE. Any error encountered during the execution automatically ends the entire stored procedure call and rolls back the transaction. This occurs because subtransactions are not supported.
If an error occurs in the exception handling block, it is propagated out and can be caught by an outer exception handling block, if one exists.
stored-procedure-trapping-errors

EXCEPTION WHEN OTHERS THEN NULL in Postgres

I have an exception in Oracle PL/SQL that needs to be ported to PostgreSQL pl/pgsql. Below is the oracle variant
EXCEPTION
WHEN OTHERS THEN
NULL;
What is the PL/PGSQL variant?
It's the same syntax. Compare the 2 following executions:
DO
$$
BEGIN
RAISE division_by_zero;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
$$
DO
And:
DO
$$
BEGIN
RAISE division_by_zero;
END;
$$
ERROR: division_by_zero
CONTEXT: PL/pgSQL function inline_code_block line 3 at RAISE
DO NOT port this as it is. It is a BUG ALWAYS. If you do nothing else at least log the error. If where it occurs is interactive, or data loading, or report generating, or a whole host of others then create some kind of message indicating the process failed. If users are depending on this data and it is not there it is your application that is broken, not the users expectations. I understand your are migrating a system but while doing so you should not carry forward obvious bugs. This is one.
First, avoid trapping "any exception"s like that with no specific behavior at all. Except for very simple functions, consider logging it somewhere, or rewrite the code in a more elegant manner.
I found it here: apparently, you don't need to put anything at all.
You should try the following:
EXCEPTION
WHEN OTHERS THEN
-- Do nothing
Hope it helps.

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;

trigger to silently preempt insertion in a table

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.