(ref) Trigger on Object Table

You can create triggers on object tables. In this case, the trigger can reference the pseudocolumn OBJECT_VALUE.
In the example below you:

(1) Create an OBJECT_TYPE to define a table.
(2) Create an OBJECT TABLE obj_employee
(3) Insert data on obj_employee
(4) Create a table emp_hist for logging updates to obj_employee
(5) Create a trigger emp_obj_trg.
  • The trigger will execute for each row of obj_employee affected by a DML statement.
  • The old and new values of the object emp in obj_employee will be written in emp_history.
  • The old and new values are :OLD.OBJECT_VALUE and :NEW.OBJECT_VALUE


(1-3) Create OBJECT_TYPE, OBJECT TABLE and Insert data.

SQL> CREATE or REPLACE TYPE EmployeeType AS OBJECT (
  Id             number,
  first_name     varchar2(15),
  last_name      varchar2(15),
  hire_date      date,
  salary         number(8,2)
  );

Type created.
SQL> CREATE TABLE obj_employee OF EmployeeType;

Table created.
SQL> INSERT INTO obj_employee VALUES (
    EmployeeType(1, 'John', 'Martic', '02-AUG-03', 95000))
1 row created.

SQL> INSERT INTO obj_employee VALUES (
    EmployeeType(2, 'Mary', 'Kempft', '02-JUL-99', 98000)))
1 row created.

SQL> INSERT INTO obj_employee VALUES (
    EmployeeType(3, 'Greg', 'Bloom', '02-AUG-09', 55000))
1 row created.

SQL> commit;
Commit complete.

SQL> select * from obj_employee;

    ID FIRST_NAME      LAST_NAME       HIRE_DATE    SALARY
------ --------------- --------------- ------------ ----------
     1 John            Martic          02-AUG-03         95000
     2 Mary            Kempft          02-JUL-99         98000
     3 Greg            Bloom           02-AUG-09         55000



(4) Create history table emp_hist:
SQL> CREATE TABLE emp_hist 
  (dt          date,
   username    varchar2(20),
   old_obj_emp EmployeeType,
   new_obj_emp EmployeeType);

table created.
SQL>

Compare emp_hist and obj_employee:

  • obj_employee is an object table. Each of its rows is an object of the type EmployeeType
  • emp_hist is a traditional table. Two of its columns are objects of the type EmployeeType
(?) How is the translation/mapping OO-Relational done?
SQL> desc obj_employee
 Name               Null?  Type
 ------------------ ------ ------------------
 ID                         NUMBER
 FIRST_NAME                 VARCHAR2(15)
 LAST_NAME                  VARCHAR2(15)
 HIRE_DATE                  DATE
 SALARY                     NUMBER(8,2)

SQL> desc emp_hist
 Name               Null?  Type
 ------------------ ------ ------------------
 DT                        DATE
 USERNAME                  VARCHAR2(20)
 OLD_OBJ_EMP               EMPLOYEETYPE
 NEW_OBJ_EMP               EMPLOYEETYPE


(5) Create a trigger emp_obj_trg.
  • The trigger will execute for each row of obj_employee affected by a DML statement.
  • The old and new values of the object emp in obj_employee will be written in emp_history.
  • The old and new values are :OLD.OBJECT_VALUE and :NEW.OBJECT_VALUE

SQL> CREATE OR REPLACE TRIGGER emp_obj_trg
 AFTER UPDATE on obj_employee
 FOR EACH ROW
BEGIN
 DBMS_OUTPUT.PUT_LINE('Logging Update');
 INSERT INTO emp_hist (dt, username, old_obj_emp, new_obj_emp)
 VALUES (sysdate, user, :OLD.OBJECT_VALUE, :NEW.OBJECT_VALUE);
END emp_obj_trg;

Trigger created.
SQL> 

SQL> set serveroutput on 
SQL> update obj_employee set salary=salary*1.10 where id=1;
Logging Update

