Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Database Systems, CS420

Similar presentations


Presentation on theme: "Introduction to Database Systems, CS420"— Presentation transcript:

1 Introduction to Database Systems, CS420
SQL Triggers

2 Agenda Event-Condition-Action Rules Trigger Definition Options Example

3 REVIEW: Attribute-Based Check
CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) CHECK ( beer IN (SELECT name FROM Beers)), price REAL CHECK ( price <= 5.00 ) );

4 REVIEW: Tuple-Based Check
Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, CHECK (bar = ’Joe’’s Bar’ OR price <= 5.00) );

5 Timing of Checks Attribute-based checks are performed only when a value for that attribute is inserted or updated. Example: CHECK (price <= 5.00) checks every new price and rejects the modification (for that tuple) if the price is more than $5.

6 Triggers Triggers are only executed when a specified condition occurs, e.g., insertion of a tuple. Easier to implement than complex constraints.

7 Triggers: Motivation Attribute- and tuple-based checks are checked at known times, but are not powerful. Triggers let the user decide when to check for any condition.

8 Usage of Trigger Enforce referential integrity across nodes in a distributed database Automatically generate derived column values Enforce complex business rules Provide transparent event logging Gather statistics on table access Etc

9 Event-Condition-Action Rules
Another name for “trigger” is ECA rule, or event-condition-action rule. Event : typically a type of database modification, e.g., “insert on Sells.” Condition : Any SQL boolean-valued expression. Action : Any SQL statements.

10 Preliminary Example: A Trigger
Instead of using a foreign-key constraint and rejecting insertions into Sells(bar, beer, price) with unknown beers, a trigger can add that beer to Beers, with a NULL manufacturer.

11 Example: Trigger Definition
CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) VALUES(NewTuple.beer); The event The condition The action

12 Options: CREATE TRIGGER
CREATE TRIGGER <name> Or: CREATE OR REPLACE TRIGGER <name> Useful if there is a trigger with that name and you want to modify the trigger.

13 Options: The Event AFTER can be BEFORE.
INSERT can be DELETE or UPDATE. And UPDATE can be UPDATE ON a particular attribute.

14 Options: FOR EACH ROW Triggers are either “row-level” or “statement-level.” FOR EACH ROW indicates row-level; its absence indicates statement-level. Row level triggers : execute once for each modified tuple. Statement-level triggers : execute once for a SQL statement, regardless of how many tuples are modified.

15 Options: REFERENCING INSERT statements imply a new tuple (for row-level) or new table (for statement-level). The “table” is the set of inserted tuples. DELETE implies an old tuple or table. UPDATE implies both. Refer to these by [NEW OLD][TUPLE TABLE] AS <name>

16 Options: The Condition
Any boolean-valued condition. Evaluated on the database as it would exist before or after the triggering event, depending on whether BEFORE or AFTER is used. But always before the changes take effect. Access the new/old tuple/table through the names in the REFERENCING clause.

17 Options: The Action There can be more than one SQL statement in the action. Surround by BEGIN END if there is more than one. But queries make no sense in an action, so we are really limited to modifications.

18 Example: Monitoring Logons
CREATE OR REPLACE TRIGGER check_user AFTER LOGON ON DATABASE BEGIN sec_mgr.check_user; END; executes the procedure sec_mgr.check_user after a user logs onto the database

19 Another Example Using Sells(bar, beer, price) and a unary relation RipoffBars(bar), maintain a list of bars that raise the price of any beer by more than $1.

20 The Trigger CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells
The event – only changes to prices CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING OLD ROW AS ooo NEW ROW AS nnn FOR EACH ROW WHEN(nnn.price > ooo.price ) INSERT INTO RipoffBars VALUES(nnn.bar); Updates let us talk about old and new tuples Condition: a raise in price > $1 We need to consider each price change When the price change is great enough, add the bar to RipoffBars

21 Example: Track Changes to Emp_tab

22 Create Demo Table CREATE TABLE Emp_tab ( Empno NUMBER NOT NULL, Ename VARCHAR2(10), Job VARCHAR2(9), Mgr NUMBER(4), Hiredate DATE, Sal NUMBER(7,2), Comm NUMBER(7,2), Deptno NUMBER(2) NOT NULL); )

