Академический Документы
Профессиональный Документы
Культура Документы
Introduction
triggering event
DB
triggered action
think of examples
Rules
specify actions that are automatically triggered by certain events generalised model: EVENT-CONDITION-ACTION (ECA)
event(s): database update operation(s) condition: determines whether the rule is to be executed after the event occurred action: action to be taken
SQL command(s) external program
Example - pseudocode
consider the following relations: Employee ( Id, Name, Address, , Salary, Dept, ) Department (Dept, Name, , Tot_Sal, ) Tot_Sal represents the salary of all the employees in the department
Activity
design similar rules for the following cases:
updating the salary of certain employees deleting certain employees
Observation
the situation in the previous example should not occur in an industrial database
the total salary per department can be computed from the individual salary of each employee, therefore should not be explicitly represented the example was used for didactic reasons however, could you think of real life situations where such a design would be useful?
Increase salary
CREATE RULE IncreaseSal AFTER UPDATE OF Salary ON Employee FOR EACH ROW UPDATE Employee SET Salary = Salary + (NEW.Salary - OLD.Salary) * 0.1 WHERE Manager = NEW.Id ;
10
condition
could be empty when solely the event triggers row-level rule: the rule is triggered for each tuple for which the condition is satisfied statement-level rule: the rule is triggered only once for each triggering statement
action
SQL statement or external procedure
11
tuple level
inform the manager for every item more expensive than 1000 removed from the safe
12
13
immediate: evaluated as part of the triggering transaction (before, after or instead of executing the triggering event) deferred: evaluated at the end of the triggering transaction detached: evaluated as a separate transaction
problems
determining consistency and termination
14
action
condition
transaction T
triggering event
DELETE UPDATE INSERT INTO rel1 VALUES (); SELECT UPDATE SELECT ...
DB
15
16
triggers
allow the association of user supplied procedures (functions) with database events
17
Rules in Postgres
CREATE RULE <name> AS ON <event> TO <object> [ WHERE <condition> ] DO [ INSTEAD ] [ <action> | NOTHING ]
<event> ::= SELECT | UPDATE | INSERT | DELETE <object> ::= <table> | <table>.<column> <condition> ::= <SQL statement> /* new and old */ <action> ::= <SQL statement> /* new and old */
18
the rules mechanism is used to implement the view system for further details refer to the lab handouts
19
Triggers in Postgres
CREATE TRIGGER <name> { BEFORE | AFTER } { <event> [OR <event> ...] } ON <table> FOR EACH { ROW | STATEMENT } EXECUTE PROCEDURE <function> ( <arguments> )
<event> ::= UPDATE | INSERT | DELETE <function> ::= <user supplied function> statement triggers are not (yet) implemented
20
21