1 row updated.

SQL> update obj_employee set salary=salary*.98;
Logging Update
Logging Update
Logging Update

3 rows updated.


(6) Check the audit table (using implicit cursor):

SQL> set serveroutput on
SQL> BEGIN
 for j in (select * from emp_hist) loop
  dbms_output.put_line (
   'Date: ' || j.dt ||'-- User '|| j.username);
   DBMS_OUTPUT.PUT_LINE(
   '(old rec)-- ID:'|| j.old_obj_emp.id || '-- OLD SALARY: '|| j.old_obj_emp.salary);
  DBMS_OUTPUT.PUT_LINE(
   '(new rec)-- ID:'|| j.new_obj_emp.id || '-- NEW SALARY: '|| j.new_obj_emp.salary);
 end loop;
end;
/

Date: 22-AUG-11-- User FHAT
(old rec)-- ID:1-- OLD SALARY: 95000
(new rec)-- ID:1-- NEW SALARY: 104500
Date: 22-AUG-11-- User FHAT
(old rec)-- ID:1-- OLD SALARY: 104500
(new rec)-- ID:1-- NEW SALARY: 102410
Date: 22-AUG-11-- User FHAT
(old rec)-- ID:2-- OLD SALARY: 98000
(new rec)-- ID:2-- NEW SALARY: 96040
Date: 22-AUG-11-- User FHAT
(old rec)-- ID:3-- OLD SALARY: 55000
(new rec)-- ID:3-- NEW SALARY: 53900

PL/SQL procedure successfully completed.
SQL>








(17) On Triggers



Introduction
  • Named PL/SQL unit. Can be enabled or disabled, but cannot be explicitly invoked.
  • Trigger is created on or defined on the item (to which it will be "attached"): table, view, schema or database.
  • Firing criteria is based on a triggering event (DML, DDL, System) and on a timing specification (before, after, instead of). A conditional clause (WHEN) may also be used to further specify the triggering rules.
  • Triggers do not accept arguments.
  • Triggers can be written in PL/SQL or JAVA.
  • Starting on Oracle 11g, triggers can now be created in the disabled state.

Triggers: what for?
Customization of database management; centralization of some business or validation rules; logging and audit.
  • Overcome the mutating-table error.
  • Maintain referential integrity between parent and child.
  • Generate calculated column values
  • Log events (connections, user actions, table updates, etc)
  • Gather statistics on table access
  • Modify table data when DML statements are issued against views
  • Enforce referential integrity when child and parent tables are on different nodes of a distributed database
  • Publish information about database events, user events, and SQL statements to subscribing applications
  • Enforce complex security authorizations: (i.e. prevent DML operations on a table after regular business hours)
  • Prevent invalid transactions
  • Enforce complex business or referential integrity rules that you cannot define with constraints
  • Control the behavior of DDL statements, as by altering, creating, or renaming objects
  • when they change data in a view>
  • Audit information of system access and behavior by creating transparent logs
(but, however, nonetheless, take heed:),
  • if the trigger code turns out to be very(?) long, you will more likely have better performance using a stored procedure instead. In fact, a trigger cannot be larger than 32Kb (because stored on LONG column). If you need to write something longer, use a stored procedure instead.
  • You can’t control the sequence of or synchronize calls to triggers, and this can present problems if you rely too heavily on triggers
  • A trigger can call a SQL statement that in turn fires another trigger: The number of cascading triggers is limited to 32, after which an exception is thrown. (11g and earlier)

Triggers: How much is too much?
  • DML statements on tables with DML Triggers are likely to have decreased perform.
  • You may choose to disable triggers before loading data. Of course the cost to this is the work you'll have to perform latter what the disabled triggers did not do.
  • If the task is complex, you may spread it across multiple triggers. However, this will make it maintenance more difficult, since it is likely to make the entire process harder to follow later.
  • Triggers may get disabled by accident: For example, DDLs on objects touched by a trigger may render it unusable. If you don't catch this, you may end up with missing/corrupt data.


