Search code examples
oracle-databaseplsqloracle11gtriggersoracle-objects

RTTI in Oracle Triggers


I have this dummy types :

create or replace type Service_TY as object(
  code INTEGER,
  visit_analysis char(1)
)FINAL;
/
create or replace type Employee_TY as object(
   dummy varchar(30)
)NOT FINAL;
/

create or replace type Doctor_TY UNDER Employee_TY(
  ID INTEGER
)FINAL;
/

create or replace type Assistant_TY UNDER Employee_TY(
  ID INTEGER
)FINAL;
/

create or replace type Habilitation_TY as object(
  employee ref Employee_TY,
  service ref Service_TY
)FINAL;
/

And these dummy tables:

CREATE TABLE Service of Service_TY(
  code primary key,
  visit_analysis not null check (visit_analysis in ('v', 'a'))
);
/

CREATE TABLE Doctor of Doctor_TY(
  ID primary key
);
/

CREATE TABLE Assistant of Assistant_TY(
  ID primary key
);
/

CREATE TABLE Habilitation of Habilitation_TY;
/

I want to create a trigger that, when a new tuple is inserted in Habilitation, should check that, if the employee is an assistant (and not a doctor), the visit_analysis attribute is equal to 'a' to know if it is a legal tuple.

I don't know how to check the type of the Employee (if it is a doctor or an assistant).

I would do something like that:

create or replace
TRIGGER CHECK_HABILITATION
BEFORE INSERT ON HABILITATION
FOR EACH ROW
DECLARE
BEGIN
    IF (:NEW.EMPLOYEE is of ASSISTANT_TY)
    THEN
      IF :NEW.SERVICE.visit_analysis = 'v'
         THEN
             raise_application_error(-10000, 'invalid tuple');
    END IF;
END;

But it's not working. How should I check that type? The error I get is: Error(14,4): PLS-00103: Encountered the symbol ";" when expecting one of the following: if


Solution

  • Try to put it into a variable, the following one should work.

    create or replace
    TRIGGER CHECK_HABILITATION
    BEFORE INSERT ON HABILITATION
    FOR EACH ROW
    DECLARE
      emp employee_TY;
      ser service_TY;
    BEGIN
      select deref(:new.employee) into emp from dual;
      if (emp is of (assistant_ty)) then
        select deref(:new.service) into ser from dual;
        if ser.visit_analysis = 'v' then
          raise_application_error('-20001', 'invalid tuple');
        end if;
      end if;
    END;
    /