Upload
others
View
19
Download
0
Embed Size (px)
Citation preview
DBMG
Database Systems
Triggers
1
DBMG2
Triggers
Active Database SystemsOracle TriggersDifferences between Oracle and DB2 TriggersGuidelides in writing triggers in OracleTrigger Design
DBMG
Database Management Systems
Active Database Systems
3
DBMG
Active database systems
Traditional DBMS operation is passiveQueries and updates are explicitly requested by usersThe knowledge of processes operating on data is typically embedded into applications
Active database systemsReactivity is a service provided by a normal DBMSReactivity monitors specific database events and triggers actions in response
4
DBMG
Active database systems
Reactivity is provided by automatically executing rules Rules are in the form
EventConditionAction
Also called active or ECA rules
5
DBMG
Active rules
EventDatabase modification operation
ConditionPredicate on the database stateIf the condition is true, the action is executed
ActionSequence of SQL instructions or application procedure
6
DBMG
Rule engine
Component of the DBMS, in charge of Tracking eventsExecuting rules when appropriate
based on the execution strategy of the DBMSRule execution is interleaved with traditional transaction execution
7
DBMG
Example
The active rule manages reorder in an inventory stock
when the stocked quantity of a product goes below a given thresholda new order for the product should be issued
EventUpdate of the quantity on hand for product xInsert of a new product x
8
DBMG
Example
The active rule manages reorder in an inventory stock
when the stocked quantity of a product goes below a given thresholda new order for the product should be issued
ConditionThe quantity on hand is below a given thresholdand there are no pending orders for product x
ActionIssue an order with given reorder quantity for product x
9
DBMG
Applications of active rules
Internal applicationsmaintenance of complex integrity constraintsreplication managementmaterialized view maintenance
Business RulesIncorporate into the DBMS application knowledge
E.g., reorder ruleAlerters
widely used for notification
10
DBMG
Triggers
Commercial products implement active rules by means of triggersSQL provides instructions for defining triggers
Triggers are defined by means of the DDL instruction CREATE TRIGGER
Trigger syntax and semantics are covered in the SQL3 standard
Some commercial products implement different features with respect to the standard
11
DBMG
Trigger structure
EventInsert, delete, update of a tableEach trigger can only monitor events on a singletable
ConditionSQL predicate (it is optional)
ActionSequence of SQL instructionsProprietary programming language blocks
e.g. Oracle PL/SQLJava block
12
DBMG
Execution process
When the events take place [triggering]If the condition is true [evaluation]Then the action is executed [execution]
Seems very simple but…Execution modesExecution granularity
13
DBMG
Execution mode
ImmediateThe trigger is executed immediately before or afterthe triggering statement
DeferredThe trigger is executed immediately before commit
Only the immediate option is available in commercial systems
14
DBMG
Execution granularity
Tuple (or row level)One separate execution of the trigger for each tuple affected by the triggering statement
StatementOne single trigger execution for all tuples affected by the triggering statement
15
DBMG
Granularity example
Table T
Transaction statement
Trigger executionA row level trigger executes twiceA statement level trigger executes once
16
A B1 52 98 20
UPDATE TSET A=A+1WHERE B<10;
DBMG
Database Management Systems
Oracle Triggers
17
DBMG
Trigger syntax
18
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
Mode is BEFORE or AFTERAlso INSTEAD OF but it should be avoided
19
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
19
DBMG
Trigger syntax
Event ON TargetTable is INSERTDELETEUPDATE [OF ColumnName]
20
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
FOR EACH ROW specifies row level execution semantics
If omitted, the execution semantics is statement level
21
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
The old and new states of the row triggering a row level trigger may be accessed by means of the
OLD.ColumnName variableNEW.ColumnName variable
22
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
To rename the state variablesREFERENCING OLD AS OldVariableName
similarly for NEW
23
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
Only for row level execution semantics (i.e., FOR EACH ROW)
A condition may be optionally specifiedThe old and new state variables may be accessed
24
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger syntax
The action isa sequence of SQL instructionsa PL/SQL block
No transactional and DDL instructions25
CREATE TRIGGER TriggerNameMode Event {OR Event }ON TargetTable[[ REFERENCING ReferenceName]FOR EACH ROW[WHEN Predicate]]PL/SQL Block
DBMG
Trigger semantics
Execution modesimmediate beforeimmediate after
Granularity isrow (tuple)statement
Execution is triggered by insert, delete, or update statements in a transaction
26
DBMG
Execution algorithm
1. Before statement triggers are executed2. For each tuple in TargetTable affected by the
triggering statementa) Before row triggers are executedb) The triggering statement is executed
+ integrity constraints are checked on tuplesc) After row triggers are executed
3. Integrity constraints on tables are checked4. After statement triggers are executed
27
DBMG
Trigger semantics
The execution order for triggers with the same event, mode and granularity is not specified
it is a source of non determinismWhen an error occurs
rollback of all operations performed by the triggersrollback of the triggering statement in the triggering transaction
28
DBMG
Non termination
Trigger execution may activate other triggersCascaded trigger activation may lead to non termination of trigger execution
A maximum length for the cascading trigger execution may be set
default = 32 triggersIf the maximum is exceeded
an execution error is returned
29
DBMG
Mutating tables
A mutating table is the table modified by the statement (i.e., event) triggering the triggerThe mutating table
cannot be accessed in row level triggersmay only be accessed in statement triggers
Limited access on mutating tables only characterizes Oracle applications
accessing mutating tables is always allowed in SQL3
30
DBMG
Example
Trigger to manage reorder in an inventory stockwhen the stocked quantity of a product goes below a given thresholda new order for the product should be issued
The following database schema is givenInventory (Part#, QtyOnHand, ThresholdQty,
ReorderQty)PendingOrders(Part#, OrderDate, OrderedQty)
31
DBMG
Example
Trigger to manage reorder in an inventory stockwhen the stocked quantity of a product goes below a given thresholda new order for the product should be issued
EventUpdate of the quantity on hand for product xInsert of a new product x
Execution semanticsAfter the modification eventSeparate execution for each row of the Inventory table
32
DBMG
Trigger example
33
CREATE TRIGGER ReorderAFTER UPDATE OF QtyOnHand OR INSERT ON InventoryFOR EACH ROW
DBMG
Example
Trigger to manage reorder in an inventory stockwhen the stocked quantity of a product goes below a given thresholda new order for the product should be issued
ConditionThe quantity on hand is below a given threshold
34
DBMG
Trigger example
35
CREATE TRIGGER ReorderAFTER UPDATE OF QtyOnHand OR INSERT ON InventoryFOR EACH ROWWHEN (NEW.QtyOnHand < NEW.ThresholdQty)
DBMG
Example
Trigger to manage reorder in an inventory stockwhen the stocked quantity of a product goes below a given thresholda new order for the product should be issued
ConditionThe quantity on hand is below a given thresholdand there are no pending orders for product x
This part cannot be introduced into the WHEN clause
ActionIssue an order with given reorder quantity for product x 36
DBMG
Example: Trigger body
37
DECLAREN number;BEGINselect count(*) into Nfrom PendingOrderswhere Part# = :NEW.Part#;If (N=0) then
insert into PendingOrders(Part#,OrderedQty,OrderDate)values (:NEW.Part#, :NEW.ReorderQty, SYSDATE);
end if;END;
DBMG
Complete trigger example
38
CREATE TRIGGER ReorderAFTER UPDATE OF QtyOnHand OR INSERT ON InventoryFOR EACH ROWWHEN (NEW.QtyOnHand < NEW. ThresholdQty)DECLAREN number;BEGINselect count(*) into Nfrom PendingOrderswhere Part# = :NEW.Part#;If (N==0) then
insert into PendingOrders(Part#,OrderedQty,OrderDate)values (:NEW.Part#, :NEW.ReorderQty, SYSDATE);
end if;END;
DBMG
Database Management Systems
Concise comparison betweenOracle and DB2 Triggers
51
DBMG
Differences between Oracle and DB2Oracle DB2
Reference to Old_Table and New_Table in statement triggers No Yes
When clause in statement triggers No Yes
Execution order between row and statement triggers with same mode
Specified Arbitrary
Execution order between triggers with same event, mode and granularity
Unspecified Creation Order
More than one triggering event allowed Yes No
Forbidden access to the mutating table Yes for row triggers
No
Availability of the instead semantics Yes No
Database modifications allowed in before triggers
Yes Only NEW variables52
DBMG
Database Management Systems
Guidelines in writing triggers in Oracle
53
DBMG
Guidelines in writing triggers in Oracle
Execution Mode INSTEAD OF is allowed in Oracle but it should be avoidedUsage of before triggers in Oracle to be compliant with the standard
Modifications of the NEW variable in tuples affected by the triggering statement are allowed in before triggersOther databases modifications apart those reported in the previous point are not allowed on before triggers Before triggers cannot trigger other triggers
54
DBMG
Database Management Systems
Trigger Design
55
DBMG
Trigger design
The design of a single trigger is usually simpleIdentify
execution semanticseventcondition (optional)action
56
DBMG
Trigger design
Understanding mutual interactions among triggers is more complex
The action of one trigger may be the event of a different trigger
Cascaded executionIf mutual triggering occurs
Infinite execution is possible
57
DBMG
Trigger execution properties
TerminationFor an arbitrary database state and user transaction, trigger execution terminates in a final state (also after an abort)
ConfluenceFor an arbitrary database state and user transaction, trigger execution terminates in a unique final state, independently of the execution order of triggers
Termination is the most important propertyConfluence is enforced by deterministic trigger execution
58
DBMG
Guaranteeing termination
Termination is guaranteed at run time by aborting trigger execution after a given cascading lengthTermination may be verified at design time by means of the triggering graph
a node for each triggera directed edge Ti Tj if trigger Ti is performing an action triggering trigger Tj
A cycle in the graph shows potential non terminating executions
59TjTi
DBMG
Example
Trigger managing salary amountsWhen a given average salary value is exceeded, a salary reduction is automatically enforced
The following table is givenEmployee (Emp#, Ename, …, Salary)
EventUpdate of the Salary attribute in EmployeeInsert into Employee
Will write only trigger for update
60
DBMG
Example
Trigger managing salary amountsWhen a given average salary value is exceeded, a salary reduction is automatically enforced
The following table is givenEmployee (Emp#, Ename, …, Salary)
Execution semanticsAfter the modification eventsSeparate execution for each update instruction
No condition for execution
61
DBMG
Example
62
CREATE TRIGGER SalaryMonitorAFTER UPDATE OF Salary ON EmployeeFOR EACH STATEMENTBEGINupdate Employeeset Salary = Salary * Kwhere 2500 < (select AVG (Salary) from Employee);
END;
SalaryMonitorThe value of K may beK = 0.9 execution terminatesK = 1.1 infinite execution
DBMG
Trigger applications
Internal applicationsmaintenance of complex integrity constraintsreplication managementmaterialized view maintenance
Business RulesIncorporate into the DBMS application knowledge
E.g., reorder ruleAlerters
widely used for notification
63
DBMG
Triggers for constraint management
Triggers are exploited to enforce complex integrity constraintsDesign procedure1. Write the constraint as a SQL predicate
It provides a condition for the trigger execution2. Identify the events which may violate the
constrainti.e. the condition
3. Define the constraint management technique in the action
64
DBMG
Design example (1)
The following tables are givenSupplier S (S#, SName, …)Part P (P#, PName, …)Supply SP (S#, P#, Qty)
Constraint to be enforcedA part may be supplied by at most 10 different suppliers
65
DBMG
Design example (1)
Constraint predicate
set of parts violating the constraintEvents
insert on SPupdate of P# on SP
Actionreject the violating transaction
66
select P#from SPgroup by P#having count(*) > 10
DBMG
Design example (1)
Execution semanticsafter the modificationstatement level
to capture the effect of the entire modification(Oracle) to allow access to the mutating table
(Oracle) No conditionThe condition cannot be specified in the WHEN clauseIt is checked in the trigger body
Design for Oracle trigger semantics
67
DBMG68
Design example (1)CREATE TRIGGER TooManySuppliersAFTER UPDATE OF P# OR INSERT ON SPDECLAREN number;BEGINselect count(*) into Nfrom SPwhere P# IN (select P# from SP
group by P#having count(*) > 10);
if (N <> 0) thenraise_application_error (xxx, ‘constraint violated’);
end if;END;
DBMG
Design example (2)
The following tables are givenSupplier S (S#, SName, …)Part P (P#, PName, …)Supply SP (S#, P#, Qty)
Constraint to be enforcedThe quantity of a product supply cannot be larger than 1000. If it is larger, trim it to 1000.
Check constraints do not allow compensating actions
Implement with a trigger
69
DBMG
Design example (2)
Constraint predicateQty > 1000It is also the trigger condition
Eventsinsert on SPupdate of Qty on SP
ActionQty = 1000
70
DBMG
Design example (2)
Execution semanticsbefore the modification takes place
its effect can be changed before the constraint is checked
row leveleach tuple is modified separately
71
DBMG72
Design example (2)
CREATE TRIGGER ExcessiveQtyBEFORE UPDATE OF Qty OR INSERT ON SPFOR EACH ROWWHEN (NEW.Qty > 1000)BEGIN:NEW.Qty := 1000;END;
DBMG
Triggers for materialized view maintenance
Materialized views are queries persistently stored in the database
provide increased performancecontain redundant information
e.g., aggregate computationsTriggers are exploited to maintain redundant data
Propagate data modifications on tables to materialized view
7373
DBMG
Design example (3)
TablesStudent S (SId, SName, DCId)Degree course DC (DCId, DCName)
Materialized viewEnrolled students ES (DCId, TotalStudents)
For each degree course, TotalStudents counts the total number of enrolled studentsDefined by query
74
SELECT DCId, COUNT(*)FROM SGROUP BY DCId;
74
DBMG
Design example (3)
TablesStudent S (SId, SName, DCId)Degree course DC (DCId, DCName)
Materialized viewEnrolled students ES (DCId, TotalStudents)
For each degree course, TotalStudents counts the total number of enrolled students
A new degree course is inserted in materialized view ES when the first student is enrolled in itA degree course is deleted from ES when the last student quits it
7575
DBMG
Design example (3)
Database schemaS (SId, SName, DCId)DC (DCId, DCName)ES (DCId, TotalStudents)
Propagate modifications on table S to materialized view (table) ES
Inserting new tuples into SDeleting tuples from SUpdating the DCId attribute in one or more tuples of S
7676
DBMG
Design example (3)
Design three triggers to manage separately each data modification
Insert trigger, delete trigger, update triggerAll triggers share the same execution semantics
Execution semanticsafter the modification takes place
Table ES is updated after table S has been modifiedrow level
Separate execution for each tuple of table Ssignificantly simpler to implement
7777
DBMG
Insert trigger (3)
Eventinsert on S
No conditionIt is always executed
Actionif table ES contains the DCId in which the student is enrolled
increment TotalStudentsotherwise
add a new tuple in table ES for the degree course, with TotalStudents set to 1
7878
DBMG79
Insert trigger (3)
CREATE TRIGGER InsertNewStudentAFTER INSERT ON SFOR EACH ROWDECLAREN number;BEGIN--- check if table ES contains the tuple for the degree--- course NEW.DCId in which the student enrollsselect count(*) into Nfrom ESwhere DCId = :NEW. DCId;
79
DBMG80
Insert trigger (3)
if (N <> 0) then--- the tuple for the NEW.DCId degree course is--- available in ESupdate ESset TotalStudents = TotalStudents +1where DCId = :NEW.DCId;
else--- no tuple for the NEW.DCId degree course is--- available in ESinsert into ES (DCId, TotalStudents)values (:NEW.DCId, 1);
end if;END; 80
DBMG
Delete trigger (3)
Eventdelete from S
No conditionIt is always executed
Actionif the student was the only student enrolled in the degree course
delete the corresponding tuple from ESotherwise
decrement TotalStudents
8181
DBMG82
Delete trigger (3)
CREATE TRIGGER DeleteStudentAFTER DELETE ON SFOR EACH ROWDECLAREN number;BEGIN--- read the number of students enrolled on--- the degree course OLD.DCIdselect TotalStudents into Nfrom ESwhere DCId = :OLD.DCId;
82
DBMG83
Delete trigger (3)
if (N > 1) then--- there are many enrolled studentsupdate ESset TotalStudents = TotalStudents – 1where DCId = :OLD.DCId;
else--- there is a single enrolled studentdelete from ESwhere DCId = :OLD.DCId;
end if;END;
83
DBMG
Update trigger (3)
EventUpdate of DCId on S
No conditionIt is always executed
Actionupdate table ES for the degree course where the student was enrolled
decrement TotalStudents, or delete tuple if last student
update table ES for the degree course where the student is currently enrolled
increment TotalStudents, or insert new tuple if first student
8484
DBMG85
Update trigger (3)
CREATE TRIGGER UpdateDegreeCourseAFTER UPDATE OF DCId ON SFOR EACH ROWDECLAREN number;BEGIN--- read the number of students enrolled in --- degree course OLD.DCIdselect TotalStudents into Nfrom ESwhere DCId = :OLD.DCId;
85
DBMG86
Update trigger (3)
if (N > 1) then--- there are many enrolled studentsupdate ESset TotalStudents = TotalStudents – 1where DCId = :OLD.DCId;
else--- there is a single enrolled studentdelete from ESwhere DCId = :OLD.DCId;
end if;
86
DBMG87
Update trigger (3)
--- check if table ES contains the tuple for the degree--- course NEW.DCId in which the student is enrolledselect count(*) into Nfrom ESwhere DCId = :NEW. DCId;
87
DBMG88
Update trigger (3)
if (N <> 0) then--- the tuple for the NEW.DCId degree course is available in ES
update ESset TotalStudents = TotalStudents +1where DCId = :NEW.DCId;
else--- no tuple for the NEW.DCId degree course is available in ES
insert into ES (DCId, TotalStudents)values (:NEW.DCId, 1);
end if;END;
88