Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching a constraint violation in psql

Tags:

plsql

I am using sql developer, and have added a constraint to one of my tables.

constraint valid_gender check(gender in ('M','F','I','T'))

When I try to add an entry with say 'x' for gender using a plsql procedure, it fails with constraint violation (as it should).

I want to add a "Catch" to the plsql procedure so that if valid_gender is voilated I can raise_application_error specific to it. Is this possible?

like image 493
luke Avatar asked Aug 28 '11 12:08

luke


People also ask

How do I view constraints in PostgreSQL?

Constraints of the table can be retrieved from catalog-pg-constraint. using the SELECT query. Just a detail: If you don't have tables with the same name in multiple schemas, in PSQL just \d+ {TABLE_NAME} works too.

How do I find unique constraints in PostgreSQL?

To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.

What is a constraint violation?

A problem that indicates a syntactically correct, yet semantically illegal request. It's not meant to be used for end-user input validation, but for client developer convenience. Any constraint violation problem happening in production should be considered a bug.

What is constraint in PSQL?

Constraints are the rules enforced on data columns on table. These are used to prevent invalid data from being entered into the database. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level.


1 Answers

Oracle will raise an exception that says:

ORA-02290: check constraint (yourschema.valid_gender) violated

You can catch that in an exception handler and raise your own exception instead using raise_application_error in a couple of ways.

1) You can specifically trap the ORA-02290 exception like this:

declare
  e_check_violated exception
  pragma exception_init (e_check_violated, -2290);
begin
  insert ...
exception
  when e_check_violated then
    if sqlerrm like '%(yourschema.valid_gender)%' then
       raise_application_error(-20001,'Invalid gender');
    else
      raise;
    end if;
end;

2) You can trap all exceptions and inspect them:

begin
  insert ...
exception
  when others then
    if sqlerrm like 'ORA-02290:%(yourschema.valid_gender)%' then
       raise_application_error(-20001,'Invalid gender');
    else
      raise;
    end if;
end;

In a large application it is quite common to have an exception handling procedure to generalise this and look up the constraint-specific message in a table.

like image 101
Tony Andrews Avatar answered Oct 08 '22 13:10

Tony Andrews