I'm having issues with the exception handling of postgresql, and I'm looking for some tips/advice how to tackle this. Say I want to do the following:
SELECT col1 / col2
FROM table
The first problem that arises is that if at some point a value in col2 = 0, the query throws an exception. A solution to this is to add a NULLIF() in the denominator.
In our case, users can make their own formulas, which have to be parsed by the database, so we do not have the knowledge about the division in advance. We could make a fancy formula parser that adds NULLIF() in the right places, but then don't get me started on taking square root of negative numbers..
So I'm wondering if there is a better solution to the problem. Does something like this exist?
SELECT col1 / col2
exception
return null
FROM table
Or do I need to make use of the 'function' feature of postgresql? Is it possible to combine two columns like this?
CREATE OR REPLACE FUNCTION somefunction(col1, col2) RETURNS real AS $$
BEGIN
RETURN col1 / col2;
exception when division_by_zero then
return null;
END;
$$ LANGUAGE plpgsql;
SELECT somefunction(col1, col2, ..)
FROM table;
So keep in mind that we do not know the formula in advance! Thanks!
nullif()calls themselves. Surely you already set up all the relevant safeguards to limit sql injections? Catching exceptions in there should be easy. If no, then yeah you definitely should use a fancy formula parser!