Download as pdf or txt
Download as pdf or txt
You are on page 1of 95

Ch2 Active Database Systems {1{

SC

Active Database Systems

 An integrated facility for creating and executing production


rules from within a database system
 A typical database production rule:
when event
if condition
then action
 Powerful and uniform mechanism for:
{ Constraint enforcement
{ Derived data maintenance
{ Alerting
{ Authorization checking
{ Version management
{ Resource management
{ Knowledge management

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {2{
SC

Outline of Slides

 Chapter 2: Syntax and Semantics


{ A Relational Prototype: Starburst
{ Two Relational Systems: Oracle and DB2
{ An Object-Oriented Prototype: Chimera
{ Features and Products Overview

 Chapter 3: Applications
{ Applications of Active Rules
{ Deriving Active Rules for Constraint Management
{ Deriving Active Rules for View Maintenance
{ Rules for Replication
{ Rules for Work ow Management
{ Business Rules

 Chapter 4: Design Principles


{ Properties of Active Rules and Rule Analysis
{ Rule Modularization
{ Rule Debugging and Monitoring
{ Rule Design: IDEA Methodology (pointer)
{ Conclusions

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {3{
SC

A Relational Example: Starburst

 Done at IBM Almaden


 Chief Engineer: Jennifer Widom
 Syntax based on SQL
 Semantics is set-oriented
{ Triggering based on (arbitrary)
sets of changes
{ Actions perform (arbitrary) sets
of changes
{ Conditions and actions can refer to
sets of changes
 Instructions: create, drop,
alter, deactivate, activate

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {4{
SC

Rule Creation

<Starburst-rule> ::=CREATE RULE <rule-name>


ON <table-name>
WHEN <triggering-operations>
[ IF <SQL-predicate> ]
THEN <SQL-statements>
[ PRECEDES <rule-names> ]
[ FOLLOWS <rule-names> ]

<triggering-operation> ::= INSERTED j DELETED j


UPDATED [ ( <column-names> ) ]

 Triggering operations:
{ inserted, deleted, updated,
updated(c1,..,cn )

 Condition: arbitrary SQL predicate


 Actions: any database operations
insert, delete, update, select,
rollback, create table, etc.

 Precedes and Follows: for rule ordering

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {5{
SC

Example Rules
Salary control rule
CREATE RULE SalaryControl ON Emp
WHEN INSERTED, DELETED, UPDATED (Sal)
IF (SELECT AVG (Sal) FROM Emp ) > 100
THEN UPDATE Emp
SET Sal = .9 * Sal

High paid rule


CREATE RULE HighPaid ON Emp
WHEN INSERTED
IF EXISTS (SELECT * FROM INSERTED
WHERE Sal > 100)
THEN INSERT INTO HighPaidEmp
(SELECT * FROM INSERTED
WHERE Sal > 100)
FOLLOWS AvgSal

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {6{
SC

Transition Tables

 Logical tables storing changes that triggered rule


 Can appear anywhere in condition and action
 References restricted to triggering operations:
 inserted
deleted
new-updated
old-updated

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {7{
SC

Rule Execution Semantics

 Rules processed at commit point of each transaction


 Transaction's changes are initial triggering transition
 Rules create additional transitions which may trigger other
rules or themselves
 Each rule looks at set of changes since last considered
 When multiple rules triggered, pick one based on partial or-
dering

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {8{
SC

Example of rule execution

 Initial state:
Employee Sal
Stefano 90
Patrick 90
Michael 110
 Transaction inserts tuples (Rick,150) and (John,120)
Employee Sal
Stefano 90
Patrick 90
Michael 110
Rick 150
John 120
 Rule SalaryControl runs:
Employee Sal
Stefano 81
Patrick 81
Michael 99
Rick 135
John 108

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {9{
SC

Rule Execution Semantics (2)


 Rule SalaryControl runs again:
Employee Sal
Stefano 73
Patrick 73
Michael 89
Rick 121
John 97
 Rule HighPaid runs eventually, and inserts into HighPaid only
one tuple:
Employee Sal
Rick 122

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {10{
SC

Oracle

 Supports general-purpose triggers, developed according to


preliminary documents on the SQL3 standard.
 Actions contain arbitrary PL/SQL code.
 Two granularities: row-level and statement-level.
 Two types of immediate consideration: before and after.
 Therefore: 4 Combinations:
BEFORE ROW
BEFORE STATEMENT
AFTER ROW
AFTER STATEMENT

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {11{
SC

Syntax

<Oracle-trigger> ::= CREATE TRIGGER <trigger-name>


f BEFORE j AFTERg <trigger-events>
ON <table-name>
[ [ REFERENCING <references> ]
FOR EACH ROW
[ WHEN ( <condition> ) ] ] <PL/SQL block>

<trigger event> ::= INSERT j DELETE j UPDATE


[ OF <column-names> ]

<reference> ::= OLD AS <old-value-tuple-name> j


NEW AS <new-value-tuple-name>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {12{
SC

Trigger Processing

1. Execute the BEFORE STATEMENT trigger.


2. For each row a ected:
(a) Execute the BEFORE ROW trigger.
(b) Lock and change the row.
(c) Perform row-level referential integrity and assertion check-
ing.
(d) Execute the AFTER ROW trigger.
3. Perform statement-level referential integrity and assertion check-
ing.
4. Execute the AFTER STATEMENT trigger.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {13{
SC

Example Trigger in Oracle

Reorder rule
CREATE TRIGGER Reorder
AFTER UPDATE OF PartOnHand ON Inventory
WHEN (New.PartOnHand < New.ReorderPoint)
FOR EACH ROW
DECLARE NUMBER X
BEGIN
SELECT COUNT(*) INTO X
FROM PendingOrders
WHERE Part = New.Part;
IF X=0
THEN
INSERT INTO PendingOrders
VALUES (New.Part, New.OrderQuantity, SYSDATE)
END IF;
END;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {14{
SC

Example of execution

 Initial state of Inventory:


Part PartOnHand ReorderPoint ReorderQuantity
1 200 150 100
2 780 500 200
3 450 400 120
 PendingOrders is initially empty
 Transaction (executed on October 10, 1996):
T1: UPDATE Inventory
SET PartOnHand = PartOnHand - 70
WHERE Part = 1
 After the execution of trigger Reorder, insertion into Pendin-
gOrders of the tuple (1,100,1996-10-10)
 Another transaction (executed on the same day)
T2: UPDATE Inventory
SET PartOnHand = PartOnHand - 60
WHERE Part >= 1
 The trigger is executed upon all the tuples, and the condition
holds for parts 1 and 3, but a new order is issued for part 3,
resulting in the new tuple (3,120,1996-10-10).

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {15{
SC

DB2
 Triggers for DB2 Common Servers de ned at the IBM Al-
maden Research center in 1996.
 In uential on the SQL3 standard.
 As in Oracle: either BEFORE or AFTER their event, and
either a row- or a statement-level granularity.
 Syntax:
<DB2-trigger> ::= CREATE TRIGGER <trigger-name>
f BEFORE j AFTER g <trigger-event>
ON <table-name>
[ REFERENCING <references> ]
FOR EACH f ROW j STATEMENT g
WHEN ( <SQL-condition> )
<SQL-procedure-statements>

<trigger-event> ::= INSERT j DELETE j UPDATE


[ ON <column-names> ]

<reference> ::= OLD AS <old-value-tuple-name> j


NEW AS <new-value-tuple-name> j
OLD TABLE AS <old-value-table-name> j
NEW TABLE AS <new-value-table-name>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {16{
SC

Semantics of DB2 Triggers


 Before-triggers:
{ Used to detect error conditions and to condition input
values (assign values to NEW transition variables).
{ Read the database state prior to any modi cation made
by the event.
{ Cannot modify the database by using UPDATE, DELETE,
and INSERT statements (so they do not recursively acti-
vate other triggers).
 Several triggers (with either row- or statement-level granular-
ity) can monitor the same event.
 A system-determined total order takes into account the trig-
gers' de nition time; row- and statement-level triggers are
intertwined in the total order.
 General trigger processing algorithm after statement A:
1. Suspend the execution of A, and save its working stor-
age on a stack.
2. Compute transition values (OLD and NEW) relative
to event E .
3. Consider and execute all before-triggers relative to event
E , possibly changing the NEW transition values.
4. Apply NEW transition values to the database, thus
making the state change associated to event E e ec-
tive.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {17{
SC

5. Consider and execute all after-triggers relative to event


E . If any of them contains an action A that activates i

other triggers, then invoke this processing procedure


recursively for A . i

6. Pop from the stack the working storage for A and con-
tinue its evaluation.
 Revised trigger processing with integrity checking:

4. Apply the NEW transition values to the database, thus


making the state change associated to event E e ec-
tive. For each integrity constraint IC violated by the
current state, consider the action A that compensates
j

the integrity constraint IC .


a. Compute the transition values (OLD and NEW)
relative to A . j

b. Execute the before-triggers relative to A , possibly j

changing the NEW transition values.


c. Apply NEW transition values to the database, thus
making the state change associated to A e ective. j

d. Push all after-triggers relative to action A into a j

queue of suspended triggers.


Until a quiescent point is reached where all the in-
tegrity constraints violated in the course of the com-
putation are compensated.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {18{
SC

Examples of triggers
Supplier rule
CREATE TRIGGER OneSupplier
BEFORE UPDATE OF Supplier ON Part
REFERENCING NEW AS N
FOR EACH ROW
WHEN (N.Supplier IS NULL)
SIGNAL SQLSTATE '70005'
('Cannot change supplier to NULL')

Audit rule
CREATE TRIGGER Audit
AFTER UPDATE ON Parts
REFERENCING OLD TABLE AS OT
FOR EACH STATEMENT
INSERT INTO AuditSupplier
VALUES(USER, CURRENT DATE,
(SELECT COUNT(*) FROM OT))

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {1{
SC

An Object-Oriented System: Chimera

 Structure of the IDEA Consortium:


{ Prime Contractor: BULL
{ Partners: Politecnico, ECRC, INRIA, TxT (Italy), SEMA
(Spain)
{ Associate Partners: Univ. Bonn, BIM (Belgium), PTT
(Holland)

 Objectives of the IDEA Project:


{ Designing and implementing prototypes of Active DOOD
systems
{ Producing a methodology and tools for helping the use of
Active DOOD technology
{ Transferring experience to ADS (Bull)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {2{
SC

Chimera: the Conceptual Interface

 Chimera [the Oxford Dictionary of Current English]:


1. Greek myth: monster with a lion's head, a goat's body,
and a serpent's tail.
2. Comp.Sc.: new generation database language integrating
the paradigms of object-oriented, deductive, and active
databases.
 Relatives of Chimera:
{ Elisa Bertino = OO = lion
{ Stefano Ceri = ACT = serpent
{ Rainer Manthey = DED = goat
 Features:
{ Object-oriented conceptual model (data + operations)
{ Declarative rule language
{ Reactive processing (triggers)
 More information in www.elet.polimi.it/idea

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {3{
SC

Alternatives in Reactive Processing

 Issues in reactive processing:


{ Choice of event types.
{ Complexity of event calculus.
{ Execution modes.
{ Event e ect composition modes.
{ Event consumption modes.
{ Binding of database objects to events.
{ Binding between rule components.
{ Priorities.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {4{
SC

The Designers' Dilemma

 Choosing a semantics for active rules.


Alternatives:
{ One semantics: which one?
{ Multiple, parametric semantics: how feasible?

 The designers' beliefs:


{ One semantics is too limited (cannot cover all applica-
tions).
{ Alternatives should be limited and under control.
{ Triggers could be system-generated to implement declar-
ative aspects of Chimera.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {5{
SC

Trigger's Syntax

<de ne-trigger> ::= de ne <option> trigger <trigger-name>


[ for <class-name> ]
events <triggering-events>
condition <formula>
actions <procedural-expression>
[ f before j after g <trigger-names> ]
end

<triggering-event> ::= create j delete j


modify [ ( <attr-name> ) ]

<option> ::= [ <consumption-opt> ] [ <execution-opt> ]


<consumption-opt> ::= event-consuming j event-preserving
<execution-opt> ::= deferred j immediate

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {6{
SC

Features of Triggers in Chimera

 Trigger options:
{ immediate / deferred
{ consuming / event-preserving
 Events:
{ create, create tmp, delete,
make persistent, generalize,
modify, specialize, query

 Condition:
{ An arbitrary declarative formula of the language
 Actions:
{ Update primitives, operations, display queries, externally
de ned procedures, rollback command

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {7{
SC

Trigger Processing

 A rule is triggered when one of its triggering events has


occurred.
 Trigger processing (either immediate or deferred) consists of:
{ Ordering triggered rules according to priorities.
{ Selecting one of the highest priority rules (nondetermin-
istically).
{ Then, this rule is considered by evaluating its condition
(becomes untriggered).
{ If the condition is true or it produces some bindings, then
the reaction is executed; Actions composing the reaction
are executed in sequence.
 Until a xpoint is reached where no rule is triggered.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {8{
SC

Execution Modes

 Immediate: after the completion of the raising event.


 Deferred: at the end of a transaction (default).
 Each trigger has its own execution mode.
 Transaction commands can change modes, setting all triggers
to immediate or deferred.

Event Formulas
 Syntax: occurred(event,variable).
 Semantics: binds OIDs of objects which were a ected by the
event, according to several modes.
 Every binding represents an \event instance".

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {9{
SC

Event Consumption Modes

 Consuming: Every event instance is


considered by each rule at the rst possible rule consideration,
then disregarded.
 Preserving: All event instances are
considered by each rule at all rule considerations.

Net E ect of Event Instances


 Net e ect: Some event instances disappear due to event
combinations, such as insert, delete of the same object.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {10{
SC

Examples of triggers
Adjust salary rule
de ne trigger AdjustSalary for Employee
events create, modify(Salary)
condition Self.Salary > Self.Mgr.Salary
actions modify(Employee.Salary,Self,Self.Mgr.Salary)
end;

Immediate adjust salary rule


de ne immediate trigger ImmAdjustSalary for Employee
events create, modify(Salary)
condition occurred(create, modify(Salary),Self)
Self.Salary > Self.Mgr.Salary
actions modify(Employee.Salary,Self,Self.Mgr.Salary)
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {11{
SC

Examples of triggers (2)


Special employee rule
de ne immediate event-preserving trigger SpEmp for Employee
events modify(Salary)
condition occurred(modify(Salary),Self)
Self.Salary - old(Self.Salary) > 5000
actions create(specialEmp, [Self.name], Z)
before AdjustSalary
end;

Excessive salary rule


de ne trigger ExcessiveSalary
events create(Employee), modify(Employee.Salary),
modify(Department.Employees)
condition Department(Y), Y.Name="toys", Employee(X),
X in Y.Employees, sum(X.Salary) > 500000
action rollback
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {1{
SC

Features of Active Databases

 Events
{ Database state changes
{ Retrievals
{ Time-related
{ Application-de ned (external)
 Condition
{ Database predicate
{ Database query
{ Application procedure (external?)
 Actions
{ Database modi cations
{ Database retrieval operations
{ Other database commands
{ Application procedures

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {2{
SC

Consideration

 Immediate:
Individual update primitives of the
Data Manipulation Language
(e.g.: Insert, Delete, Update)
{ Before
{ After
{ Instead of
 Deferred:

{ User-de ned points


{ End transaction
 Detached:
Executed as separate transaction
May have causal dependencies on spawning transaction

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {3{
SC

Granularity and Transition Values

 Granularity of DB state change


{ Record (tuple-level)
{ Set of records(statement-level)

 Transition Values
{ Single tuple's OLD and NEW values
{ Collective changes:
INSERTED, DELETED
{ Updates treated:
 Explicitly OLD/NEW UPDATED
 As deleted followed by inserts

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {4{
SC

Priorities, Commands, Structuring

 Prioritization
{ None
{ Partial Order
{ Total Order

 Rule activation and deactivation


{ None
{ Under DBA Control
{ Under User Control
{ Performed by rules

 With rule sets (grouping)


and set-level commands

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {5{
SC

Informix (see: Widom-Ceri's book)

 Available since Version 6.


 Multiple triggers, single rule.
 Syntax:

<Informix trigger> ::=


CREATE TRIGGER <trigger name>
<trigger event> ON <table name>
[BEFORE [<condition>] (<actions>)]
[[REFERENCING <references>]
FOR EACH ROW [<condition>] (<actions>)]
[AFTER [<condition>] (<actions>)]

<trigger event> ::= INSERT | DELETE |


UPDATE [OF <column names>]

<reference> ::=
OLD AS <old value tuple name> |
NEW AS <new value tuple name>

<condition> ::= WHEN (<predicate>)

<action> ::= <insert statement>


| <delete statement>
| <update statement>
| <procedure call>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {6{
SC

Example Trigger in Informix

CREATE TRIGGER up price


UPDATE OF unit price ON stock
REFERENCING OLD AS pre,
NEW AS post
FOR EACH ROW WHEN
(post.unit price >
pre.unit price * 2)
INSERT INTO warn tab VALUES
(pre.stock num, pre.order num,
pre.unit price, post.unit price,
CURRENT)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {7{
SC

Ingres (see: Widom-Ceri's book)

 Available in Knowledge
Management Extension.
 Semantics: AFTER, tuple-level.
 Syntax:

<Ingres rule> ::=


CREATE RULE <rule name>
AFTER <rule events> ON <table name>
[REFERENCING <references>]
WHERE <predicate>
EXECUTE PROCEDURE <procedure call>

<rule event> ::= INSERT | DELETE |


UPDATE [(<column name>)]

<reference> ::=
OLD AS <old value tuple name> |
NEW AS <new value tuple name>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {8{
SC

Example Trigger in Ingres

CREATE RULE emp delete


AFTER DELETE FROM EMPLOYEE
EXECUTE PROCEDURE manager emp track
(ename = OLD.name,
mname = NEW.manager)
CREATE PROCEDURE manager emp track
(ename VARCHAR (30),
mname VARCHAR (30)) AS
BEGIN
UPDATE manager
SET employees = employees - 1
WHERE name = :mname;
INSERT INTO mgrlog VALUES
(:mname, :ename);
END;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {9{
SC

RDB (see: Widom-Ceri's book)

 Semantics:
{ Both BEFORE and AFTER
{ Both Statement and Tuple Level
 Syntax:

<Rdb trigger> ::=


CREATE TRIGGER <trigger name>
{BEFORE | AFTER} <trigger event>
ON <table name>
[REFERENCING <references>]
WHEN <predicate> (<statement>)
[FOR EACH ROW]

<trigger event> ::= INSERT | DELETE |


UPDATE [OF <column names>]

<reference> ::=
OLD AS <old value tuple name> |
NEW AS <new value tuple name>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {10{
SC

Example Trigger in RDB

CREATE TRIGGER
code cascade update
BEFORE UPDATE OF code
ON work status
REFERENCING OLD AS old work status
NEW AS new work status
(UPDATE employee E
SET E.code = NEW.code
WHERE E.code = OLD.code)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {11{
SC

Sybase (see: Widom-Ceri's book)


 Since Sybase SQL Server Release 10.0.
 Each table may have at most three
triggers (insert, delete, update).
 Semantics: AFTER, Statement-level
 Syntax:

<Sybase trigger1> ::=


CREATE TRIGGER <trigger name>
ON <table name>
FOR <trigger events>
AS <SQL statements>

<trigger event> ::= INSERT | DELETE | UPDATE

 Variant:
<Sybase trigger2> ::=
CREATE TRIGGER <trigger name>
ON <table name>
FOR <trigger restricted-events>
AS [IF <trig-upd-exp>] <SQL statements>

<trigger restricted-events> ::= INSERT | UPDATE

<trig-upd-exp> ::= UPDATE(<column name>) |


<trig-upd-exp> AND <trig-upd-exp> |
<trig-upd-exp> OR <trig-upd-exp>

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {12{
SC

Example Trigger in Sybase

CREATE TRIGGER delcascadetrig


ON titles
FOR deletes
AS
DELETE titleauthor
FROM titleauthor,deleted
WHERE titleauthor.title id =
deleted.title id
DELETE salesdetail
FROM salesdetail,deleted
WHERE salesdetail.title id =
deleted.title id
DELETE roysched
FROM roysched,deleted
WHERE roysched.title id =
deleted.title id

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch2 Active Database Systems {13{
SC

Feature Comparison
(see: Widom-Ceri's book)

SQL3 Oracle Infor Ingres RDB Sybase All Inter


mix base base
Multiple events N Y Y Y Y Y Y Y
BEFORE clause Y Y Y Y Y Y Y Y
AFTER clause Y Y Y Y Y Y Y Y
INSTEAD OF clause Y N N N N N N N
Condition present Y Y Y Y Y N Y N
Tuple-level granularity Y Y Y Y Y N Y Y
Tuple-level references Y Y Y Y Y N Y Y
Statement-level granularity Y Y Y N N Y N N
Table-level references Y N N N N Y N N
Priorities Y N N N N N N Y
Cascade allowed Y Y Y Y Y Y Y Y
Loop allowed N Y Y Y N Y Y Y
Max recursion depth 32 61 20 8 20 ?
Explicit authorization Y Y Y N N Y N N

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {1{
SC

Applications of Active Rules

 Internal to the database:


{ Integrity constraint maintenance
{ Support of data derivation
(including data replication).
 Extended functionalities:
{ Work ow management systems
{ Version managers
{ Event tracking and logging
{ Security administration
 Business Rules:
{ Trading rules for the bond market
{ Warehouse and inventory management
{ Energy management rules

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {2{
SC

Internal and Extended Rules

 Perform classicalDBMS functions


 Can be approached with structured
approaches and techniques
 Can be automatically or
semi-automatically generated
 Can be declaratively speci ed

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {3{
SC

Declarative Design of Active Rules


for Integrity and View Maintenance

 Internal applications of active databases are:


{ Static
{ Declarative
{ High-level, easy to understand

 Approach
{ User speci es application at
declarative (high) level
{ System derives low-level rules
that implement it (automatically
or semi-automatically)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {4{
SC

Framework

 Rules should be programmed by DBA


 Rule programming should be
assisted by rule design tools
 Rule derivation can be:
{ Completely automatic
(for few well-de ned problems)
{ Partially automatic
(interactive system)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {5{
SC

Integrity Constraint Maintenance

 Constraints are static conditions


{ Every employee's department exists
{ Every employee's salary is between 30 and 100
 Rules monitor dynamic database
changes to enforce constraints
{ when change to employees or departments
if an employee's department doesn't exist
then x the constraint
{ when change to employee salaries
if a salary is not between 30 and 100
then x the constraint
 Generalizing:
{ when potentially invalidating operations
if constraint violated
then x it
{ Constraint consistency points =
Rule processing points

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {6{
SC

Integrity-Preserving Rules

 Constraint: condition C
 Rules(s):
when operations that could make
C become false
if C is false
then make C true
or abort transaction
 Example:
C = every employee's department exists
Operations = insert into emp,
delete from dept,
update to emp.deptno,
update to dept.dno
 Condition:
{ There is some employee violating C (due to above ops)
 Action: make C true
{ Rollback insertion of emp
{ Rollback deletion of dept
{ Put emp into a dummy dept

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {7{
SC

Example: Referential Integrity


 Constraint:
EXISTS (SELECT * FROM Dept
WHERE Dno = Emp.Deptno)
 Denial form:
NOT EXISTS (SELECT * FROM Dept
WHERE Dno = Emp.Deptno)
 Abort Rules

CREATE RULE DeptEmp1 ON Emp


WHEN INSERTED, UPDATED(Deptno)
IF EXISTS (SELECT * FROM Emp
WHERE NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))
THEN ROLLBACK

CREATE RULE DeptEmp2 ON Dept


WHEN DELETED, UPDATED(Dno)
IF EXISTS (SELECT * FROM Emp
WHERE NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))
THEN ROLLBACK

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {8{
SC

Example: Repair Rules for EMP


CREATE RULE DeptEmp1 ON Emp
WHEN INSERTED
IF EXISTS ( SELECT * FROM INSERTED
WHERE NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))
THEN UPDATE Emp
SET DeptNo = NULL
WHERE EmpNo IN
(SELECT EmpNo FROM INSERTED)
AND NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {9{
SC

Example: Repair Rules for EMP (2)


CREATE RULE DeptEmp2 ON Emp
WHEN UPDATED(Deptno)
IF EXISTS (SELECT * FROM NEW-UPDATED
WHERE NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))
THEN UPDATE Emp
SET DeptNo = 99
WHERE EmpNo IN
(SELECT EmpNo FROM NEW-UPDATED)
AND NOT EXISTS
(SELECT * FROM Dept
WHERE Dno = Emp.DeptNo))

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {10{
SC

Example: Repair Rules for DEPT


Repair rules on table Dept
CREATE RULE DeptEmp3 ON Dept
WHEN DELETED
IF EXISTS (SELECT * FROM Emp WHERE EXISTS
(SELECT * FROM DELETED
WHERE Dno = Emp.DeptNo))
THEN DELETE FROM Emp
WHERE EXISTS
(SELECT * FROM DELETED
WHERE Dno = Emp.Deptno)

CREATE RULE DeptEmp4 ON Dept


WHEN UPDATED(Dno)
IF EXISTS (SELECT * FROM Emp WHERE EXISTS
(SELECT * FROM OLD-UPDATED
WHERE Dno = Emp.Deptno))
THEN DELETE FROM Emp
WHERE EXISTS
(SELECT * FROM OLD-UPDATED
WHERE Dno = Emp.DeptNo)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {11{
SC

View Maintenance

 Logical tables derived from base tables


{ Portion of database speci ed by retrieval query
{ Used to provide di erent abstraction levels (or: external
schemas)
 Referenced in retrieval queries
 Virtual views
{ Not physically stored
{ Implemented by query modi cation
 Materialized views
{ Physically stored
{ Kept consistent with base tables

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {12{
SC

Virtual Views

 Views de ne derived data by static database queries


Table high-paid =
All employees with high salaries
 Virtual views are not stored in the database
 Rules dynamically detect queries on
virtual views and transform into
queries on base tables
when retrieve from high-paid
then retrieve from emp
where sal > X

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {13{
SC

Materialized Views

 View: V = query Q
 Rules(s): when operations that can change
the result of Q
then modify V
 How to generate rule(s) from view?
 Generate triggering operations by analyzing Q

V = all employees with high salaries

Ops = insert into emp,


delete from emp,
update emp.sal
 Generate action to modify V
{ Evaluate query Q, set V = result
{ Evaluate Q using changed values,
update V
{ Determine which by analyzing Q

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {14{
SC

Materialized Views and Rules

 SQL select expressions


de ne view V as
select Cols from Tables where Predicate
 Materialized initially, stored in database
 \Refreshed" at rule processing points
Changes to base tables !
Production rules modify view

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {15{
SC

View-Maintaining Rules

 Recomputation approach (easy but bad)


when changes to base tables
then recompute view
 Incremental approach (good but hard)
when changes to base tables
then change view
 Incremental rules is complicated for:
{ Views with duplicates
{ Certain base table operations

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {16{
SC

Example
 Relational view selecting departments with one employee who
earns more than 50,000
DEFINE VIEW HighPaidDept AS
(SELECT DISTINCT Dept.Name
FROM Dept, Emp
WHERE Dept.Dno = Emp.Deptno
AND Emp.Sal > 50K)
 Critical events
1. insertions into Emp
2. insertions into Dept
3. deletions from Emp
4. deletions from Dept
5. updates to Emp.Deptno
6. updates to Emp.Sal
7. updates to Dept.Dno

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {17{
SC

Refresh Rules written in Starburst


Refresh rules CREATE RULE RefreshHighPaidDept1 ON Dept
WHEN INSERTED, DELETED,
UPDATED(Deptno), UPDATED(Sal)
THEN DELETE * FROM HighPaidDept;
INSERT INTO HighPaidDept:
(SELECT DISTINCT Dept.Name
FROM Dept, Emp
WHERE Dept.Dno = Emp.Deptno
AND Emp.Sal > 50K)

CREATE RULE RefreshHighPaidDept2 ON Emp


WHEN INSERTED, DELETED, UPDATED(Dno)
THEN DELETE * FROM HighPaidDept;
INSERT INTO HighPaidDept:
(SELECT DISTINCT Dept.Name
FROM Dept, Emp
WHERE Dept.Dno = Emp.Deptno
AND Emp.Sal > 50K)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {18{
SC

Incremental Rule for Insert on Dept


Incremental refresh rule
CREATE RULE IncrRefreshHighPaidDept1 ON Dept
WHEN INSERTED
THEN INSERT INTO HighPaidDept:
(SELECT DISTINCT Dept.Name
FROM INSERTED, Emp
WHERE INSERTED.Dno = Emp.Deptno
AND Emp.Sal > 50K)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {19{
SC

Replication

 A special case of data derivation (identical copies).


 Main application: distributed systems (copies on di erent
servers).
 Typical approach: asynchronous.
{ Capture Step: Active rules react to changes on one
copy and collect changes into deltas.
{ Apply step: Deltas are propagated to other copies at
the appropriate time.
 Alternatives:
{ Primary-Secondary
{ Symmetric

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {20{
SC

Active Rules for Replication


Capture rules CREATE RULE Capture1 ON Primary
WHEN INSERTED
THEN INSERT INTO PosDelta
(SELECT * FROM INSERTED)

CREATE RULE Capture2 ON Primary


WHEN DELETED
THEN INSERT INTO NegDelta
(SELECT * FROM DELETED)

CREATE RULE Capture3 ON Primary


WHEN UPDATED
THEN INSERT INTO PosDelta
(SELECT * FROM NEW-UPDATED);
INSERT INTO NegDelta
(SELECT * FROM OLD-UPDATED)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {21{
SC

Work ow Management

 A new paradigm for organizing the working activities within


enterprise.
 Intrinsecally reactive: work ow managers monitor events and
perform the required event management activities.
 Events are:
{ Internal: generated from within the work ow manager
while work ows are progressing.
{ External: representing the interaction of the work ow
manager with the external world.
 The most signi cant application of rules: expressing excep-
tions to the normal ow.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {22{
SC

Examples of Active Rules for Work ow


Management
de ne trigger WF1 for Agent
events modify(Agent.Availability)
condition Agent(A), occurred(modify(Agent.Availability),A),
A.Availability=FALSE, task(T), T.Responsible=A,
T.Type='Urgent', Agent(B), A.Substitute=B,
B.Availability=TRUE
actions modify(Task.Responsible, T, B)
end;

de ne trigger WF2 for Accident


events create(Accident)
condition Accident(A), occurred(create, A),
Booking(B), B.Car = A.DamagedCar,
actions create(Warning,[B.Number,B.Agent],X)
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {23{
SC

Business Rules

 Performing a part of the application-speci c business.


 Examples:
{ Stock and bond trading in nancial applications.
{ Airway assignment to ights in air trac control systems
{ Order management in inventory control systems.
 Key design principle:
knowledge independence.
{ Factoring knowledge out
of the applications.
{ Rules automatically shared
by all applications.
{ Rules logically part
of the database schema
(designed by \DBA").
{ Knowledge evolution feasible and
controllable (changing rules
without changing applications)).

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {24{
SC

Energy Management System

 The ENEL Energy Management System uses a "radial topol-


ogy" network ( forest), each "user" connected to a single
"distributor" through a network of intermediate "nodes".
 The purpose of the network is to transfer the exact power from
distributors to users through nodes and (directed) branches
connecting pairs of nodes.
 A transaction changes the user's pro le, then the system nds
the appropriate layout and power supply.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch3 Active Database Systems {25{
SC

Active Rules
R1: If a new user requires power, connect it to the closest node
R2: If a user or a node requires less power, change the power of the
user or node and propagate the change to its input branch
R3: If a branch requires less power, change the power of the branch
and propagate the change to its input node
R4: If the power required from a distributor is decreased, change its
output power accordingly
R5: If a user or node requires more power, change the power of the
user or node and propagate the change to its input branch
R6: If a branch requires more power, change the power of the branch
and propagate the change to its input node
R7: If the power required from a distributor is increased, change its
output power accordingly
R8: If a distributor's power exceeds its maximum, rollback the
entire transaction
R9: If a branch's power is changed, change the power of some of its
wires accordingly
R10: If a wire's power is above its threshold, change wire type
R11: If there's no suitable wire type, add another wire to the branch
R12: If a wire is not included into a tube, add a tube around it
R13: If a tube is too small to fit all its wires, change it into a
larger tube
R14: If a wire inside a tube is high voltage and the tube is not
protected, change it into a protected tube
R15: If there's no suitable tube, split the branch into two branches

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {1{
SC

Properties of rule execution

 Termination:
For any legal transaction, the subsequent rule execution ter-
minates.
 Con uence:
For any legal transaction, the subsequent rule execution ter-
minates in the same nal state.
 Identical observable behavior:
For any legal transaction, the subsequent rule execution is
con uent and produces the same output sequence.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {2{
SC

Analysis of Termination

 An active database has Non-Terminating Behavior i


there exists at least one transaction which produces non-
terminating rule processing.
 Triggering Graph (TG):
{ Directed graph fV; E g
{ Node vi 2 V correspond to rule ri 2 R.
{ Arc hrj ; rk i 2 E means that the action of rule rj gener-
ates events which trigger rule rk .
 Acyclicity of the triggering graph implies the absence of non-
terminating behaviors.
 Two rules creating an arc:
CREATE RULE T1 FOR Table1
WHEN . . .
IF . . .
THEN UPDATE Table1.Attr1 . . .

CREATE RULE T2 FOR Table1


WHEN UPDATED(Attr1)
IF . . .
THEN . . .

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {3{
SC

Cyclic Rule
 With termination:
CREATE RULE SalaryControl ON Emp
WHEN INSERTED, DELETED, UPDATED (Sal)
IF (SELECT AVG (Sal) FROM Emp ) > 100
THEN UPDATE Emp
SET Sal = .9 * Sal
 Without termination:
CREATE RULE SalaryControl2 ON Emp
WHEN INSERTED, DELETED, UPDATED (Sal)
IF (SELECT AVG (Sal) FROM Emp ) > 100
THEN UPDATE Emp
SET Sal = 1.1 * Sal

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {4{
SC

Improving Rule Analysis


 Eliminate edge < ri; rj > between two rules when:
{ The condition of rj is guaranteed to be false after the
execution of ri.
{ The new data produced by ri do not satisfy the condition
of rj .
 Example of second case:
Grade range rules CREATE TRIGGER CheckGradeDomain1
AFTER UPDATE OF Exam ON Grade
REFERENCING NEW AS N
FOR EACH ROW
WHEN (N.Grade > 30)
UPDATE Exam
SET Grade = NULL
WHERE ExamNumber = N.ExamNumber

CREATE TRIGGER CheckGradeDomain2


AFTER UPDATE OF Exam ON Grade
REFERENCING NEW AS N
FOR EACH ROW
WHEN (N.Grade < 18)
THEN UPDATE Exam
SET Grade = NULL
WHERE ExamNumber = N.ExamNumber

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {5{
SC

Con uence

 Set-oriented Rules
{ Total ordering and termination imply con uence.
 Tuple-oriented Rules
{ Con uence is much harder to ensure; it requires that the
nal state does not depend on the system's controlled
order in which tuples are accessed.
{ Con uence is not necessary or desirable in many cases.
{ Mutating table exception, when a table that is currently
being updated also needs to be changed by a rule; may
reveal lack of con uence.
 Sucient condition for con uence: Commutativity of two
rules ri and rj if for any database state, considering rule ri
and then rule rj produces the same database as considering
rule rj and then rule ri.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {6{
SC

Commutative Rules
create trigger T1 for C1
events modify(A1)
condition C1(X), X.A1=7
actions modify(C1.A2,X,A2+1)
end;

create trigger T2 for C1


events modify(A1)
condition C1(X), X.A1=7
actions modify(C1.A2,X,A2+2)
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {7{
SC

Observable Determinism

 Prescribes that, for any input application, rule processing exe-


cution terminates in the same nal state with the same output
sequence (messages, display activities, reports).
 Observable determinism is not necessary or desirable in many
cases.
 Rules may be con uent but not provide observable determin-
ism:
create trigger T1 for C1
events modify(A1)
condition C1(X), X.A1=7
actions modify(C1.A2,X,A2+1),
display(I where integer(I), I=X.A2)
end;

create trigger T2 for C1


events modify(A1)
condition C1(X), X.A1=7
actions modify(C1.A2,X,A2+2),
display(I where integer(I), I=X.A2)
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {8{
SC

Modularization Techniques
for Active Rule Design

 The main problem with rules:


understanding their interaction.
 This is not just a design issue,
but rather a maintenance problem.
{ Understanding rules after their design
is quite hard.
{ Adding one rule to a rule set
may lead to unexpected behaviors.
 The main reason: lack of modularization
devices for active rules.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {9{
SC

Rule Strati cation

 Strati cation:
partitioning of rules into disjoint strata
such that each strata includes \uniform" rules.
 Consequence:
Rule behavior can be abstracted by:
{ Reasoning \locally" on each individual stratum
{ Reasoning \globally" of the behavior across strata
 A key design principle for providing rule modularization
and control.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {10{
SC

Strati cation Approaches

 Strati cation can be:


{ Behavioral:
active rules of a stratum have given
behavior (e.g., they try to achieve
a speci c objective).
{ Assertional:
active rules of a stratum establish the
truth of given predicates (called
stratum post-condition).
{ Structural:
events of active rules of strata
are globally acyclic.
 The rst case subsumes the other ones.
 We concentrate on behavioral strati cation.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {11{
SC

Behavioral Strati cation

 Intuition:
{ For each stratum S , introduce
a metric mS (integer nite function).
{ mS measures the distance from
the current database state to a
stratum xpoint, the quiescent
state produced by rules of a
stratum running in isolation.
{ Strata are ordered by priority.
{ The execution of rules belonging to
lower priority strata does not
perturbate the metric of strata
at higher priority.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {12{
SC

Local Convergence,
Metric Conservation

 Metric mS of stratum S is a nite


function on N de ned for
every database state: mS : DB ! N .
 Stratum S locally converges:
{ Rules of S , considered in isolation,
from any initial state D1
always reach a quiescent state,
denoted by D2.
{ If any rule executes its action part,
(D2 6= D1), then mS (D2) < mS (D1).
 Sj conserves the metrics of Si :
{ I , whenever any rule of Sj is executed
and transforms a database state D1
into a database state D2,
then it is mi(D2)  mi(D1).

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {13{
SC

Behavioral Strati cation

 S = fS1 [ S2 [ ::Sng is a behavioral strati cation:


{ All strata Si locally converge.
{ A total order < is de ned on S
such that, if Si < Sj , then:
 All rules of Si have greater
priority than rules of Sj .
 Sj conserves the metrics of Si .

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {14{
SC

Example: Order Management

 A company receives and then processes client orders; or-


der processing tranforms pending orders into accepted orders
when certain conditions on client's credit and trusting are
met. Order processing is automatically performed by active
rules: orders are accepted if they are within the allocated
credit of clients, or if a client is trusted.
 Database:

de ne object class Order


attributes OrderNumber: integer,
Issuer: Client,
Amount: integer,
Status: (accepted, pending, rejected)
end;

de ne object class Client


attributes Name: string,
Credit: integer,
Trusted: boolean
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {15{
SC

Active Rules (Single Stratum)


create trigger T1 for Order
events create
condition Order(O), Client(C), holds(create, O),
O.Status=pending, O.Issuer=C, C.Trusted=true
actions modify(Order.Status, O, accepted),
modify(Client.Credit, C, C.Credit - O.Amount)
end;

create trigger T2 for Order


events modify(Amount), modify(Status)
condition Order(O), Client(C), holds(modify,O),
integer(I), I=O.Amount-old(O.Amount),
C.Trusted=true
actions modify(Order.Status, O, accepted),
modify(Client.Credit, C, C.Credit - I)
end;

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {16{
SC

Active Rules (Single Stratum)


create trigger T3 for Order
events create
condition Order(O), Client(C), holds(create,O),
C.Credit > A.Amount
actions modify(Order.Status, O, accepted),
modify(Client.Credit, C, C.Credit - O.Amount)
end;

create trigger T4 for Order


events modify(Amount), modify(Status)
condition Order(O), Client(C), C=O.Issuer, holds(modify,O),
integer(I), I=O.Amount-old(O.Amount), C.Credit > I
actions modify(Order.Status, O, accepted),
modify(Client.Credit, C, C.Credit - I)
end;

Metric : count(Orders) - count(AcceptedOrders)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {17{
SC

Active Rules Modi cation

 Assume now a change of politics of the company, due to reces-


sion. When clients' credit falls below 50K, then their orders
are suspended.
create trigger T5 for Client
events modify(Credit)
condition Client(C), holds(modify(Client.Credit),C),
C.Credit < -50K, Order(O), O.Issuer=C
actions modify(Order.Status, O, pending)
before T1, T2, T3, T4
end;
 T5 violates the metrics of the stratum.
 With inserts or update of orders of
trusted clients:
rule T5 loops with rules T2.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {18{
SC

Correction of the Modi cation

 An obvious correction is to delete the fact that a


client is trusted as part of the rule's action.
create trigger T5 for Client
events modify(Credit)
condition Client(C), holds(modify(Client.Credit),C),
C.Credit < - 50K, Order(O), O.Issuer=C
actions modify(Order.Status, O, pending),
modify(Client.Trusted, C, false)
before T1, T2, T3, T4
end;
Stratum S1 T5
metric m1: count(trusted-clients)
Stratum S2: T1 through T4
metric m2: count(orders) - count(accepted-orders)
 T5 is at a higher stratum than T1..T4:
 S2 preserves the metrics of S1.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {19{
SC

Mapping Applications to Strati cations

 Assertional and event-based


strati cations (not covered)
are most suited to internal and
extended applications.
 Behavioral strati cation is
most suited to business rules.

Applications Suggested
Strati cation
Constraint Assertional
Internal maintenance strati cation
applications Derived data Event-based
maintenance strati cation
Replication Assertional
management strati cation
Version Event-based
Extended management strati cation
applications Event-based
Work ow strati cation and
management assertional
strati cation
External Business Behavioral
applications rules strati cation

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {20{
SC

Design Strategy with Modularization

1. Identify applicative tasks for active rules.


2. Associate each applicative task to a module.
3. Associate each task to the condition under which the task
should be executed.
4. Describe the task: \if condition, then action".
5. Detect for each task the events which cause the task to be
executed.
6. Identify for each task a metric which indicates the \progress"
towards the solution of the task.
7. De ne the \natural order" of tasks so that tasks which not
require the execution of other tasks have priority.
8. Generate active rules responding to the events which are as-
sociated to the task.
9. Check that when rules execute their action they improve the
metric and thus \progress" towards the task's solution.
10. Check that when rules execute they do not decrease the met-
rics of any task preceding the current task in the natural order
de ned at step 7.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {21{
SC

Large Example: EMS

The ENEL Energy Management System uses a "ra-


dial topology" network ( forest), each "user" con-
nected to a single "distributor" through a network
of intermediate "nodes".
 The purpose of the network is to transfer the exact
power from distributors to users through nodes and
(directed) branches connecting pairs of nodes.
 Triggers belong to 4 strata:
S1 reacts to new requests, S2 to node/branch un-
balance,
S3 to wire requirements (they should carry power
at given voltage),
S4 to tube requirements (they should encapsulate
wires with given size/protection requirements).
 A transaction changes the user's pro le, then the
system nds the appropriate layout and power sup-
ply.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {22{
SC

Active Rules, Strata 1 and 2

 Stratum 1
R11: If a new user requires power, connect it to the
closest node

 Stratum 2
R21: If a user or a node requires less power, change
the power of the user or node and propagate the change
to its input branch
R22: If a branch requires less power, change the power of the
branch and propagate the change to its input node
R23: If the power required from a distributor is decreased,
change its output power accordingly
R24: If a user or node requires more power, change the power
of the user or node and propagate the change to its
input branch
R25: If a branch requires more power, change the power of
the branch and propagate the change to its input node
R26: If the power required from a distributor is increased,
change its output power accordingly
R27: If a distributor's power exceeds its maximum, rollback
the entire transaction

Priorities in S2 (partial order):


{R21,R22,R23} precede {R24,R25,R26,R27}

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {23{
SC

Active Rules, Strata 3 and 4


 Stratum 3
R31: If a branch's power is changed, change the power of
some of its wires accordingly
R32: If a wire's power is above its threshold, change
wire type
R33: If there's no suitable wire type, add another wire
to the branch

 Stratum 4
R41: If a wire is not included into a tube, add a tube
around it
R42: If a tube is too small to fit all its wires, change
it into a larger tube
R43: If a wire inside a tube is high voltage and the tube
is not protected, change it into a protected tube
R44: If there's no suitable tube, split the branch into
two branches

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {24{
SC

Metrics and Prioritization


 Metrics:
m1: count(disconnected new users)
m2: count(nodes with unbalanced
power distribution)
m3: count(wires which are inappropriate
to carry the required power)
m4: count(wires which are not contained
into the appropriate tubes)

 Priorities:
1. S1<S2 (S2<S1 excluded:
S1 may generate a user
with unmatched power)
2. S2<S3 (S3<S2 excluded:
S2 may generate wrong
wire types)
3. S3<S4 (S4<S3 excluded:
S3 may generate a wire
not included into tube)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {25{
SC

Rule Debugging and Monitoring

 Purpose: run-time debugging and monitoring for tuning ac-


tive rules' behavior.
 Commercial systems lack of debugging and monitoring tools.
 Minimum requirement: trace facility - but often unavailable.
 Some research prototypes o er powerful debuggers.

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {26{
SC

Debugging in Chimera
 A debugging environment is started before rule processing or
activated by spy points in the rules.
 Interactive execution:
{ At the rule step level (halt+inspection after each rule
execution)
{ At the intra-rule step level (halt+inspection after each
step of triggering, condition evaluation, and action execu-
tion).
 Available functionalities (in both modes):
{ Information on rules (including their source code, trigger-
ing time, and event consumption mode)
{ Commands for rule activation and deactivation
{ Inspection of the con ict set (immediate or deferred)
{ Inspection of the trace
{ Information on occurred events (event type, OIDs of the
objects a ected by the event)
 Available functionalities only in intra-rule step mode:
{ Display of the processing status
{ Detection of the next executable rule
{ Dynamic modi cation of priorities
{ Information on bindings produced by the condition

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {27{
SC

IDEA Methodology

 Methodology: www.elet.polimi.it/idea
(More than 250 slides available in HTML)
 Web-Laboratory: www.txt.it/idea
(Java-based implementations of IADE, ARACHNE, and PAN-
DORA)

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997
Ch4 Active Database Systems {28{
SC

Conclusions

 Database production rules are:


{ Very powerful
{ Very widespread (on almost all relational products)
{ Very dicult to program
 Active rule products must be enhanced:
{ Although SQL3 is not yet published, many products are
\implemented", with severe limitation and sometimes ill-
de ned semantics
 Strati cation will hopefully soon become a widespread notion
for improving design
 Declarative interfaces are possible for many active database
applications: integrity constraints, materialized views, virtual
views, authorization, dependency control, deduction, versions,
work ow management, resource management, ....

Zaniolo|Ceri|Faloutsos|Snodgrass|Subrahmanian| Zicari|All Rights Reserved


Advanced Database Systems Morgan Kaufmann Copyright c 1997

You might also like