Distributed Database Applications COSC 5050 Week Six

advertisement
Distributed Database
Applications
COSC 5050
Week Six
Outline
Triggers
DML triggers
Mutating tables
Other triggers
Webster University
Distributed Database Applications
Jiangping Wang
Trigger
Trigger
A named PL/SQL block stored in a database and
executed implicitly when a triggering event occurs
Triggering event
DML statement, DDL statement, and database
event executed or occurred on database
A trigger can fire before or after a triggering
event
Webster University
Distributed Database Applications
Jiangping Wang
Use of Triggers
Perform validation on changes being
made to tables
Automate maintenance of the database
Apply rules about acceptable database
administration activity
Webster University
Distributed Database Applications
Jiangping Wang
Type of Trigger
DML statement
DDL statement
Database event
Instead of
Suspended statement
Webster University
Distributed Database Applications
Jiangping Wang
DML Trigger
Fires when records are inserted into,
updated within, or deleted from a table
Webster University
Distributed Database Applications
Jiangping Wang
DML Trigger
DML Trigger concepts
Before trigger
After trigger
Statement-level trigger
For a SQL statement as a whole
Row-level trigger
For a single affected row
NEW and OLD pseudo-record
Only available within a DML trigger
WHEN clause
Webster University
Distributed Database Applications
Jiangping Wang
DML Trigger
Transaction participation
DML triggers participate in the transaction
from which they were fired
If trigger raise an exception?
If trigger performs any DML itself?
Cannot issue COMMIT or ROLLBACK from
within a DML trigger
Unless autonomous transaction is used
Webster University
Distributed Database Applications
Jiangping Wang
Twelve DML Triggers
Action
Insert, update, and delete
Level
Statement-level and row-level
Timing
Before and after
Webster University
Distributed Database Applications
Jiangping Wang
Twelve Triggers
INSERT
UPDATE
DELETE
BEFORE INSERT STMT BEFORE UPDATE STMT BEFORE DELETE STMT
BEFORE INSERT ROW
BEFORE UPDATE ROW
BEFORE DELETE ROW
AFTER INSERT STMT
AFTER UPDATE STMT
AFTER DELETE STMT
AFTER INSERT ROW
AFTER UPDATE ROW
AFTER DELETE ROW
Webster University
Distributed Database Applications
Jiangping Wang
Trigger Name
Trigger name must be unique within a
schema
INSERT
UPDATE
DELETE
BEFORE INSERT STMT BEFORE UPDATE STMT BEFORE DELETE STMT
TABLE_NAME_BIS
TABLE_NAME_BUS
TABLE_NAME_BDS
BEFORE INSERT ROW
TABLE_NAME_BIR
BEFORE UPDATE ROW
TABLE_NAME_BUR
BEFORE DELETE ROW
TABLE_NAME_BDR
AFTER INSERT STMT
TABLE_NAME_AIS
AFTER UPDATE STMT
TABLE_NAME_AUS
AFTER DELETE STMT
TABLE_NAME_ADS
AFTER INSERT ROW
TABLE_NAME_AIR
AFTER UPDATE ROW
TABLE_NAME_AUR
AFTER DELETE ROW
TABLE_NAME_ADR
Webster University
Distributed Database Applications
Jiangping Wang
Statement vs. Row Trigger
-- an after statement level trigger
CREATE OR REPLACE TRIGGER statement_trigger
AFTER update ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('After update statement level');
END;
/
-- an after row level trigger
CREATE OR REPLACE TRIGGER row_trigger
AFTER update ON employee
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('After update row level');
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
Before vs. After Trigger
-- a before statement level trigger
CREATE OR REPLACE TRIGGER before_statement_trigger
BEFORE update ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('Before update statement level');
END;
/
-- an after statement level trigger
CREATE OR REPLACE TRIGGER after_statement_trigger
AFTER update ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('After update statement level');
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
Trigger for Various DML
-- after insert statement
CREATE OR REPLACE TRIGGER after_insert_statement
AFTER INSERT ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('After insert statement');
END;
/
-- after update statement
CREATE OR REPLACE TRIGGER after_update_statement
AFTER UPDATE ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('After update statement');
END;
/
-- after delete statement
CREATE OR REPLACE TRIGGER after_delete_statement
AFTER DELETE ON employee
BEGIN
DBMS_OUTPUT.PUT_LINE('After delete statement');
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
When Clause
When clause must evaluate to TRUE for
the trigger to fire
create or replace trigger bef_ins_ceo_comp
after update
on ceo_compensation
for each row
when ( old.compensation * 1.2 < new.compensation )
pragma autonomous_transaction;
begin
insert into ceo_comp_history
values (:new.name,
:old.compensation, :new.compensation,
‘after update’, sysdate);
commit;
end;
Webster University
Distributed Database Applications
Jiangping Wang
When Clause
-- an after row level trigger
CREATE OR REPLACE TRIGGER row_when_trigger
AFTER update ON employee
FOR EACH ROW
WHEN (OLD.code > 1000 and NEW.code > OLD.code)
BEGIN
DBMS_OUTPUT.PUT_LINE('After update when code < 1000');
DBMS_OUTPUT.PUT_LINE('Old value = ' || :OLD.code || ', ' );
DBMS_OUTPUT.PUT_LINE('New value = ' || :NEW.code || '. ' );
END;
/
CREATE OR REPLACE TRIGGER valid_when_clause
BEFORE INSERT ON frame
FOR EACH ROW
WHEN ( TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 17 )
...
Webster University
Distributed Database Applications
Jiangping Wang
Pseudo-Record
Data structures that like records for a row
level trigger
NEW -- new values, for insert and update
OLD -- original values, for update and delete
Is of a type
triggering_table%rowtype
Preface with a colon within trigger
:new.salary
No colon with WHEN clause
Webster University
Distributed Database Applications
Jiangping Wang
Pseudo-Record
Use of REFERENCING clause
Create or replace trigger audit_update
after update on frame
referencing old as prior_to_cheat new as after_cheat
for each row
Begin
insert into frame_audit
(bowler_id,
game_id,
frame_number,
old_strike,
new_strike, …)
values
(:after_cheat.bowler_id,
:after_cheat.game_id,
:after_cheat.game_id,
:prior_to_cheat.strike,
:after_cheat.strike, …)
End;
Webster University
Distributed Database Applications
Jiangping Wang
Determining DML Action
INSERTING
UPDATING
DELETING
PACKAGE DBMS_STANDARD IS
FUNCTION INSERTING RETURN BOOLEAN;
FUNCTION DELETING RETURN BOOLEAN;
FUNCTION UPDATING RETURN BOOLEAN;
FUNCTION UPDATING (COLNAM VARCHAR2) RETURN BOOLEAN;
…
END DBMS_STANDARD
Webster University
Distributed Database Applications
Jiangping Wang
Determining DML Action
alter table employee add
( created_by varchar2(20)
, created_date date
, modified_by varchar2(20)
, modified_date date
);
create or replace trigger three_in_one
before delete or insert or update on employee
for each row
begin
if inserting then
:new.created_by := user;
:new.created_date := sysdate;
elsif deleting then
dbms_output.put_line('audit_deletion(user, sysdate)');
elsif updating then
:new.modified_by := user;
:new.modified_date := sysdate;
end if;
end;
Webster University
Distributed Database Applications
Jiangping Wang
Multiple Triggers
Multiple triggers of the same type for a
single table
A single trigger is easier to maintain
Multiple same type triggers reduce
parse and execution time
No guarantee of the order of firing
Webster University
Distributed Database Applications
Jiangping Wang
Data Dictionary
USER_TRIGGERS
SELECT TRIGGER_NAME, STATUS
FROM USER_TRIGGERS;
SELECT TRIGGER_BODY
FROM USER_TRIGGERS
WHERE TRIGGER_NAME = '&1';
SELECT TEXT
FROM USER_SOURCE
WHERE NAME = '&1';
Webster University
Distributed Database Applications
Jiangping Wang
Mutating Tables
Mutating table
A table having a DML statement issued
against it
Mutating table error
Trigger tries to read or modify such a table
When a row level trigger tries to examine
or change a table that is already
undergoing change
Webster University
Distributed Database Applications
Jiangping Wang
Mutating Tables
Table is mutating when it
Is being modified by insert, update, or delete
statement
Is being read by Oracle to enforce a referential
integrity constraint
Is being updated by Oracle to enforce a delete
cascade constraint
What tables mutate?
When do tables mutate?
Webster University
Distributed Database Applications
Jiangping Wang
What Tables Mutate
For any insert, update, or delete statement,
the table that is the target will mutate
Foreign key constraints, both parent and child
tables will mutate whenever:
Update parent (parent update restrict)
Delete from parent (parent delete restrict)
Insert into child (child insert restrict)
Update child (child update restrict)
When delete cascade, the parent table and all
relative child tables will mutate
Webster University
Distributed Database Applications
Jiangping Wang
Mutating Problem
The problem occurs when a trigger
attempts to read from a table or update
a table while it is mutating
A row trigger cannot issue a read/write
against a table that is mutating
Statement level trigger is fine
Webster University
Distributed Database Applications
Jiangping Wang
When Tables Mutate
create table tab (n number);
-- The before insert statement
create or replace trigger tab_bis
before insert on tab
--for each row
declare
row_count number;
begin
dbms_output.put_line(
'enter before insert statement trigger');
select count(*) into row_count from tab;
dbms_output.put_line(
'leave before insert statement trigger');
end;
/
Webster University
Distributed Database Applications
Jiangping Wang
When Tables Mutate
Triggers generate mutating table error
INSERT
UPDATE
DELETE
BEFORE INSERT STMT BEFORE UPDATE STMT BEFORE DELETE STMT
NO
NO
NO
BEFORE INSERT ROW
NO (single row insert only)
BEFORE UPDATE ROW
YES
BEFORE DELETE ROW
YES
AFTER INSERT STMT
NO
AFTER UPDATE STMT
NO
AFTER DELETE STMT
NO
AFTER INSERT ROW
YES
AFTER UPDATE ROW
YES
AFTER DELETE ROW
YES
Webster University
Distributed Database Applications
Jiangping Wang
When Tables Mutate
Think of four triggers as a series of
events:
Before Statement
No Error
Before Statement
No Error
Before Statement
Mutating Error
Before Row
Mutating Error
Before Row
Mutating Error
Before Row
Mutating Error
After Row
Mutating Error
After Row
Mutating Error
After Row
Mutating Error
After Statement
No Error
After Statement
No Error
After Statement
Mutating Error
Delete Cascade
Webster University
Distributed Database Applications
Jiangping Wang
DDL Triggers
Create table / alter table
Create index
Create trigger / drop trigger
Webster University
Distributed Database Applications
Jiangping Wang
CREATE OR REPLACE TRIGGER town_crier
AFTER CREATE ON SCHEMA
BEGIN
DBMS_OUTPUT.PUT_LINE('I believe you have created something!');
END;
/
SET SERVEROUTPUT ON
DROP TABLE a_table;
CREATE TABLE a_table
(col1 NUMBER);
CREATE INDEX an_index ON a_table(col1);
DROP FUNCTION a_function;
CREATE FUNCTION a_function RETURN BOOLEAN AS
BEGIN
RETURN(TRUE);
END;
/
/*-- a CRLF to flush DBMS_OUTPUTs buffer */
EXEC DBMS_OUTPUT.PUT_LINE(CHR(10));
Webster University
Distributed Database Applications
Jiangping Wang
Dropping the Undroppable
CREATE OR REPLACE TRIGGER ON_CREATE
BEFORE CREATE ON SCHEMA
BEGIN
RAISE_APPLICATION_ERROR(
-20000,
'ERROR: OBJECTS CANNOT BE CREATED IN THIS DATABASE.');
END;
CREATE OR REPLACE TRIGGER UNDROPPABLE
BEFORE DROP ON SCHEMA
BEGIN
RAISE_APPLICATION_ERROR(
-20000,
'YOU CANNOT DROP ME! ');
END;
Webster University
Distributed Database Applications
Jiangping Wang
Database Event Triggers
Database event triggers fire whenever
database wide events occur
START UP
SHUTDOWN
SERVERERROR
LOGON
LOGOFF
Webster University
Distributed Database Applications
Jiangping Wang
Database Event Triggers
CREATE OR REPLACE TRIGGER error_log
AFTER SERVERERROR ON SCHEMA
DECLARE
v_errnum NUMBER;
v_now
DATE := SYSDATE;
v_counter NUMBER := 1;
BEGIN
LOOP
v_errnum := ORA_SERVER_ERROR(v_counter);
EXIT WHEN v_errnum = 0;
INSERT INTO error_log(
username, error_number, sequence, timestamp)
VALUES(USER, v_errnum, v_counter, v_now);
v_counter := v_counter + 1;
END LOOP;
END;
/
Webster University
Distributed Database Applications
Jiangping Wang
INSTEAD OF Triggers
View
A custom representation of data
Can be referred to as a “stored query”
Non-updateable view
Set operations such as union, union all, intersect,
minus
Group functions such as avg, count, max, min,sum
Group by or having clauses
The distinct operator
Webster University
Distributed Database Applications
Jiangping Wang
INSTEAD OF Triggers
create view dept_summary
as
select department.dept_num, dept_name,
count(ssn) as total_employees
from department inner join employee
on department.dept_num = employee.dept_num
group by department.dept_num, dept_name;
delete from dept_summary where dept_num = 2;
Webster University
Distributed Database Applications
Jiangping Wang
INSTEAD OF Triggers
create or replace trigger dept_summary_del
instead of delete on dept_summary
for each row
begin
update department set dept_mgr_ssn = null
where dept_num = :old.dept_num;
delete from employee
where dept_num = :old.dept_num;
delete from department
where dept_num = :old.dept_num;
end;
delete from dept_summary where dept_num = 2;
delete from dept_summary where dept_num = 15;
delete from dept_summary where dept_num = 1;
Webster University
Distributed Database Applications
Jiangping Wang
INSTEAD OF Triggers
Complexity of designing an INSTEAD
OF trigger
The relationship among tables
Effect of a trigger design
Underlying tables may not be limited by
the view query
Webster University
Distributed Database Applications
Jiangping Wang
AFTER SUSPEND Triggers
Fire whenever a statement is
suspended
Space issue
Suspended/resumable statement
Webster University
Distributed Database Applications
Jiangping Wang
Maintaining Triggers
Disable triggers
Enable triggers
Drop triggers
View triggers
USER_TRIGGERS
Validity of triggers
SELECT OBJECT_NAME,
OBJECT_TYPE, STATUS FROM USER_OBJECTS;
Webster University
Distributed Database Applications
Jiangping Wang
Administration of Triggers
Enable and disable
ALTER
ALTER
ALTER
ALTER
TABLE PURCHASE_ORDER ENABLE ALL TRIGGERS;
TABLE PURCHASE_ORDER DISABLE ALL TRIGGERS;
TRIGGER PURCHASE_ORDER_BIR DISABLE;
TRIGGER PURCHASE_ORDER_BIR ENABLE;
Drop
DROP TRIGGER PURCHASE_ORDER_BIR;
Webster University
Distributed Database Applications
Jiangping Wang
Administration of Triggers
If the table is dropped, the table’s
database triggers are dropped as well
Be careful to use “replace”
Replace existing function, procedure, or
package with the same name
Associate a different table with your
trigger, an error message is generated
Webster University
Distributed Database Applications
Jiangping Wang
Homework
Create a PL/SQL update trigger on the
employee table that caps the salary
increment by 10%.
What are the eventual update values for the
PL/SQL commands?
Create an audit table and implement the
audit_deletion trigger logic.
Lab activities.
Webster University
Distributed Database Applications
Jiangping Wang
Download