Skip site navigation (1) Skip section navigation (2)

using functions to generate custom error messages

From: Joel Rodrigues <skyfyre(at)Phreaker(dot)net>
To: pgsql-novice(at)postgresql(dot)org
Subject: using functions to generate custom error messages
Date: 2002-11-13 18:04:41
Message-ID: 9EEC31DE-F739-11D6-8BB2-0005024EF27F@Phreaker.net (view raw or flat)
Thread:
Lists: pgsql-novice
[I just sent this using the wrong e-mail address, so assuming it 
won't show up, here it comes again...]

Hello,

Would it be considered good practice to use functions to 
generate custom error messages ?

The only odd thing about it I can see is that constraints have 
to be coded into the function, whether or not they've already 
been included in the table itself.

Here's an example.

CREATE TABLE amelie (
    rating    int CHECK (rating <= 10)
);


The results of using just this :

hypatia=# INSERT INTO amelie VALUES ('11');
ERROR:  ExecAppend: rejected due to CHECK constraint amelie_rating


Here is the function with the constraint included again (phrased 
differently):

CREATE FUNCTION maxten () RETURNS OPAQUE AS '
     BEGIN
         IF NEW.rating > 10 THEN
             RAISE EXCEPTION ''Alert ! Please enter a number 
between 0 and 10.'';
         END IF;

         RETURN NEW;
     END;
' LANGUAGE 'plpgsql';


And the trigger:

CREATE TRIGGER trigtest BEFORE INSERT OR UPDATE
     ON amelie
     FOR EACH ROW
     EXECUTE PROCEDURE maxten();


The results of this:

hypatia=# INSERT INTO amelie VALUES ('11');
ERROR:  Alert ! Please enter a number between 0 and 10.

My goal with this is to stick with the principle of keeping 
"business logic" in the DBMS, avoiding elaborate error checking 
and other unnecessary verbosity in my Python CGI scripts. I can 
easily insert the function generated ERROR message into an xhtml 
template and display it in the web browser.

I do understand that there are other ways/places to do error 
checking, in the CGI script or in JavaScript, but this is 
how/where I'd like to do it.

BTW, does anyone know why \df doesn't find the function "maxten" 
that I created ?


hypatia=# \df maxten

                List of functions
  Result data type | Name | Argument data types
------------------+------+---------------------
(0 rows)


Cheers,
Joel



Responses

pgsql-novice by date

Next:From: Joel RodriguesDate: 2002-11-13 18:05:40
Subject: Re: Display a function
Previous:From: Varun KacholiaDate: 2002-11-13 17:54:17
Subject: Re: Help with JDBC connection...

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group