Top Banner
Distributed Database Applications COSC 5050 Week Six
43

Distributed Database Applications

Feb 04, 2016

Download

Documents

Grady

Distributed Database Applications. COSC 5050 Week Six. Outline. Triggers DML triggers Mutating tables Other triggers. Trigger. Trigger A named PL/SQL block stored in a database and executed implicitly when a triggering event occurs Triggering event - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Distributed Database Applications

Distributed Database Applications

COSC 5050Week Six

Page 2: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Outline

TriggersDML triggersMutating tablesOther triggers

Page 3: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

TriggerTrigger

A named PL/SQL block stored in a database and executed implicitly when a triggering event occurs

Triggering eventDML statement, DDL statement, and database event executed or occurred on database

A trigger can fire before or after a triggering event

Page 4: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Use of Triggers

Perform validation on changes being made to tablesAutomate maintenance of the databaseApply rules about acceptable database administration activity

Page 5: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Type of Trigger

DML statementDDL statementDatabase eventInstead ofSuspended statement

Page 6: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

DML TriggerFires when records are inserted into, updated within, or deleted from a table

Page 7: Distributed Database Applications

Jiangping Wang

DML TriggerDML Trigger concepts

Before triggerAfter triggerStatement-level trigger

For a SQL statement as a whole

Row-level triggerFor a single affected row

NEW and OLD pseudo-recordOnly available within a DML trigger

WHEN clause

Webster University Distributed Database Applications

Page 8: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

DML Trigger

Transaction participationDML triggers participate in the transaction from which they were firedIf 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

Page 9: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Twelve DML Triggers

ActionInsert, update, and delete

LevelStatement-level and row-level

TimingBefore and after

Page 10: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

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

Page 11: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Trigger Name

Trigger name must be unique within a schema

INSERT UPDATE DELETE

BEFORE INSERT STMT

TABLE_NAME_BIS

BEFORE UPDATE STMT

TABLE_NAME_BUS

BEFORE DELETE STMT

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

Page 12: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Statement vs. Row Trigger-- an after statement level triggerCREATE OR REPLACE TRIGGER statement_triggerAFTER update ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('After update statement level');END;/

-- an after row level trigger CREATE OR REPLACE TRIGGER row_triggerAFTER update ON employeeFOR EACH ROWBEGIN DBMS_OUTPUT.PUT_LINE('After update row level');END;/

Page 13: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Before vs. After Trigger-- a before statement level triggerCREATE OR REPLACE TRIGGER before_statement_triggerBEFORE update ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('Before update statement level');END;/

-- an after statement level triggerCREATE OR REPLACE TRIGGER after_statement_triggerAFTER update ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('After update statement level');END;/

Page 14: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Trigger for Various DML-- after insert statementCREATE OR REPLACE TRIGGER after_insert_statementAFTER INSERT ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('After insert statement');END;/-- after update statementCREATE OR REPLACE TRIGGER after_update_statementAFTER UPDATE ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('After update statement');END;/-- after delete statementCREATE OR REPLACE TRIGGER after_delete_statementAFTER DELETE ON employeeBEGIN DBMS_OUTPUT.PUT_LINE('After delete statement');END;/

Page 15: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

When Clause

create or replace trigger bef_ins_ceo_compafter updateon ceo_compensationfor each row

when ( old.compensation * 1.2 < new.compensation )pragma autonomous_transaction;

begininsert into ceo_comp_history

values (:new.name, :old.compensation, :new.compensation, ‘after update’, sysdate);

commit;end;

When clause must evaluate to TRUE for the trigger to fire

Page 16: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

When Clause -- an after row level trigger CREATE OR REPLACE TRIGGER row_when_triggerAFTER update ON employeeFOR EACH ROWWHEN (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 ) ...

Page 17: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Pseudo-RecordData structures that like records for a row level triggerNEW -- new values, for insert and updateOLD -- original values, for update and deleteIs of a type triggering_table%rowtype

Preface with a colon within trigger:new.salaryNo colon with WHEN clause

Page 18: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Pseudo-RecordUse of REFERENCING clauseCreate or replace trigger audit_update after update on frame referencing old as prior_to_cheat new as after_cheat for each rowBegin 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;

Page 19: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Determining DML Action

INSERTINGUPDATINGDELETING

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

Page 20: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Determining DML Actionalter table employee add( created_by varchar2(20), created_date date, modified_by varchar2(20), modified_date date);

create or replace trigger three_in_onebefore delete or insert or update on employeefor each rowbegin 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;

Page 21: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Multiple Triggers

Multiple triggers of the same type for a single tableA single trigger is easier to maintainMultiple same type triggers reduce parse and execution time

No guarantee of the order of firing

Page 22: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Data DictionaryUSER_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';

Page 23: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Mutating Tables