23 Insert Rows INSERT INTO Emp_tab(101, ‘e1’, ‘SP’, 104, ‘10/20/2005’, 800, 7%, 10); INSERT INTO Emp_tab(102, ‘e2’, ‘IT’, 201, ‘11/20/1990’, 900, 5%, 20); INSERT INTO Emp_tab(103, ‘e3’, ‘IT’, 201, ‘07/20/1995’, 880, 5%, 20); INSERT INTO Emp_tab(104, ‘e4’, ‘SP’, null, ‘01/20/2005’, 850, 6%, 10); INSERT INTO Emp_tab(105, ‘e5’, ‘IT’, 201, ‘04/20/2010’, 950, 5%, 20); INSERT INTO Emp_tab(201, ‘et’, ‘IT’, null, ‘12/20/1990’, 2000, 8%, 20);

24 Display Data in the Table
SELECT deptno, count(*) FROM Emp_tab GROUP BY deptno;

25 Create Log Table Set up the following data structure to track salary increase CREATE TABLE Emp_log ( Emp_id NUMBER, Log_date DATE, New_salary NUMBER, Action VARCHAR2(20));

26 Create Trigger CREATE OR REPLACE TRIGGER Log_salary_increase AFTER UPDATE ON Emp_tab REFERENCING NEW ROW as nnn FOR EACH ROW WHEN (nnn.Sal > 1000) BEGIN INSERT INTO Emp_log (Emp_id, Log_date, New_salary, Action) VALUES (nnn.Empno, SYSDATE, nnn.SAL, 'NEW SAL'); END;

27 Run an Update TRIGGER Log_salary_increase AFTER UPDATE ON Emp_tab REFERENCING NEW ROW as nnn FOR EACH ROW WHEN (nnn.Sal > 1000) BEGIN …. UPDATE Emp_tab SET Sal = Sal WHERE Deptno = 20; How many times will the trigger be fired? Since there are 4 employees in department 20, the trigger fires 4 times when this statement is entered, because 4 rows are affected

28 fires only once for each UPDATE
Another Trigger CREATE OR REPLACE TRIGGER Log_emp_update AFTER UPDATE ON Emp_tab BEGIN INSERT INTO Emp_log (Log_date, Action) VALUES (SYSDATE, 'Emp_tab COMMISSIONS CHANGED'); END; fires only once for each UPDATE

29 Clean Up -- clean the table drop table Emp_tab Table dropped.

30 Example: Enforce Security

31 Set up Data Structure CREATE TABLE Emp99 ( Empno NOT NULL NUMBER(4), Ename VARCHAR2(10), Job VARCHAR2(9), Mgr NUMBER(4), Hiredate DATE, Sal NUMBER(7,2), Comm NUMBER(7,2), Deptno NUMBER(2), Bonus NUMBER, Ssn NUMBER, Job_classification NUMBER); CREATE TABLE Company_holidays (Day DATE);

32 The Trigger CREATE OR REPLACE TRIGGER Emp_permit_changes BEFORE INSERT OR DELETE OR UPDATE ON Emp99 DECLARE Dummy INTEGER; Not_on_weekends EXCEPTION; Not_on_holidays EXCEPTION; Non_working_hours EXCEPTION;

33 The Trigger (cont.) BEGIN /* Check for weekends: */ IF (TO_CHAR(Sysdate, 'DY') = 'SAT' OR TO_CHAR(Sysdate, 'DY') = 'SUN') THEN RAISE Not_on_weekends; END IF;

34 The Trigger (cont.) /* Check for company holidays: */ SELECT COUNT(*) INTO Dummy FROM Company_holidays WHERE TRUNC(Day) = TRUNC(Sysdate); -- Discard time parts of dates IF dummy > 0 THEN RAISE Not_on_holidays; END IF;

35 The Trigger (cont.) /* Check for work hours (8am to 6pm): */ IF (TO_CHAR(Sysdate, 'HH24') < 8 OR TO_CHAR(Sysdate, 'HH24') > 18) THEN RAISE Non_working_hours; END IF;

36 The Trigger (cont.) EXCEPTION WHEN Not_on_weekends THEN Raise_application_error(-20324,'Might not change ' || 'employee table during the weekend'); WHEN Not_on_holidays THEN Raise_application_error(-20325,'Might not change ' || 'employee table during a holiday'); WHEN Non_working_hours THEN Raise_application_error(-20326,'Might not change ' || 'emp table during nonworking hours'); END;

37 Clean Up -- clean the tables drop table Emp99; drop table Company_holidays;

38 Constraints vs. Triggers
Constraints: statements about the database that are always true. A constraint applies to existing data in the table and any statement that manipulates the table Triggers: constrain what a transaction can do. A trigger does not apply to data loaded before the definition of the trigger it is not known if all data in a table conforms to the rules established by an associated trigger

39 Summary Event-Condition-Action rules Create trigger Options Event

40 END


Download ppt "Introduction to Database Systems, CS420"

Similar presentations


Ads by Google