Skip to content Skip to sidebar Skip to footer

Elegant Way Of Handling Postgresql Exceptions?

In PostgreSQL, I would like to create a safe-wrapping mechanism which returns empty result if an exception occurs. Consider the following: SELECT * FROM myschema.mytable; I could

Solution 1:

Exception handling in PL/pgSQL

Generally, plpgsql code is always wrapped into a BEGIN .. END block. That can be inside the body of a DO statement or a function. Blocks can be nested inside - but they cannot exist outside, don't confuse this with plain SQL.

Each BEGIN block can optionally include an EXCEPTION clause for handling exceptions, but functions that need to trap exceptions are considerably more expensive, so it's best to avoid exceptions a priori.

More information:

How to avoid an exception in the example

A DO statement can't return anything. Create a function that takes table and schema name as parameters and returns whatever you want:

CREATEOR REPLACE FUNCTION f_tbl_value(_tbl text, _schema text ='public')
  RETURNSTABLE (value text)
  LANGUAGE plpgsql AS
$func$
DECLARE
   _t regclass := to_regclass(_schema ||'.'|| _tbl);
BEGIN
   IF _t ISNULLTHENvalue :=''; RETURN NEXT;    -- return single empty stringELSERETURN QUERY EXECUTE'SELECT value FROM '|| _t;  -- return set of valuesEND IF;
END
$func$;

Call:

SELECT*FROM f_tbl_value('my_table');

Or:

SELECT*FROM f_tbl_value('my_table', 'my_schema');

Assuming you want a set of rows with a single text column or an empty string if the table does not exist.

Also assuming that a column value exists if the given table exists. You could test for that, too, but you didn't ask for that.

Both input parameters are only case sensitive if double-quoted. Just like identifiers are handled in SQL statements.

The schema name defaults to 'public' in my example. Adapt to your needs. You could even ignore the schema completely and default to the current search_path.

to_regclass() is new in Postgres 9.4. For older versions substitute:

IF EXISTS (
   SELECTFROM information_schema.tables 
   WHERE  table_schema = _schema
   AND    table_name = _tbl
);

This is actually more accurate, because it tests exactly what you need. More options and detailed explanation:

Always defend against SQL injection when working with dynamic SQL! The cast to regclass does the trick here. More details:

Solution 2:

If you are selecting only one column then the COALESCE() function should be able to do the trick for you

SELECTCOALESCE( value, '{}'::text[] ) FROM myschema.mytable

If you require more rows you may require to create a function with types.

Post a Comment for "Elegant Way Of Handling Postgresql Exceptions?"