Five types of Triggers
DDL Triggers
  • On CREATE, ALTER, DROP
  • Useful to control or monitor DDL statements.
  • An instead-of create table trigger allow for:
    • Ensuring that table creation meets development standards (i.e. proper storage or partitioning clauses.
    • Monitor poor programming practices (i.e. programs create and drop temporary tables rather than use Oracle collections. Temporary tables can fragmentdisk space and degrade database performance over time.
DML Triggers
  • Statement-level or row-level
  • Audit, check, save, and replace values before they are changed.
  • Automatic numbering of numeric primary keys (through row-level trigger).
Compound Triggers
  • Act as statement- and row-level triggers.
  • Lets you capture information at four timing points:
    (a) before the firing statement;
    (b) before each row change from the firing statement;
    (c) after each row change from the firing statement; and
    (d) after the firing statement.
  • Audit, check, save, and replace values before they are changed when you need to take action at both the statement and row event levels.
Instead-of Triggers
  • Enable you to stop performance of a DML statement and redirect the DML statement.
  • Often used to manage how you write to non-updatable views: They apply business rules and directly insert,update, or delete rows in tables that define updatable views.
  • Alternatively, they insert, update, or delete rows in tables unrelated to the view.
System Database event Triggers
  • Fire when a system activity occurs in the database (i.e. logon and logoff).
  • Useful for auditing information of system access. (You can track system events and map them to users).


Constraints
  • Apply to OLD and NEW data.
  • Easier to write and less error-prone.
Triggers
  • Apply only to NEW data.
  • Can enforce complex business rules.
  • Enforce ref integrity on distributed databases.


Using DML triggers

Using Compound triggers (11g only)

Using triggers on object tables
You can create triggers on object tables. In this case, the trigger can reference the pseudocolumn OBJECT_VALUE. Check an example here.

Using INSTEAD OF triggers

INSTEAD OF triggers are created on views. This allow DML statements to be issued against non-updatable views. Check an example here.

Privileges required to use Triggers

- CREATE TRIGGER: For your own objects.
- CREATE ANY TRIGGER + ALTER ANY TABLE.
- EXECUTE:to fire triggers on other schemas

Trigger Design Guidelines
  • Do not create triggers that duplicate database features. For example, do not create a trigger to reject invalid data if you can do the same with constraints.
  • Do not create triggers that depend on the order in which a SQL statement processes rows (which can vary).

    For example, do not assign a value to a global package variable in a row trigger if the current value of the variable depends on the row being processed by the row trigger. If a trigger updates global package variables, initialize those variables in a BEFORE statement trigger.
  • If the triggering statement of a BEFORE statement trigger is an UPDATE or DELETE statement that conflicts with an UPDATE statement that is running, then the database does a transparent ROLLBACK to SAVEPOINT and restarts the triggering statement. The database can do this many times before the triggering statement completes successfully. Each time the database restarts the triggering statement, the trigger fires. The ROLLBACK to SAVEPOINT does not undo changes to package variables that the trigger references. To detect this situation, include a counter variable in the package.
  • Do not create recursive triggers. The trigger fires recursively until it runs out of memory.
  • If you create a trigger that includes a statement that accesses a remote database, then put the exception handler for that statement in a stored subprogram and invoke the subprogram from the trigger.
  • Use DATABASE triggers judiciously. They fire every time any database user initiates a triggering event.
  • Only committed triggers fire. A trigger is committed, implicitly, after the CREATE TRIGGER statement that creates it succeeds.

Trigger Restrictions
  • Maximum Trigger Size
    • Max 32Kb. If needed, you can move code into functions, procedures or packages. In this case, the code could also be reused. stored modules can also be wrapped.
    • If the logic for your trigger requires much more than 60 lines of PL/SQL source text, then put most of the source text in a stored subprogram and invoke the subprogram from the trigger
  • DCL and DDL Restrictions
    • Only an autonomous trigger can run TCL or DDL statements
    • Nonsystem trigger bodies can’t contain DDL statements. They also can’t contain Transaction Control Language (TCL) commands, like ROLLBACK, SAVEPOINT,or COMMIT.
    • A trigger cannot invoke a subprogram that runs transaction control statements, because the subprogram runs in the context of the trigger body.
    • If you declare a trigger as autonomous, nonsystem trigger bodies can contain Data Control Language commands because they don’t alter the transaction scope.
    • To enable a trigger to work outside the scope of a triggering statement you use include in its DECLARE block: PRAGMA AUTONOMOUS_TRANSACTION;
    • A larger problem with SQL statements exists with remote transactions. If you call a remote
      schema-level function or procedure from a trigger body, it is possible that you may encounter a
      timestamp or signature mismatch. A mismatch invalidates the trigger and causes the triggering
      SQL statement to fail.
  • LONG and LONG RAW Datatypes
    • The LONG and LONG RAW datatypes are legacy components. Migrate out of them.
    • A trigger cannot declare a variable of the LONG or LONG RAW data type.
    • You may, however, insert into a LONG or LONG RAW column when the value can be converted CHAR or VARCHAR2.
    • Row-level triggers cannot use a :new,:old or parent with a LONG or LONG RAW column.
  • Triggers will fail if try to access a mutating table.
  • Oracle 11g has relaxed some mutating table restrictions

Triggers and data transfers
These utilities may fire triggers:
SQL*LOoader (sqlldr), Data Pump Import (impdp) and Original import (imp)
SQL*Loader (sqlldr):
- During a SQL*Loader conventional load, INSERT triggers fire.
- Before a SQL*Loader direct load, triggers are disabled.
Data Pump Import (impdp):
- If a table to be imported does not exist on the target database, or if you specify TABLE_EXISTS_ACTION=REPLACE, then impdp creates and loads the table before creating any triggers, so no triggers fire.
- If a table to be imported exists on the target database, and you specify either TABLE_EXISTS_ACTION=APPEND or TABLE_EXISTS_ACTION=TRUNCATE, then impdp loads rows into the existing table, and INSERT triggers created on the table fire.
Original Import (imp):
- If a table to be imported does not exist on the target database, then imp creates and loads the table before creating any triggers, so no triggers fire.
- If a table to be imported exists on the target database, then the Import IGNORE parameter determines whether triggers fire during import operations:
- If IGNORE=n (default), then imp does not change the table and no triggers fire.
- If IGNORE=y, then imp loads rows into the existing table, and INSERT triggers created on the table fire.

(ref) On Data Types



(a) Scalar data types
Can have subtypes. A data type and its subtypes comprise a data type family.


PL/SQL scalar data types are:
  • The SQL data types
  • BOOLEAN
  • PLS_INTEGER
  • BINARY_INTEGER
  • REF CURSOR
  • User-defined subtypes

More information on Oracle and SQL Data types...

  • The PL/SQL data types include the SQL data types. Some have larger max sizes:
  • CHAR, NCHAR, RAW, VARCHAR2, NVARCHAR2, LONG, LONG RAW, BLOB, CLOB, NCLOB
  • PL/SQL define subtypes for BINARY_FLOAT: SIMPLE_FLOAT and BINARY_DOUBLE: SIMPLE_DOUBLE

CHAR vs. VARCHAR2

Predefined Subtypes
  • CHAR: CHARACTER (PL/SQL and SQL)
  • VARCHAR2: VARCHAR (PL/SQL and SQL), STRING (PL/SQL alone)
Memory allocation
  • CHAR(MaxSize): During compile MaxSize is allocated in memory.
  • VARCHAR2(MaxSize): If MaxSize < 4k: full allocation at compile time. (for performance)
  • VARCHAR2(MaxSize): If MaxSize >= 4k: allocation enough for the actual value during run time. (for efficient memory use)
Blank Padding
  • CHAR will do blank-pads to the maximum size. Information loss.
  • VARCHAR2 will NOT do blank-pads to the maximum size. No information loss.
Value Comparisons
  • If one or both values in the comparison have the data type VARCHAR2 or NVARCHAR2, nonpadded comparison semantics apply; otherwise, blank-padded semantics apply

LONG and LONG RAW
Supported for backward compatibility only.
  • Instead of LONG: use VARCHAR2(32760), BLOB, CLOB, NCLOB
  • Instead of LONG RAW: use BLOB
  • From LONG variable => LONG column: ANY Value.
  • From LONG RAW variable => LONG RAW column: ANY Value.
  • From LONG (or LONG RAW) column => LONG (LONG RAW) variable: 32Kb maximum.
  • TRIGGER restrictions: (a) Cannot declare LONG or LONG RAW. (b)Cannot use correlation name NEW or PARENT with LONG or LONG RAW. (c) Stmt can reference LONG or LONG RAW column ONLY if the column data can be converted to CHAR or VARCHAR2.

ROWID and UROWID variables (more on ROWIDs here)
  • ROWIDTOCHAR and CHARTOROWID: Conversion functions.
  • UROWID: more versatile. Compatible with logical, physical and foreign rowids.
  • DBMS_ROWID package:
    The DBMS_ROWID package lets you create ROWIDs and obtain information about ROWIDs from PL/SQL programs and SQL statements. You can find the data block number, the object number, and other ROWID components.
    DBMS_ROWID is intended for upgrading from Oracle 7 to 8.X.

About Rowids
rowids are used in the construction of indexes. In addition to this,
  • Rowids are the fastest means of accessing particular rows.
  • Rowids provide the ability to see how a table is organized.
  • Rowids are unique identifiers for rows in a given table.

ROWID Pseudocolumn
  • Every Oracle table has a pseudocolumn named ROWID. It value, however, is not actually stored in the table.
  • You can select from pseudocolumns, but you cannot insert, update, or delete their values.
  • Values of the ROWID pseudocolumn are strings representing the address of each row.

-- Query to show the extended rowid
SQL> select rowid from hr.employees where employee_id=100;

ROWID
------------------
AAAC9EAAEAAAABXAAA 

  • ROWID is not physically stored in the database.It is inferred from the file and block address of the data.
  • An extended rowid includes a data object number. This rowid type uses a base 64 encoding of the physical address for each row.


  • Extended rowid: four-piece format.
  • AAAC9E: The data object number identifies the segment. A data object number is assigned to every database segment.
  • AAE: The data file number: Tablespace-relative. Identifies the file that contains the row.
  • AAAABX: The data block number Identifies the block that contains the row. Relative to the datafile.
  • AAA: The row number: identifies the row in the block.

When does a ROWID change?
  • If row movement is enabled: ROWID can change because of partition key updates, Flashback Table operations, shrink table operations, and so on.
  • If row movement is disabled: ROWID can change if the row is exported and imported using Oracle Database utilities
  • You can create table column using the ROWID data type. However, storing a rowid with the intent of using it latter, for example, as an audit trail record, may not be a good idea:
  • rowid may change as the result of an alter table or after partition movement (for partitioned tables).










(more on ROWIDs here)




Boolean
  • Valid values: {TRUE | FALSE | NULL}
  • SQL has no equivalent to BOOLEAN. Thus you cannot:
  • Assign a BOOLEAN value to a database table column
  • Select or fetch the value of a database table column into a BOOLEAN variable
  • Use a BOOLEAN value in a SQL statement, SQL function, or PL/SQL function invoked from a SQL statement
  • Cannot pass a BOOLEAN value to the DBMS_OUTPUT.PUT or DBMS_OUTPUT.PUTLINE subprogram.


PLS_INTEGER and BINARY_INTEGER
User-Defined PL/SQL Subtypes