Distributed Database Applications COSC 5050 Week Six.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
Oracle PL/SQL (2) John Ortiz. Lecture 14Oracle PL/SQL (2)2 Package  A package is a group of related PL/SQL objects (variables, …), procedures, and functions.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 8 Application Data Auditing.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 8 Application Data Auditing.
Triggers. Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Creating Triggers.
Oracle PL/SQL TRIGGERS
 Data creation and destruction  Inserting into a table  Deleting from a table  Modifying values in a table  Other commonly used features  Views 
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Triggers in SQL’99 CS561.
Triggers.
Stored Procedures PL/SQL code stored in the database and executed when called by the user. Called by procedure name from another PL/SQL block or using.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Adapted from Afyouni, Database Security and Auditing Database Application Auditing – Ch. 8.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
SQL Server 7.0 Maintaining Referential Integrity.
Distributed Database Applications COSC 5050 Week One.
In Oracle.  A PL/SQL block stored in the database and fired in response to a specified event ◦ DML statements : insert, update, delete ◦ DDL statements.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
1 ISYS Triggers. 2 Agenda Triggers Review Correlation identifiers (pseudo records) Restrictions on triggers Trigger usage Mutating tables Enabling.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Technology Jing Shen.
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
1 Chapter 7 Triggers and Active Databases. 2 Trigger Overview Element of the database schema General form: ON IF THEN –Event- request to execute database.
Creating DDL and Database Event Triggers. 2 home back first prev next last What Will I Learn? Describe events that cause DDL and database event triggers.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Objectives Database triggers and syntax
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) a database trigger automatically.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Chapter 19: Triggers1 Chapter Nineteen Triggers Objective: – Understanding Triggers – Types of Triggers – Applications of Triggers – How to work with Triggers.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ISYS Triggers.
Creating Triggers.
Creating Database Triggers
Active Database Concepts
SQL Stored Triggers Presented by: Dr. Samir Tartir
Introduction to Triggers
Agenda Triggers Review Correlation identifiers (pseudo records)
ISYS Triggers.
Introduction to Triggers
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Creating Triggers.
Contents Preface I Introduction Lesson Objectives I-2
Triggers.
Prof. Arfaoui. COM390 Chapter 9
TRIGGERS.
Responding to Data Manipulation Via Triggers
Presentation transcript:

Distributed Database Applications COSC 5050 Week Six

Jiangping Wang Webster UniversityDistributed Database Applications Outline Triggers DML triggers Mutating tables Other triggers

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications Use of Triggers Perform validation on changes being made to tables Automate maintenance of the database Apply rules about acceptable database administration activity

Jiangping Wang Webster UniversityDistributed Database Applications Type of Trigger DML statement DDL statement Database event Instead of Suspended statement

Jiangping Wang Webster UniversityDistributed Database Applications DML Trigger Fires when records are inserted into, updated within, or deleted from a table

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 UniversityDistributed Database Applications

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications Twelve DML Triggers Action Insert, update, and delete Level Statement-level and row-level Timing Before and after

Jiangping Wang Webster UniversityDistributed Database Applications Twelve Triggers INSERTUPDATEDELETE BEFORE INSERT STMTBEFORE UPDATE STMTBEFORE DELETE STMT BEFORE INSERT ROWBEFORE UPDATE ROWBEFORE DELETE ROW AFTER INSERT STMTAFTER UPDATE STMTAFTER DELETE STMT AFTER INSERT ROWAFTER UPDATE ROWAFTER DELETE ROW

Jiangping Wang Webster UniversityDistributed Database Applications Trigger Name Trigger name must be unique within a schema INSERTUPDATEDELETE 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

Jiangping Wang Webster UniversityDistributed Database Applications 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; /

Jiangping Wang Webster UniversityDistributed Database Applications 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; /

Jiangping Wang Webster UniversityDistributed Database Applications 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; /

Jiangping Wang Webster UniversityDistributed Database Applications When Clause 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; When clause must evaluate to TRUE for the trigger to fire

Jiangping Wang Webster UniversityDistributed Database Applications 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 )...

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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, :prior_to_cheat.strike, :after_cheat.strike, …) End;

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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;

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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';

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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?

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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; /

Jiangping Wang Webster UniversityDistributed Database Applications When Tables Mutate INSERTUPDATEDELETE 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

Jiangping Wang Webster UniversityDistributed Database Applications When Tables Mutate Think of four triggers as a series of events: Before Statement No Error Before Row Mutating Error After Row Mutating Error After Statement No Error Before Statement No Error Before Row Mutating Error After Row Mutating Error After Statement No Error Before Statement Mutating Error Before Row Mutating Error After Row Mutating Error After Statement Mutating Error Delete Cascade

Jiangping Wang Webster UniversityDistributed Database Applications DDL Triggers Create table / alter table Create index Create trigger / drop trigger

Jiangping Wang Webster UniversityDistributed Database Applications 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));

Jiangping Wang Webster UniversityDistributed Database Applications Dropping the Undroppable CREATE OR REPLACE TRIGGER ON_CREATE BEFORE CREATE ON SCHEMA BEGIN RAISE_APPLICATION_ERROR( , 'ERROR: OBJECTS CANNOT BE CREATED IN THIS DATABASE.'); END; CREATE OR REPLACE TRIGGER UNDROPPABLE BEFORE DROP ON SCHEMA BEGIN RAISE_APPLICATION_ERROR( , 'YOU CANNOT DROP ME! '); END;

Jiangping Wang Webster UniversityDistributed Database Applications Database Event Triggers Database event triggers fire whenever database wide events occur START UP SHUTDOWN SERVERERROR LOGON LOGOFF

Jiangping Wang Webster UniversityDistributed Database Applications 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; / Database Event Triggers

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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;

Jiangping Wang Webster UniversityDistributed Database Applications 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;

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications AFTER SUSPEND Triggers Fire whenever a statement is suspended Space issue Suspended/resumable statement

Jiangping Wang Webster UniversityDistributed Database Applications Maintaining Triggers Disable triggers Enable triggers Drop triggers View triggers USER_TRIGGERS Validity of triggers SELECT OBJECT_NAME, OBJECT_TYPE, STATUS FROM USER_OBJECTS;

Jiangping Wang Webster UniversityDistributed Database Applications Administration of Triggers Enable and disable ALTER 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; Drop DROP TRIGGER PURCHASE_ORDER_BIR;

Jiangping Wang Webster UniversityDistributed Database Applications 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

Jiangping Wang Webster UniversityDistributed Database Applications 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.