Active DatabasesCIS 6711 Triggers: The Problem - Examples from COMPANY Database 1.Limit all salary increases to 50%. 2.Enforce policy that salaries may.

Slides:



Advertisements
Similar presentations
Active database concepts
Advertisements

Convert ER to Relational Database Entity relation Entity relation Attributes attributes Attributes attributes Primary key primary key Primary key primary.
1 Constraints, Triggers and Active Databases Chapter 9.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
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.
IC and Triggers in SQL. Find age of the youngest sailor with age
©Silberschatz, Korth and Sudarshan6.1Database System Concepts Chapter 6: Integrity (and Security) Domain Constraints Referential Integrity Assertions Triggers.
Triggers. Triggers: Motivation Assertions are powerful, but the DBMS often can’t tell when they need to be checked. Attribute- and tuple-based checks.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
CMSC424: Database Design Instructor: Amol Deshpande
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
1 CMSC424, Spring 2005 CMSC424: Database Design Lecture 8.
MySQL Tutorial (2) Introduction to Database. Banking Example branch (branch-name, branch-city, assets) customer (customer-name, customer-street, customer-city)
Triggers.
CMSC424: Database Design Instructor: Amol Deshpande
Cs3431 Triggers vs Constraints Section 7.5. cs3431 Triggers (Make DB Active) Trigger: A procedure that starts automatically if specified changes occur.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
Chapter 6: Integrity Objective Key Constraints (Chapter 2) Cardinality Constraints (Chapter 2) Domain Constraints Referential Integrity Assertions Triggers.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE) Datalog.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
Data Integrity An empty database is a correct database.
FEN  Data Definition: CREATE TABLE, ALTER TABLE  Data Manipulation: INSERT, UPDATE, DELETE  Queries: SELECT SQL: Structured Query Language.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
Slide Chapter 5 The Relational Data Model and Relational Database Constraints.
Chapter 4 Advanced SQL: Integrity Constraints. 2 n Ensure Data Consistency n Domain Constraints  enforce valid attribute values from domain sets  domain.
Triggers. Why Triggers ? Suppose a warehouse wishes to maintain a minimum inventory of each item. Number of items kept in items table Items(name, number,...)
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
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
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Topics Related to Attribute Values Objectives of the Lecture : To consider sorting relations by attribute values. To consider Triggers and their use for.
INTRODUCTION lecture1 1. Data base concept Data is a meaningless static value. What does 3421 means? Information is the data you process in a manner that.
MySQL Tutorial Introduction to Database. Introduction of MySQL  MySQL is an SQL (Structured Query Language) based relational database management system.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
COP-5725 Practice Exercises
©Silberschatz, Korth and Sudarshan5.1Database System Concepts - 6 th Edition Triggers Chapter 5.
Database Management COP4540, SCS, FIU Database Trigger.
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)
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
SQL- Updates, Assertions and Views. Data Definition, Constraints, and Schema Changes Used to CREATE, DROP, and ALTER the descriptions of the tables (relations)
Database System Concepts, 5th Ed. ©Sang Ho Lee Chapter 8: Application Design and Development.
Elaborated By : REPUBLIQUE TUNISIENNE MINISTERE DE L’ENSEIGNEMENT SUPERIEUR University Year :
Copyright © 2004 Pearson Education, Inc.. Chapter 24 Enhanced Data Models for Advanced Applications.
Database Constraints Ashima Wadhwa. Database Constraints Database constraints are restrictions on the contents of the database or on database operations.
Chapter 6: Integrity (and Security)
Creating Database Triggers
Constraints and Triggers
Active Database Concepts
Views, Stored Procedures, Functions, and Triggers
Prepared Statements Function and Triggers
Integrity Constraints
Introduction lecture1.
אילוצי שלמות אילוצי תחום מפתחות ומפתחות זרים טריגרים triggers
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
Triggers A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger.
Information Management
Introduction to Database
Presentation transcript:

Active DatabasesCIS 6711 Triggers: The Problem - Examples from COMPANY Database 1.Limit all salary increases to 50%. 2.Enforce policy that salaries may never decrease. 3.Maintain TotalSalary in DEPARTMENT relation as employees and their salaries change. 4.Inform a supervisor whenever a supervisee’s salary becomes larger than the supervisor’s. 5.All new hires for a given job code get the same starting salary, which is available in the STARTING_PAY table. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode) DEPARTMENT(DNO, TotalSalary, ManagerSSN) STARTING_PAY(JobCode, StartPay)

Active DatabasesCIS 6712 The Problem: Example from BANK Database Branch(BranchID, BranchName, BranchCity, Assets) Customer(CustID, CustName, CustStreet, CustCity) Account(AccountNo, BranchID, Balance) AccountCustomer(AccountNo, CustID) Loan(LoanNo, BranchID, Balance) LoanCustomer(LoanID, CustID) 6.Branch Assets are maintained as sum(Account.Balance) for each branch. 7.Overdrafts do not produce a negative balance. Instead they are treated as a loan. The account balance is set to 0 and a loan is created for the amount of the overdraft.

