* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download SQL Triggers
Survey
Document related concepts
Transcript
Introduction to Database Systems, CS420 SQL Triggers 1 Agenda 2 Event-Condition-Action Rules Trigger Definition Options Example 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 ) ); 3 REVIEW: Tuple-Based Check 4 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) ); Timing of Checks Attribute-based checks are performed only when a value for that attribute is inserted or updated. 5 Example: CHECK (price <= 5.00) checks every new price and rejects the modification (for that tuple) if the price is more than $5. Triggers Triggers are only executed when a specified condition occurs, e.g., insertion of a tuple. Easier to implement than complex constraints. 6 Triggers: Motivation 7 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. Usage of Trigger 8 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 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. 9 Preliminary Example: A Trigger 10 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. Example: Trigger Definition The event CREATE TRIGGER BeerTrig AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW The condition WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) The action VALUES(NewTuple.beer); 11 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. 12 Options: The Event AFTER can be BEFORE. INSERT can be DELETE or UPDATE. 13 And UPDATE can be UPDATE . . . ON a particular attribute. 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. 14 Options: REFERENCING INSERT statements imply a new tuple (for row-level) or new table (for statementlevel). 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> 15 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. 16 But always before the changes take effect. Access the new/old tuple/table through the names in the REFERENCING clause. Options: The Action There can be more than one SQL statement in the action. 17 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. Example: Monitoring Logons CREATE OR REPLACE TRIGGER check_user AFTER LOGON ON DATABASE BEGIN sec_mgr.check_user; executes the procedure sec_mgr.check_user END; after a user logs onto the database 18 Another Example 19 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. The Trigger The event – only changes to prices CREATE TRIGGER PriceTrig AFTER UPDATE OF price ON Sells REFERENCING Updates let us talk about old Condition: OLD ROW AS ooo and new tuples a raise in NEW ROW AS nnn We need to consider price > $1 each price change FOR EACH ROW WHEN(nnn.price > ooo.price + 1.00) INSERT INTO RipoffBars When the price change is great enough, add VALUES(nnn.bar); the bar to RipoffBars 20 Example: Track Changes to Emp_tab 21 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); ) 22 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); 23 Display Data in the Table SELECT FROM GROUP BY 24 deptno, count(*) Emp_tab deptno; 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)); 25 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; 26 Run an Update UPDATE SET WHERE Emp_tab Sal = Sal + 1000.0 Deptno = 20; How many times will the trigger be fired? TRIGGER Log_salary_increase AFTER UPDATE ON Emp_tab REFERENCING NEW ROW as nnn FOR EACH ROW WHEN (nnn.Sal > 1000) BEGIN …. Since there are 4 employees in department 20, the trigger fires 4 times when this statement is entered, because 4 rows are affected 27 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 28 Clean Up -- clean the table drop table Emp_tab Table dropped. 29 Example: Enforce Security 30 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); 31 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; 32 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; 33 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; 34 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; 35 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; 36 Clean Up -- clean the tables drop table Emp99; drop table Company_holidays; 37 Constraints vs. Triggers 38 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 Summary Event-Condition-Action rules Create trigger Options Event Condition Action 39 END 40