Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one report the line on which an error occured in Postgres/plpgsql?

I have been using something more or less like this in postgres to emulate how, in SQL Server, I have used Try/Catch blocks with transactions that can be rolled back in the Catch if an error is found:

do $$
begin
[SQL here]

exception when others then
    raise notice 'Error in insert statement ---> % %', SQLERRM, SQLSTATE LINE;
end;    

$$ language 'plpgsql';

Is there a way to report the line where the error occurred, like "ERROR_LINE()?

Thanks in advance

like image 446
Sanjay Advani Avatar asked Jun 03 '15 22:06

Sanjay Advani


People also ask

How do I comment a line in PostgreSQL?

Syntax Using /* and */ symbols In PostgreSQL, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.

When you are raising statement in PostgreSQL What kind of messages can be reported back to the client?

PostgreSQL only reports the info , warning , and notice level messages back to the client.

What is error handling in PostgreSQL?

First, when an error occurs between the begin and exception , PL/pgSQL stops the execution and passes the control to the exception list. Second, PL/pgSQL searches for the first condition that matches the occurring error. Third, if there is a match, the corresponding handle_exception statements will execute.

How do you handle user defined exceptions in PostgreSQL?

if it is an user defined exception, delete the corresponding declaration and specify unique error code via ERRCODE in a USING clause. in catch-block replace SQLCODE by SQLSTATE.


1 Answers

On some modern PostgreSQL, you can use GET STACKED DIAGNOSTICS statement. There is not possibility to get linenumber, but you can get a call context, where lineno is included:

postgres=> DO $$
DECLARE 
  a int DEFAULT 0;
  _c text;
BEGIN
  BEGIN
    PERFORM 10/a;
  EXCEPTION WHEN OTHERS THEN
    GET STACKED DIAGNOSTICS _c = PG_EXCEPTION_CONTEXT;
    RAISE NOTICE 'context: >>%<<', _c;
  END;
END;
$$;
NOTICE:  00000: context: >>SQL statement "SELECT 10/a"
PL/pgSQL function inline_code_block line 7 at PERFORM<<
LOCATION:  exec_stmt_raise, pl_exec.c:3041
DO
like image 145
Pavel Stehule Avatar answered Sep 24 '22 13:09

Pavel Stehule