Active DatabasesCIS 6713 The Problem: Example from TEMPERATURE Database TEMPSCityTemp Denver25 Columbus15 Anchorage-15 EXTREMESCityHigh Temp High Date Low Temp Low Date Denver1007/30-101/20 Columbus957/522/14 Anchorage878/3-102/16 8.Given table of temperatures TEMPS, that is periodically updated, keep the table of extreme temperatures EXTREMES up to date. Create the EXTREMES table and populate with all the cities in the TEMPS table, setting the other attributes to null.

Active DatabasesCIS 6714 What is Needed? The Event-Condition-Action Model (ECA Model) Rules (or triggers) with three components: –Event triggering the rule. (insert, delete, update) E.g., an employee’s salary changes. –Condition to determine if rule action should be executed. E.g., is new Temp in City higher than HighTemp for that City? –Action to be taken. E.g., update the Department’s Total Salary.

Active DatabasesCIS 6715 What is Needed? The Event-Condition-Action Model (ECA Model), continued Actions may apply before or after the triggering event is executed. An SQL statement may change several rows. –Apply action once per SQL statement. –Apply action for each row changed by SQL statement.

Active DatabasesCIS 6716 Availability Triggers included in SQL 1999 (SQL 3) –Not in earlier standards. Included much earlier in most products: –Oracle, Sybase, DB2 –As a consequence syntax may differ from the standard.

Active DatabasesCIS 6717 The Problem: Examples from COMPANY Database 1.Limit all salary increases to 50%. 2.Enforce policy that salaries may never decrease. 3.Maintain TotalSalary in DEPARTMENT relation as employees and their salaries change. (EN, Fig (a)) 4.Inform a supervisor whenever a supervisee’s salary becomes larger than the supervisor’s. (EN, Fig (b)) 5.All new hires for a given job code get the same starting salary, which is available in the STARTING_PAY table. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode) DEPARTMENT(DNO, TotalSalary, ManagerSSN) STARTING_PAY(JobCode, StartPay)

Active DatabasesCIS COMPANY Database Limit all salary increases to 50% before trigger emp_salary_limit create trigger emp_salary_limit before update of EMPLOYEE for each row when (new.Salary > 1.5 * old.Salary) set new.Salary = 1.5 * old.Salary; EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode) “new” refers to the new tuple. “old” refers to the old tuple.

Active DatabasesCIS COMPANY Database Enforce policy that salaries may never decrease before trigger emp_salary_no_decrease create trigger emp_salary_no_decrease before update of EMPLOYEE for each row when (new.Salary < old.Salary) begin log the event; signal error condition; end Method depends on DBMS. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode)

Active DatabasesCIS COMPANY Database: All new hires for a given job code get the same starting salary, which is available in the STARTING_PAY table. before trigger emp_start_pay create trigger emp_start_pay before insert on EMPLOYEE for each row set Salary = (select StartPay fromSTARTING_PAY whereJobCode = new.JobCode) EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode) STARTING_PAY(JobCode, StartPay)

Active DatabasesCIS BANK Database: Overdrafts do not produce a negative balance. Instead they are treated as a loan. The account balance is set to 0 and a loan is created for the amount of the overdraft. after trigger overdraft_trigger

Active DatabasesCIS BANK Database: Overdrafts, continued after trigger overdraft_trigger Branch(BranchID, BranchName, BranchCity, Assets) Customer(CustID, CustName, CustStreet, CustCity) Account(AccountNo, BranchID, Balance) AccountCustomer(AccountNo, CustID) Loan(LoanNo, BranchID, Balance) LoanCustomer(LoanID, CustID) Insert a new tuple in the Loan relation, using same branch as the account. Make LoanNo the same as the AccountNo and the Balance the amount of the overdraft. Insert a new tuple in the LoanCustomer relation relating the new loan to this customer. Set the Balance of the Account tuple to 0.

Active DatabasesCIS BANK Database: Overdrafts, continued after trigger overdraft_trigger create trigger overdraft_trigger after update on Account for each row when new.balance < 0 begin insert into Loan values (new.AccountID, new.BranchID, -new.Balance); insert into LoanCustomer (selectCustID, AccountNo fromAccountCustomer AC wherenew.AccountID = AC.AccountID); update Account set Balance = 0 where Account.AccountNo = new.AccountNo; end;

Active DatabasesCIS TEMPS Database: Create the EXTREMES table and populate with all the cities in the TEMPS table, setting the other attributes to null. after triggers HighTempUpdate and LowTempUpdate TEMPS(City, Temp) EXTREMES(City, HighTemp, HighDate, LowTemp, LowDate) Need two after triggers –one for updating the high temperature ( HighTempUpdate ), –the other for updating the low temperature ( LowTempUpdate ). They will be very similar.