Mutating table A table having a DML statement issued against it

Mutating table errorTrigger tries to read or modify such a tableWhen a row level trigger tries to examine or change a table that is already undergoing change

Page 24: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Mutating TablesTable is mutating when it

Is being modified by insert, update, or delete statementIs being read by Oracle to enforce a referential integrity constraintIs being updated by Oracle to enforce a delete cascade constraint

What tables mutate?When do tables mutate?

Page 25: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

What Tables MutateFor any insert, update, or delete statement, the table that is the target will mutateForeign 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

Page 26: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Mutating Problem

The problem occurs when a trigger attempts to read from a table or update a table while it is mutatingA row trigger cannot issue a read/write against a table that is mutating

Statement level trigger is fine

Page 27: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

When Tables Mutatecreate table tab (n number);

-- The before insert statementcreate or replace trigger tab_bisbefore insert on tab--for each rowdeclare

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;/

Page 28: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

When Tables Mutate

INSERT UPDATE DELETE

BEFORE INSERT STMT

NO

BEFORE UPDATE STMT

NO

BEFORE DELETE STMT

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

Triggers generate mutating table error

Page 29: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

When Tables Mutate

Think of four triggers as a series of events:

Before StatementNo Error

Before RowMutating Error

After RowMutating Error

After StatementNo Error

Before StatementNo Error

Before RowMutating Error

After RowMutating Error

After StatementNo Error

Before StatementMutating Error

Before RowMutating Error

After RowMutating Error

After StatementMutating Error

Delete Cascade

Page 30: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

DDL Triggers

Create table / alter tableCreate indexCreate trigger / drop trigger

Page 31: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

CREATE OR REPLACE TRIGGER town_crierAFTER CREATE ON SCHEMABEGIN DBMS_OUTPUT.PUT_LINE('I believe you have created something!');END;/

SET SERVEROUTPUT ONDROP 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 ASBEGIN RETURN(TRUE);END;/

/*-- a CRLF to flush DBMS_OUTPUTs buffer */EXEC DBMS_OUTPUT.PUT_LINE(CHR(10));

Page 32: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Dropping the Undroppable

CREATE OR REPLACE TRIGGER ON_CREATEBEFORE CREATE ON SCHEMABEGIN RAISE_APPLICATION_ERROR( -20000, 'ERROR: OBJECTS CANNOT BE CREATED IN THIS DATABASE.');END;

CREATE OR REPLACE TRIGGER UNDROPPABLEBEFORE DROP ON SCHEMABEGIN RAISE_APPLICATION_ERROR( -20000, 'YOU CANNOT DROP ME! ');END;

Page 33: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Database Event Triggers

Database event triggers fire whenever database wide events occur

START UPSHUTDOWNSERVERERRORLOGONLOGOFF

Page 34: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

CREATE OR REPLACE TRIGGER error_log AFTER SERVERERROR ON SCHEMADECLARE 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;/

Database Event Triggers

Page 35: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

INSTEAD OF TriggersView

A custom representation of dataCan be referred to as a “stored query”

Non-updateable viewSet operations such as union, union all, intersect, minusGroup functions such as avg, count, max, min,sumGroup by or having clausesThe distinct operator

Page 36: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

INSTEAD OF Triggerscreate 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;

Page 37: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

INSTEAD OF Triggerscreate or replace trigger dept_summary_delinstead of delete on dept_summaryfor each rowbegin 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;

Page 38: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

INSTEAD OF Triggers

Complexity of designing an INSTEAD OF trigger

The relationship among tablesEffect of a trigger designUnderlying tables may not be limited by the view query

Page 39: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

AFTER SUSPEND Triggers

Fire whenever a statement is suspended

Space issueSuspended/resumable statement

Page 40: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Maintaining Triggers

Disable triggersEnable triggersDrop triggersView triggers

USER_TRIGGERS

Validity of triggersSELECT OBJECT_NAME,

OBJECT_TYPE, STATUS FROM USER_OBJECTS;

Page 41: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Administration of Triggers

Enable and disableALTER TABLE PURCHASE_ORDER ENABLE ALL TRIGGERS;

ALTER TABLE PURCHASE_ORDER DISABLE ALL TRIGGERS;

ALTER TRIGGER PURCHASE_ORDER_BIR DISABLE;

ALTER TRIGGER PURCHASE_ORDER_BIR ENABLE;

DropDROP TRIGGER PURCHASE_ORDER_BIR;

Page 42: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

Administration of Triggers

If the table is dropped, the table’s database triggers are dropped as wellBe careful to use “replace”

Replace existing function, procedure, or package with the same nameAssociate a different table with your trigger, an error message is generated

Page 43: Distributed Database Applications

Jiangping WangWebster University Distributed Database Applications

HomeworkCreate 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.