Active DatabasesCIS TEMPS Database: continued. High Tempearture Update create trigger HighTempUpdate after update of TEMPS for each row when (new.Temp > (selectHighTemp fromEXTREMES whereCity= new.City) or(selectHighTemp fromEXTREMES whereCity = new.City) is null )) update EXTREMES set HighTemp= new.Temp, HighDate = current date whereCity = new.City; TEMPS(City, Temp) EXTREMES(City, HighTemp, HighDate, LowTemp, LowDate) Initially HighTemp is null. Normal situation. Low Temperature similar.

Active DatabasesCIS TEMPS Database: continued. Other Problems Insert a new City into TEMPS. –Must also insert into EXTREMES. –Initial values of HighTemp, HighDate, LowTemp, LowDate must be set. Delete a City from TEMPS. –Leave City in EXTREMES. –Delete City from EXTREMES.

Active DatabasesCIS TEMPS Database: continued. Insert a new City into TEMPS : Insert City tuple into EXTREMES. Set initial values of HighTemp, HighDate, LowTemp, LowDate. create trigger NewCity after insert of TEMPS for each row insert into EXTREMES(City,HighTemp, HighDate, LowTemp, LowDate) values(new.City, new.Temp, Current Date, new.Temp, Current Date); TEMPS(City, Temp) EXTREMES(City, HighTemp, HighDate, LowTemp, LowDate)

Active DatabasesCIS TEMPS Database: continued. Delete a City from TEMPS : Delete City tuple from EXTREMES. Add Foreign Key constraint for EXTREMES. Alter table EXTREMES add constraint fk foreign key(City) references TEMPS on delete cascade; TEMPS(City, Temp) EXTREMES(City, HighTemp, HighDate, LowTemp, LowDate)

Active DatabasesCIS Problems with Use of Triggers How to guarantee set of triggers is consistent? Recursion is allowed. –How to guarantee termination? Tools are still needed to help address these problems.

Active DatabasesCIS Triggers: The Problem - 9. Another Example from COMPANY Database 1.Add a new field, Span, to the EMPLOYEE relation. For each employee, Span is the number of employees supervised. 2.Initialize Span appropriately. 3.Keep Span correct as the database changes. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode) DEPARTMENT(DNO, TotalSalary, ManagerSSN) STARTING_PAY(JobCode, StartPay) EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode, Span)

Active DatabasesCIS COMPANY Database For each employee, Span is the number of employees supervised. Idea Add the Span attribute to EMPLOYEE. Initialize the values of Span based on the current database. Create insert, delete and update triggers to keep Span up to date for an employee’s immediate supervisor. Create another update trigger to propagate the change in Span up through the rest of the hierarchy. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode, Span)

Active DatabasesCIS COMPANY Database Update Span for the immediate supervisor. create trigger EmpHire after insert on EMPLOYEE for each row update EMPLOYEE set Span = Span + 1 where SSN = new.SupervisorSSN; EMPLOYEE(Name, SSN,..., SupervisorSSN,..., Span) create trigger EmpTransfer after update of SupervisorSSN on EMPLOYEE for each row begin update EMPLOYEE set Span = Span - 1 where SSN = old.SupervisorSSN; update EMPLOYEE set Span = Span + 1 where SSN = new.SupervisorSSN; end; create trigger EmpQuit after delete on EMPLOYEE for each row update EMPLOYEE set Span = Span - 1 where SSN = old.SupervisorSSN;

Active DatabasesCIS COMPANY Database Propagate Span up the supervisor tree. EMPLOYEE(Name, SSN, Salary, DNO, SupervisorSSN, JobCode, Span) A B create trigger EmpPropagate after update of Span on EMPLOYEE for each row update EMPLOYEE set Span = Span + (new.Span - old.Span) where SSN = new.SupervisorSSN; Supervisor +(new.Span - old.Span) decrease (4 - 5) = -1 increase (4 - 3) = +1 new value

Active DatabasesCIS For each PERSON, record their mother, father and number of descendants. PERSONS(Name, Mother, Father, NumDescendants) create trigger NewMother after insert on PERSONS for each row update PERSONS set NumDescendants = NumDescendants + 1 where Name = new.Mother; create trigger NewFather after insert on PERSONS for each row update PERSONS set NumDescendants = NumDescendants + 1 where Name = new.Father; Then update the maternal and paternal ancestors. After insert, update the mother and father.

Active DatabasesCIS For each PERSON, record their mother, father and number of descendants. Update the maternal and paternal ancestors. create trigger MaternalAncestor after update of NumDescendants on PERSONS for each row update PERSONS set NumDescendants = NumDescendants + new.NumDescendants - old.NumDescendants where Name = new.Mother; At n th level of family tree, how many triggers? PERSONS(Name, Mother, Father, NumDescendants) create trigger PaternalAncestor after update of NumDescendants on PERSONS /* Similar. Just replace “Mother” with “Father.” */