Sie sind auf Seite 1von 12

Integrating Triggers and Declarative Constraints in SQL

Database Systems
Roberta Cochrane Hamid Pirahesh Nelson Mattos
IBM Almaden Research Center, San Jose, CA
{bobbiec, pirahesh, mattos}Qalmaden.ibm.com

[3, 11, 341promotes event condition action (ECA) rules


as the uniform mechanism to support constraints, au-
Abstract thorisation and application logic. The only prior work
that considers the simultaneous existence of separate
This paper describes a model that integrates specifications and models for the execution of ECA
the execution of triggers with the evaluation rules and declarative constraints is [16]. However,
of declarative constraints in SQL database sys- most commercial DBMSs support a rich set of declar-
tems. This model achieves full compatibility ative constraint constructs compliant with SQL92, and
with the 1992 international standard for SQL commercial applications rely on the fact that this spec-
(SQL92). It preserves the set semantics for ification will not change. Hence, the active database
declarative constraint evaluation while allow- model that will be used in practice must integrate pro-
ing the execution of powerful procedural trig- cedural triggers (one form of ECA rules) with the ex-
gers. It was implemented in DB2 for common isting model for declarative constraints defined by the
servers and was recently accepted as the model SQL international standard (SQL92) [20, 27, 71.
for the emerging SQL standard (SQW). There are many practical reasons why, when appli-
cable, declarative constraints should be used in lieu
1 Introduction of triggers. However, declarative constraints alone are
not powerful enough to support all the active data-
Active databases are taking a prominent role in com- base requirements of applications. Most popular ac-
mercial database applications [6, 30, 29, 131. With tive database models developed thus far bear some
client/server solutions, applications are being devel- resemblance to either OPS5 [2] style production rule
oped by small, autonomous groups of developers with systems or deductive logic. Unfortunately, the trigger-
narrow views of the overall enterprise; the enterprise ing mechanisms emerging in the commercial DBMSs
information system is very vulnerable to integrity vi- [24, 12, 35, 171 d o not follow this approach. Instead,
olations because it lacks strict enforcement of the en- they are procedural in nature, and lack many reason-
terprise business rules. Active data proactively moni- ing advantzges inherent in such rule-based systems.
tors events and, without user intervention, protects its However, this procedural model is a natural mapping
own integrity or invokes actions either within or ex- of existing commercial application logic.
ternal to the database. Active data features can be This paper describes the first integrated model for
used to bind frequently used application logic to data reconciling the execution of triggers with the evalua-
for invocation directly within the server, decreasing tion of SQL92 declarative constraints. It resolves the
client/server communication. problems with the co-existence of triggers and declar-
As the SQL standard progresses to its next re- ative constraints introduced in [16], and it is the only
lease (SQL3)[21], i t is. under pressure to include a model that (a) allows triggers to coexist with deferred
well-defined model for active data. Prior research constraints and cascading referential constraints, (b)
incorporates before-triggers, after-triggers, row-level
Permission to copy without fee all OP part of this material is
granted provided that the copies, are not made or distributed for triggers, and statement-level triggers in a uniform
direct commercial advantage, the VLDB copyright notice and framework that is integrated with the set semantics for
the title of the publication and its date appear, and notice is modifications required by SQL92 (not previously un-
given that copying is by permission of the Very Large Data Base
Endowment. To copy otherwise, o+ to republish, requires a fee
derstood), and (c) defines scoping rules for transition
and/or special permission from the Endowment. variables and tables in the context of the aforemen-
Proceedings of the 22nd VLDB Conference tioned types of triggers.
Mumbai(Bombay), India, 1996 SQL3 [21] mc 1u d es advanced database features and

567
has started the final publication process. Until now, beit useful, set of static constraints that define the
SQL3 has received little input from the active database acceptable states of the value of the database, e.g.
community. Yet there is increasing interest from both salary > commission+honrlyYage* hoursWorked. They do
commercial SQL vendors and customers for a well- not support transitional constraints that restrict the
defined specification of SQL triggers. Our model was way in which the database value can transition from
recently accepted as the model for SQL3 triggers [5], one state to the next e.g. salary increases must be 1~s
and we hope~that this paper will stimulate further con- than IOX. They also do not support event-driven invo-
tribution from the research community. cation of application and business logic. Hence, trig-
The structure of the paper is as follows. Section 2 gers are required to enhance the declarative constraint
discusses the relative advantages of declarative con- constructs and to capture application specific business
straints and triggers. Section 3 presents declarative rules. Triggers provide a procedural means for defining
constraints and their fixpoint evaluation model as de- implicit activity during database modifications. They
fined in SQL92. Section 4 proposes our model for are used to support event-driven invocation of appli-
SQL3 triggers and defines their execution in the ab- cation logic, which can be tightly integrated with a
sence of declarative constraints. Our model for in- modification and executed in the database engine by
tegrating the evaluation of declarative constraints and specifying a trigger on the base table of the modifica-
the execution of triggers in SQL is presented 3 sections: tion. Triggers should not be used as a replacement for
Section 5 formally describes the integrated execution declarative constraints. However, they extend the con-
model, demonstrated by an example in Section 6, and straint logic with transitional constraints, data con-
discussed further in Section 7 which highlights the con- ditioning capabilities, exception handling, and user-
tributions of our work with respect to other products defined repairing actions.
and prototypes. In summary, there are advantages to using both
declarative constraints and procedural triggers, and
both types of constructs are available in many com-
2 Constraints or Triggers?
mercial systems. It is not feasible to expect applica-
An active database system (DBMS) should support tions providers to either migrate their existing appli-
constraints as well as event-driven application logic. cations to use only triggers or partition the tables in
However, declarative constraints should be used in lieu their database according to the type of constraints and
of triggers whenever possible. First, several triggers triggers that are required. It is therefore imperative to
are required to enforce one declarative constraint; even define and understand the interaction of constraints
then, the system has no way of guaranteeing the valid- and triggers.
ity of the constraint in all cases. Consider the database
load utilities in which the database checks the declar- 3 Declarative Constraints in SQL92
ative constraints against the loaded data before it can
be accessed. There is no way to determine which trig- Declarative constraints in SQL92 include two forms
gers should be checked since triggers are also used for of static constraints: check constraints and referen-
transitional constraints and for event-driven applica- tial constraints.l SQL92 also supports the definition
tion logic. This behavior also applies when constraints of symmetric views (sometimes referred to as the with
and triggers are added to a database with pre-existing check option), which are transitional constraints ap-
data. plied to updates and inserts through a view.
The database engine can use knowledge of declara- Although declaratively specified, each constraint
tive specifications to optimally evaluate constraints. implies a set of events for which the constraint is
For example, concurrency control hot spots can be checked and>n action to be taken if the constraint is
avoided during referential integrity enforcement by not satisfied (or, more accurately, evaluates to false).
reducing the isolation level to cursor stability [28]. When a static constraint is defined, the system verifies
Guaranteeing the presumed semantic intent of trig- it against the existing data, and once defined, guar-
gers, in general, requires an isolation level of repeat- antees that the constraint is always satisfied. After
able read [lo]. Furthermore, semantic query optimiza- load utilities are used, the system verifies all declara-
tion is not possible if the declarative semantics are tive static constraints before the loaded data can be
hidden in triggers. Tool vendors may also take advan- accessed.
tage of declarative constraints for pre-checking entries A check constraint, typically used to validate in-
at the client (e.g. a mobile laptop) before sending data put data, is a condition that is true for every row in
to the server. a given table. In general, a check constraint can be
The declarative constructs provided by most sys- ‘In X&92, primary keys, unique keys, and NOT NULL are
tems and defined in SQL92 only support a small, al- viewed as special cases of check constraints.

568
any SQL condition, including multi-table assertions. key columns for any child rows that match the mod-
Since such assertions are extremely expensive to sup- ified parent to their default values; and CASCADE,
port, this feature is practically restricted to the special which deletes any matching child rows.
case key constraints and one variable aggregate-free A symmetric view is defined by specifying the WITH
check constraints, i.e., value constraints, in most ex- CHECK OPTION clause during the creation of the
isting products. These constraints allow the definition view. It defines a transitional constraint that is eval-
of uniqueness constraints, value restrictions and intra- uated whenever the view is modified by an INSERT
row value checks on a single table. In object-oriented or UPDATE statement. The most general form of this
extensions of SQL, check constraints can contain func- clause indicates that any row modified through an UP-
tions applied to the values as long as the functions are DATE or INSERT statement on a symmetric view must
deterministic and do not have side-effects. Value con- remain in the view after the modification. If the mod-
straints need only be evaluated when the constraint is ification causes the row to disappear from the view,
defined, after special load utilities are run, or when any then the statement causing the modification is rejected
table on which the constraint is defined is modified by and any changes made by the statement are undone.
an UPDATE or INSERT statement. In addition, multi-
Constraint Evaluation In the Absence of Fr”riggers
table assertions may also need to be checked when any
table referenced in the condition is modified. If the The evaluation of declarative constraints, well-defined
constraint evaluates to false for any updated or in+ by SQL92, is complex and if done incorrectly can lead
serted rows (or, for a multi-table assertion, any row in to anomalous non-deterministic behavior [26]. Dif-
any referenced table), then the statement that caused ficulties arise when an SQL statement modifies sev-
the modification2 is rejected and any changes made by eral rows or causes the evaluation of multiple RI con-
the statement are undone. straints. The result of the statement must not depend
A referential integrity (RI) constraint establishes a on the order in which the rows are modified or the or-
relationship between a set of columns designated as a der in which the constraints are applied. Hence, sev-
foreign key and a unique key such that the non-null val- eral existing products restrict the combinations of con-
ues of the foreign key must also appear as values in the straints that can be defined and the classes of updates
unique key. The foreign key’s table is the constraint’s and deletions allowed on unique keys [1914. According
child table and the unique key’s table is the constraint’s to SQL92, the constraints must effectively be processed
parent table. Note that the parent table and child ta- only after all modifications of the original statement
ble can be the same, referred to as a self-referencing RI are applied. However, there is a common optimiza-
constraint. Like check constraints, RI constraints must tion employed that evaluates constraints in-flight as
also be checked when the constraint is defined and af- the rows are modified. This optimization must only
ter special load utilities are run. However, since there be used when the success or failure of the statement is
are two tables involved in the constraint, there are four not dependent on the order in which the rows or the
modifications that cause constraint evaluation: (a) in- constraints are processed.
sertions into the child table, (b) updates a foreign key The interaction of simultaneously enforcing check
column, (c) deletions from the parent table, and (d) constraints, RI constraints, and symmetric views when
updates of a unique key column. Whenever modifica- the update or delete rule of one of the RI constraints
tions to the child table violate the constraint, the state- is either SET NULL or CASCADE is another potential
ment that caused the modification is rejected and any source of non-determinism. This ambiguity was re-
changes made by the statement are undone. However, moved by a run-time marking algorithm defined in [15]
the action to be taken when the parent is modified by which defines a fixpoint computation for enforcement
a DELETE or UPDATE statement is one of a set of of the declarative constraints. With a few subtle ex-
pre-defined actions that is specified with a delete rule ceptions, this run-time algorithm results in the follow-
or update rule, respectively, when the constraint is de- ing evaluation order for constraints:
fined. This pre-defined set includes: NO ACTION and
1. Evaluate the original statement’s modifications.
RESTRICT, which reject the violating statement3; SET
NULL, which sets the nullable columns of the foreign 2. Evaluate all constraints with RESTRICT semantics.
key of any child rows that match the modified parent If any are violated, return an error after undoing
rows to null; SET DEFAULT, which sets the foreign any changes made by the original statement.

2we refer to UPDATE, DELETE and INSERT statements 3. Perform all cascaded modifications, including SET
collectively as modifications. NULL. As modifications are cascaded, any fur-
‘NO ACTION and RESTRICT have very subtle differences
which are not illuminated here as these distinctionsdo not affect 4DB2 for Common Servers Version 2 has removed these
the model presented in this paper. restrictions.

569
ther activated RESTRICT constraints must also be modifications are applied. Note that the granularity
checked. does not dictate when the trigger executes. Obviously,
there are many cases when row-level triggers can be
4. Perform all cascaded deletes. As deletes are cas- safely and optimally processed in-flight. However, if
caded, any further activated RESTRICT and cas- they or any constraints that must be evaluated require
caded modifications must be checked. access to either the base table of the triggering event
or any table that is modified by the trigger or the con-
5. Evaluate all constraints with NO ACTION seman-
straints, then row-level triggers can only be processed
tics, including check constraints, symmetric views,
in a set-oriented fashion. E.g., if a row-level update
unique keys and not-null constraints. If any of these
trigger on table T accesses the average of a column in
constraints are violated, raise an error and undo any
T, then the average must not be computed in the mid-
changes made by the original statement and any re-
dle of the triggering update; it must either be com-
sulting cascaded actions.
puted entirely before or after the application of any
Thus, SQL92 has a very explicit specification for modifications to T.
deterministic evaluation of constraints with respect to Each trigger has access to the before-transition val-
database modifications. This specification defines a ues and after-transition values of the event through the
fixpoint evaluation that is independent of the order in declaration of transition variables and transition ta-
which rows or constraints are processed. Not only has bles. The declaration “referencing NEW as N” de-
this evaluation model been published as the SQL stan- fines N as a single row correlation variable that contains
dard for over four years, but more than a dozen SQL the value of a row in the database immediately after
database vendors have a conforming implementation the modification is applied. Similarly, “referencing
of SQL92 constraints. OLD as 0” declares 0 as a single row correlation vari-
able containing the value of the same row in the data-
base before the modification is applied. If both OLD
4 A Proposal for SQL Triggers
and NEW transition variables are declared as above,
In contrast to declarative constraints, triggers are pro- then the new and old values of a given row can be
cedural. The event governing the execution of a trigger compared. For example, if the trigger’s table is EMP,
is explicitly specified in its definition. This triggering and EMP has column salary, then we can check if the
event is an UPDATE, DELETE or INSERT statement modification was a raise by comparing 0. salary with
applied to a base table. An optional column list can N. salary. Transition tables are similarly declared us-
be specified in the case of updates to further restrict ing keywords NEW-TABLE and OLD-TABLE. If NT is
the set of update events that activate the trigger. declared as a new transition table, it is a virtual table
The trigger also has an activation time that specifies containing the values of all modified rows immediately
if the trigger is executed before or after its event and a after the modification is applied. Similarly, if OT is
granularity that defines how many times the trigger is declared as an old transition table, it is a virtual ta-
executed for the event. Before-triggers execute before ble containing the values of all modified rows before
their event and are extremely useful for conditioning the modification is applied. The contents of transition
of the input data before modifications are applied to tables is operationally defined in Section 5,
the database and the relevant constraints evaluated. Not all types of transition variables and transition
After-triggers execute after their event and are typi- table references are valid for each type of trigger. In
cally used to embed application logic, which typically particular, triggers defined on insert events can only
runs after the modification completes. see new values and triggers defined on delete events
The granularity of a trigger can be specified as ei- can only see old values while triggers defined on up-
ther FOR EACH ROW or FOR EACH STATEMENT, date events can see both old and new values Further-
referred to as row-level and statement-level triggers re- more, transition variables are only accessible at the
spectively. When the event of a row-level trigger oc- granularity of one row, and hence, can only be refer-
curs, the trigger is executed once for each row affected enced by row-level triggers. As will be described in
by the event. If no rows are affected, then the trigger Section 5, both statement-level and row-level before-
is never evaluated. However, a statement-level trigger triggers participate in a fixpoint computation of the
is executed exactly once whenever its event occurs, transition tables; during the computation of this fix-
even if the event does not modify any rows. Like to point, inherently, the entire content of’the transition
constraints, both row-level and statement-level after- tables is not yet computed. Hence, before-triggers can-
triggers must (appear to) execute only after the trig- not reference transition tables. However, both row-
gering event finishes executing; before-triggers must level and statement-level after-triggers can reference
appear to execute entirely before the triggering event’s transition tables. Such references allow row-level after-

570
triggers to compare a single transition row value with eligible triggers must be executed according to some
aggregations on the transition tables, e.g., how the new discernible total order global to the entire set of trig-
salary in a given row compares with total impact of the gers. Our execution model assumes the existence of
salary increase. some global ordering of the entire set of triggers, a la
Each trigger has an action that is optionally Postgres [33] or Starburst [l].
guarded by a condition; the action is only executed lPrigger Execution in the Absence of Constraints
when the triggering event occurs and, if specified, the
condition is satisfied. The condition is a single, unre- The execution of an after-trigger may activate other
stricted search condition and the action is a procedure triggers, recursively activate itself, or activate the eval-
containing a sequence of SQL statements. Both the uation of constraints. Triggers that activate other trig-
action and the condition can query the transition vari- gers are executed in a nested procedural fashion. If a
ables and tables as well as the current value of the modification statement S in trigger action A causes an
database, and these queries can invoke user-defined event E, and there are no constraints defined in the
functions. Since before-triggers appear to execute en- system, S is processed as follows.
tirely before the event occurs, any queries of the data-
base in their conditions or actions must appear to read 1. Execution of A is temporarily suspended, saving all
the database state prior to any modifications made by local state on a stack. New and old transition tables
the event. Similarly, the conditions and actions of all for S are computed.
after-triggers must appear to read the database state 2. All before-triggers activated by E are executed in
after all of the event’s modifications are applied. If the sequence according to their creation order. If a
after-trigger needs to query the state of the database before-trigger contains an assignment statement,
prior to the event, then it can reconstruct it using the then the appropriate fields in the new transition ta-
transition tables. For example, if T is modified by the ble are modified for the row associated with the new
triggering event, NT is the new transition table and OT transition variable.
is the old transition table, then the state of T prior to
the event can be approximated by (T \ NT) U OT. 3. The current values in the new transition table are
The trigger action is an atomic procedure, e.g., SQL applied to the database.
Procedural Stored Module (PSM), that may contain
4. All after-triggers activated by E are executed in se-
SQL statements combined with other procedural con-
quence according to their creation order. If any
structs. The SQL statements are executed in the order
such execution causes another event, then the state-
in which they occur in the evaluation of the proce-
ment causing the event is processed recursively
dure. If any one of the SQL statements fail, the entire
starting in step 1.
trigger action is rolled-back, including the triggering
event. After-triggers, used primarily to embed applica- 5. A’s state is recovered from the stack and processing
tion logic in the database, can contain any data manip resumes with the statement that follows S in A.
ulation SQL, including SELECT, UPDATE, INSERT,
and DELETE statements. Before-triggers can contain Recalling that an event is the entire SQL statement,
condition data using an assignment statement that al- the event-to-condition binding is deferred (with the
lows the trigger body to set the values of transition exception of the first trigger executed), and condition-
variables declared as NEW. Note that this statement to-action binding is immediate. The difference is that
is not allowed in after-triggers since the modification is in these prototype systems, the event is a modification
already applied to the database, and the NEW transi- to a single row and in SQL systems the event is an
tion variable is no longer maleable. Conversely, before- entire SQL statement that may involve modifications
triggers cannot modify the database using UPDATE, to several rows.
DELETE, or INSERT statements since this leads to a In the above model, there is at most one SQL state-
nested model of unapplied modifications. ment being applied to the database at any given point.
Triggers can indirectly cause a statement-level roll- That is, there is only one set of transitions being com-
back by raising an error, e.g., using the SQL signal puted for a given event. Recall that we do not al-
statement. When this occurs, the containing SQL low-before-triggers to modify the database. If we did,
statement fails and, as described above, the entire many statements could be in progress simultaneously.
trigger action is rolled-back, including the triggering Because before-triggers execute prior to the applica-
event. tion of their triggering modification, allowing modifi-
Several triggers can have the same event and acti- cations causes an endless chain of unapplied modifica-
vation time. Hence, multiple triggers can be simulta- tions to build up. These modifications are not visible
neously eligible for execution. When this occurs, the to the nested invocations of other triggers and result in

571
an ambiguity as to what persists in the database when tion variables are derived directly from the new and
the before-triggers and any cascaded actions due to old values of the transition. When either a row-level
such statements complete. trigger or statement-level trigger is executed, the value
of the new and old transition tables are computed from
5 An Integrated Model the trigger’s activating A. The new transition table is
a table containing one row for each transition in A
This section defines a model that integrates the exe- whose value is the new value of the transition. Sim-
cution of before-triggers and after-triggers defined in ilarly, the old transition table is computed from the
Section 4 with the fix-point evaluation of SQL92 con- old values of the transitions.
straints summarized in Section 3. This model is incor- An Update, Delete, or Insert statement S is exe-
porated in the IBM DB2 for Common Servers Version cuted by the procedure ExecuteSJDI as depicted in
2 product and was recently proposed and accepted as Figure 1 and described below.
the model for trigger execution in SQLJ. Compute A, for S. The execution of statement S
One of the motivating principles behind the design begins with the initialization of A,, which represents
of our execution model is to minimize the window in transitions made by S or by any resulting cascaded ac-
which the declarative constraints of the database are tions with the same modification type and table as S’s
not guaranteed. This is particularly important for ap- event. The values of A, are determined based on the
plication logic that is embedded in after-triggers. Ap- current values of the database and the semantics of S.
plication logic is more easily written and debugged if If S is a DELETE(T), then A, is initialized as the set
one can assume that the declarative constraints are of all transitions for all rows that satisfy the search
enforced. Furthermore, many semantic optimization condition of S. If 8 is a transition in A,, &old is the
techniques can only be applied if the declarative con- value of the row that is to be deleted, and B.new is
straints are enforced. Otherwise, the resulting plans not applicable. If S is INSERT(T), then Ai is initial-
may yield erroneous results. Our model guarantees ized as the set of transitions for all rows identified by
that any statement issued externally by an application the VALUES clause or query expression of S. If B is a
or internally by an after-trigger will only read database transition in A,, B.new contains the new values to be
states that are consistent with respect to the declar- inserted into the database and &old is not applicable.
ative constraints. If S is UPDATE(T), then ‘A, is initialized as the set of
Figure 1 depicts the execution of an SQL modifica- transitions for all rows that satisfy the search condi-
tion statement S. During the processing of S, data is tion of S. If B is a transition in Ai, &old is the value
conceptually stored in two different repositories: the of the row before the update and B.new is the value of
database and the working storage. The database rep- the row after the update.
resents the persistent repository of the enterprise data Execute before-triggers for S. Let Bl, B2, . . ., BP
that is shared among applications and whose visibility be all of the before-triggers activated by Al’s event
is protected by the authorization and locking mecha- in increasing order according to the global trigger or-
nisms of the DBMS. On the other hand, the worlcing dering. B1 is considered first. If B1 is a row-level
storage is local to and contains transitions computed trigger, it is executed once for each row in A,, which
during the execution of S. A transition associates the implies that it is not executed if A, is empty. If BI is
before-value and after-value of a single row resulting a statement-level trigger, it is executed exactly once.
from an event. If 0 is a transition representing a mod- Note that a statement-level trigger is executed even if
ification of a row for some event E, then 6.new (appli- Ai is empty, because the triggering event, S, occurred.
cable for insert and update events) is the value of the All statements in a row-level trigger are executed for
row to be applied to the database and e.old (applica- a given row before proceeding to the next row. The
ble for delete and update events) is the value of the remaining before-triggers B2, . . ., BP are considered in
row before E is executed. Transitions are grouped into turn. Before-triggers can read data from the database.
sets Al, . . . . A,, according to their event type, which A row-level before-trigger can also use an assignment
is update, delete or insert 5 qualified by a single table. statement to modify columns of a given rows new tran-
A trigger is activated by a transition set if the event sition value. Because restrictions on before-triggers
type of the trigger is the same as the event type of the prevent them from modifying the database, they can-
transition set. When a row-level trigger is executed not cause cascaded execution of triggers or cascaded
for a transition, the value of the new and old transi- evaluation of constraints. However, a triggered action
may explicitly request an error to be returned. There
61n the case of update, the event type is further partitioned is no need to rollback any changes made by S since AI
by column sets if there are triggers whose event specifies a col-
umn list. This level of detail is omitted for the purposes of this
has not yet been applied to the database.
description. Apply A, to the database. This is the first point

572
Figure 1: Execution of a Database Modification Statement
in the processing of S when S’s modifications are made is satisfied, then Si will be empty. But we must still ex-
to the database. Note that any changes made to Ai ecute statement-level before-triggers for Si. We must
by row-level before-triggers are reflected in the modi- also create Ai for Si if it does not already exists to
fications applied to the database. schedule the execution of the corresponding statement-
level after-triggers.
Evaluate the declarative constraints for S. If A,
is empty, this step does not have any effect. Otherwise, Let Bil, Bi2, ., Bip be the before-triggers acti-
constraints (referential constraints, check constraints vated by 6;‘s event in increasing order according to
and symmetric views) are evaluated for all modifica- the global trigger ordering. Bil is considered first.
tions made by S according to the SQL92 semantics If it is a newly activated statement-level trigger, i.e.,
summarized in Section 3. The figure refers to a fix- it was not activated previously by S or by any other
point, which is reached only when (a) no constraints cascading action, then it is executed once. If it is a
are violated and (b) statement-level before-triggers for row-level trigger, then it is executed once for each row
all cascaded actions of the evaluated constraints are in Si. The remaining before-triggers Bi2, . . ., Bip are
executed. This is symmetric with the execution of similarly considered in turn. Note that a statement-
statement-level before-triggers for statements that do level before-trigger Bstmt is evaluated at most once
not actually perform any modifications. If the fix- for a statement and its cascading actions. If Bstmt is
point is not reached because of the evaluation of some activated by S’s event, then it is never executed by.a
constraint C, then either C is not satisfied or C is sat- cascading action of a declarative constraint for S. Oth-
isfied and has a cascading action for which statement- erwise, it is executed the first time it is activated by a
level before triggers must be processed. So, if C does cascaded action.
not have a cascading action, then an error must be re-’ The modifications of & are then applied to the data-
turned. If the evaluation of C requires a cascading ac- base. If there does not already exist a transition table
tion Si (CASCADE, SET NULL, SET DEFAULT), then Ai in the working storage with the same event as &,
all before-triggers activated by Si must be processed then Ai is created and initialized with the values of
before the Si’s modifications are applied to the data- Si. Otherwise, the transitions in & are appended to
base. First, transitions for Si’s modifications are com- &. The declarative constraint processing continues in
puted and stored in a temporary transition set Si If C this manner until a fixpoint is reached, i.e., all of the

573
declarative constraints are satisfied and all statement- AUDITPARTS(modtype, updated-by, moddate, numrecs)
level before-triggers for cascaded actions required for PARTS(codenum, supplier, cost, super-part,
updated-by,record-date)
the evaluation of a constraints are executed.
If the evaluation of a constraint causes an error to be HIBVAL: check (cost >= 10.0)
returned, then any modifications made to the database VALIDDIST: PARTS(supp1i-x) references DISTRIBUTOR(id)
by Execute-UDI are first undone. These modifications on delete set null
PARTSUPPART: PARTS(super-part) references PARTS(codenum)
are represented by the transitions in Ai, ., A,, in on delete cascade
the working storage. Processing for Execute-UDI ter-
minates and returns an error. EOUCAPITAL view: (select * from PARTS
where COST < 500) with check option
Execute after-triggers for S and its cascading
actions. Let Al, AZ, . . ., A, be all statement and Check constraint MINVAL verifies that only parts
row-level after-triggers activated by events of Ai, ., with cost greater than 10 are tracked. The RI con-
A, in increasing order according to the global trigger straint VALIDDIST ensures that any non-null value
ordering. Processing of the after-triggers is the same of PARTS.suppher is a valid distributor. Because the
as previously described for before-triggers, with the delete rule is SET NULL, the deletion of a distribu-
following exceptions: (a) the set of simultaneously ac- tor will set the supplier field for any part supplied by
tivated triggers contain triggers with different events the deleted distributor to NULL. The self-referencing
(rather than a single event) since the entire contents of RI constraint PARTSUPPART ensures that all values
the working storage is considered, (b) statement-level of super-parts are also listed as parts. The delete rule
triggers execute once for the transition set Ai of their of cascade will delete a part whenever its super part
respective activating event, (c) after-triggers cannot is deleted. Symmetric view NONCAPITAL selects only
change the new values of A;, and (d) any explicit er- parts that are not classified as capital equipment. Any
ror returned by the action of a trigger must first undo insertion of capital equipment or update that reclas-
changes made to the database by Execute-UDI. Be- sifies non-capital equipment as capital is not allowed
cause the action of an after-trigger can contain SQL through this view.
statements that modify the database, such statements The following row-level before-trigger ensures that
must be processed in a recursive manner. When a the supplier field is never updated to any value other
DELETE, UPDATE, or INSERT statement S’ is en- than NULL. If this occurs the originating statement is
countered during the execution of after-trigger Ai, the rolled-back and an error is reported.
current contents of the working storage is pushed on a
stack clearing its current contents, and Execute-UDI is create trigger OHESUPPLIER
recursively invoked to process S’. After Execute-UDI before update of supplier on PARTS
referencing new as B
finishes executing S’, the saved contents of the working for each row
storage is popped from the stack. If the recursive in- when (II.supplier IS ROT BULL)
vocation causes an error, all modifications made to the signal sqlstate '70005' ('Cannot change supplier');
database by Execute-I-ID1 are undone and processing
terminates in error. The following row-level before-trigger computes the
Return. If the above processing of the before-triggers, time and user of each update.
declarative constraints, and after-triggers completes create trigger USERDATE
successfully with no explicit errors during trigger ex- before update on PARTS
ecution, constraint violation errors, or errors caused referencing new as B
from recursive invocations of Execute-UDI, then pro- for each row
set B.updated-by = USER,
cessing returns successfully. Otherwise, processing re- B.record-data = CURREBT DATE;
turns an error after restoring the database to its state
prior to this execution of Execute-UDI. Note that, as The following statement-level after-trigger uses a tran-
described, when any error occurs, the database will sition table to audit the number of parts updated.
eventually be restored to the state of the database be- Assume there is a similar statement-level trigger
fore the execution of the outermost modification event RECORDDEL after deletions on PARTS.
(i.e. to the beginning of the original statement).
create trigger RECORDUPD
after update on PARTS
6 Our Model in Action referencing old-table as OT
Consider an application that with the following tables, for each statement
constraints, and a symmetric view: insert into AUDITPARTS
values('U', USER, CURREBT DATE,
DISTRIBUTORS(id,location) (select count(*) from OT));

574
When all suppliers located in California are deleted tive constraints, achieving full compatibility with
from table DISTRIBUTOR, the referential constraint SQL92, the standard to which commercial SQL
VALIDDIST will be evaluated, causing the supplier DBMSs are committed. Assumptions made in pre-
column for all rows in PART whose supplier column vious models are either incompatible with SQL or
matches the id of any of the deleted distributors to be compromise the generality and expressive power of
set to NULL. This update, in turn, activates the two SQL, which is unacceptable.
before-triggers ONESUPPLIER and USERDATE, which
are then executed. Assume that the global order is the It allows both before-triggers and after-triggers and
same as the creation time order of the triggers, so that distinguishes between them. After-triggers are used
ONESUPPLIER is executed before USERDATE First, primarily as an extension to the application logic
the new value for supplier is checked. Because it is while before-triggers are primarily used to extend
NULL, the condition of trigger ONESUPPLIER is not the constraint logic.
satisfied, so the error is not returned. Second, update
values for columns updated-by and record-date are com- It incorporates the before-triggers as data condi-
puted from the environment values for the current user tioners and extensions to the constraint logic into
and date. Once these triggers are evaluated for all of the fixpoint computation.
the identified rows, the resulting updates are applied
It ensures that application logic embedded in after-
to the database, which activates the statement-level
triggers see a constraint-consistent database.
trigger RECORDUPD. This trigger will insert one row
into table AUDITPARTS to record number of rows in It clearly defines the contents and scoping rules for
PARTS updated as a result of a statement issued by both transition tables and transition variables.
the current user.
Now, suppose that all parts with NULL suppliers are It recognizes that triggers with different events may
deleted. The referential constraint PARTSUPPART is be triggered simultaneously and hence, supports a
evaluated and subsequently deletes any row in PART global ordering of all triggers.
whose super-part was deleted. This process continues
until there are no rows left in PART with either a NULL Prior to the acceptance of our model, SQL3 con-
supplier or a super-part value that does not match some tained a specification for triggers that was incomplete,
codenum value of a remaining row in PART. Once the did not address any of the above issues [5], and im-
evaluation of PARTSUPPART reaches this fixpoint, the posed many arbitrary restrictions. For instance, it
statement-level trigger RECORDDEL is activated and explicitly disallowed the definition of any trigger on
inserts one record in table AUDITPARTS to record the a table that was the target of a cascading referential
total number of rows deleted from PARTS by the issued action.
delete statement and the resulting cascading actions. We integrate trigger execution in the context of the
To demonstrate symmetric views in this scenario, set-semantics of SQL by defining the triggering event
consider an update to the cost column of the view as a single SQL statement, even for row-level triggers.
NONCAPITAL. This update will first activate before- We also make this model upward compatible with the
triggers. In this case, only.USERDATE is activated be- evaluation of constraints defined by SQL92. We rec-
cause ONESUPPLIER is only activated on updates to ognize that the integration of triggers in the presence
the supplier column. Then, the update is applied with of this fixpoint constraint model requires certain re-
the value of cost specified in the original statement and strictions for before-triggers that are not required for
the values for updated-by and record-date computed by after-triggers.
trigger USERDATE. Subsequently, the check constraint An important aspect of the model described in this
MINVAL and the symmetric view are evaluated to ver- paper is that it distinguishes between before-triggers
ify the new cost value is between 10 and 500; a value and after-triggers. Before-triggers participate in the
less than 10 indicates the part is not valuable enough fixpoint computation of declarative constraints, and
to record, and a value of 500 or more would cause the consequently, the fixpoint computation of the transi-
updated rows to be reclassified as capital equipment tion tables. After-triggers execute only after declara-
and disappear from the view. tive constraints are satisfied. By definition, a before-
trigger must be executed before the activating mod-
‘7 Discussion of our Model ifications are applied to the database, but any such
before-trigger executed during the fixpoint evaluation
The main contributions of our model are as follows.
of constraints may be exposed to an inconsistent data-
l It is integrated with the set semantics of SQL and base. One way to prevent this is to simulate the eval-
the fixpoint semantics for the evaluation of declara- uation of constraints, e.g., using the run-time marking

575
algorithms defined in [15], to pre-compute the transi- and, as highlighted in [32], this is an important concern
tion tables before executing any of the before-triggers in the employment of active features. Many optimiz-
or applying any of the modifications. The disadvan- ers use uniqueness and referential constraints to reduce
tage of this approach is that it prevents the use of duplicate elimination and access to parent tables; such
before-triggers to condition the data as the transition semantic optimization techniques can only be applied
tables would be pre-computed before the triggers are when declarative constraints are guaranteed.
executed. Because we view data conditioning as one of Non-determinism is inherent in row-level after-
the primary advantages of before-triggers, we clearly triggers due to the order in which rows are processed.
distinguish between the uses and properties of before- Consider an update of two rows r-1 and r2 in T, and a
triggers and after-triggers as previously described. row-level after-trigger for updates to T that inserts the
Like declarative constraints, the execution of value of the new transition variable into table S, and
before-triggers must be monotonic because they par- subsequently appends table S to table R. If rl is pro-
ticipate in the fixpoint computation of transition ta- cessed first, then two copies of rl will be appended to
bles. Consequently, neither statement-level nor row- R and only one copy of r2. If r2 is processed first, then
level before-triggers can use aggregate information, two copies of rs will be appended to R and only one
e.g., total number of employees deleted, computed copy of rl. It is enlightening to notice that most row-
from transition tables; this information is meaningless level after-triggers can be simulated with a statement-
until the fixpoint computation is complete. Because level after-trigger in which the trigger program iterates
aggregation is the main reason for including transition through each row of the transition table if trigger ac-
tables, we restrict their use entirely in before-triggers. tions support iteration. In addition, these statement-
Our model also does not allow before-triggers to mod- level after-triggers could use the “order by” clause to
ify the database because such modifications can lead sort the rows in the transition tables and guarantee
to non-monotonic behavior. Furthermore, such mod- a deterministic behavior. Another topic for future re-
ifications may cause the activation of further triggers search is to support an ordering clause to help users
which may lead to confusing behavior due to the nest- control the processing of row-level triggers. Row-level
ing of modifications yet to be applied to the data- triggers are an important feature because they greatly
base. Clearly, these restrictions on before-triggers are simplify trigger actions. In addition to providing a
conservative, and identifying the situations in before- convenient short-hand for processing actions once per
triggers in which transition table references or mod- each row, they inherently provide a mechanism for
ifications do not lead to non-monotonic behavior are pairing the new and old transition values of an up-
topics for further investigation. dated row. Simulating this mechanism in statement-
Our model evaluates declarative constraints before level triggers requires a join of the old and new tran-
executing any after-triggers. This concurs with exist- sition tables using the columns of non-updatable pri-,
ing implementations of triggers in the marketplace [24, mary keys. Furthermore, row-level before-triggers can-
Ii’]. However, these implementations have fundamen- not be simulated with statement-level before-triggers
tal limitations. Some only support statement-level because the statement-level before-triggers cannot ref-
after-triggers, leading to very verbose triggers for re- erence transition tables.
peatedly performing operations on each row modified Our model is unique in considering the semantics
by the triggering event. Others intermix the execution and scoping rules for transition table and transition
of row-level after-triggers with the evaluation of con- variable references within the context of all the vari-
straints in a way that does not maintain the SQL92 ous flavors of triggers. Transition tables can be refer-
constraint evaluation model and does not guarantee enced in the conditions and actions of both row-level
that application logic in an after-trigger operates on and statement-level after-triggers, and facilitate appli-
a consistent database. A previous proposal [16] pro- cations that perform actions based on the aggregate
vides a detailed analysis of the difficulties in specifying information about the transition. Furthermore, a tran-
a model for simultaneously evaluating declarative con- sition table collects all transitions of an event type for
straints and procedural triggers in SQL. In contrast to the execution of a statement and the evaluation of its
our model, this proposal attempts to define a model constraints. This is particularly advantageous in the
in which constraints are evaluated only after all of the case of cyclic RI, as it delivers the full transition table
triggers are executed. Hence logic embedded in after- to the application logic, allowing it to reason about the
triggers is possibly exposed to inconsistent data. Un- net-effect of a given statement. Consider a deletion
fortunately, application libraries require a consistent for a department table that causes cascaded deletes
database and, as such, cannot be used by trigger bod- of all employees in the deleted department, which in
ies. Interestingly, such semantics may also lead to turn causes cascaded deletes of any departments man-
a severe performance degradation of trigger execution, aged by the deleted emp!oyees. At the end of the

576
constraint evaluation, the OLD transition table of a DBMSs. Given the differing expressive powers of
delete-trigger for the department table contains all of declarative constraints and triggers, support for both
the deleted departments, and the OLD transition ta- is required for today’s applications.
ble of a delete-trigger for the employee table contains The semantics of the interaction of triggers and
all of the deleted employees. Assuming no other after- declarative constraints must be carefully defined to
trigger modifies the database, these transition tables avoid inconsistent execution and to provide users a
can be unioned with the existing database to recon- comprehensive model for understanding such interac-
struct its contents prior to the original delete state- tion. This is the first paper that defines such a model.
ment Our model is unique in that it maintains the set seman-
Our model utilizes a global trigger ordering when tics for evaluating declarative constraints as defined by
the fixpoint execution of constraints executes many SQL92 while allowing the execution of powerful proce-
events causing the simultaneous activation of several dural triggers. This model integrates trigger execution
after-triggers with different event types. A global trig- with all forms of constraints defined in the SQL92 stan-
ger ordering is also required for the execution of de- dard: primary keys, unique keys, NOT NULL specifi-
ferred constraints and triggers. SQL3 currently does cations, check constraints, referential constraints, and
not provide a mechanism for a user defined global or- symmetric views. The main advantage of this model,
dering, and, in the implementation of DB2, we define as described in Section 7 “Discussion of the Model”,
the global ordering according to the creation times- is that it maintains the SQL92 fixpoint semantics for
tamp. Extending the standards to allow user speci- the evaluation of constraints and incorporates before-
fied global ordering among all triggers, similar to the triggers into this fixpoint computation while ensuring
Starburst Rule System [l], and extending our model that application logic embedded in after-triggers op-
to support deferred triggers and constraints are topics erates with a consistent database. This work is also
for future work. the first to define the semantics and scoping rules of
Although there has been considerable research ac- both transition tables and transition variables in the
tivity for active DBMSs, prior to this paper the im- context of row-level and statement-level triggers.
portant problem of completely integrating declarative
constraints and active rules without restrictions has Acknowledgments
not been addressed. The execution models of many Richard Sidle incorporated portions of this execution
prototype active database systems, e.g., Ariel [14], model into DB2 C/S, Dan Lee, John Hornibrook, and
HiPac [8, 181, RDL [22], RPL [9], and Starburst [36], the entire DB2 Common Server team implemented and
consider only ECA rules and are more in the style of tested DB2 C/S triggers. Don Chamberlin, Bruce
OPS5; the activation of triggers is considered only at Lindsay, Pat Selinger, Mike Carey and many others
preset activation points, the execution of trigger ac- at Almaden provided thorough review of this work.
tions are non-interruptible, and trigger activation is
determined based on the net-effect of multiple events.
References
Because declarative constraints are supported using
[l] R. Agrawal, R. Cochrane, and B. Lindsay. On main-
rules, these systems cannot benefit from the important taining priorities in a production rule system. In Proc.
semantic query optimization techniques [23]. In con- of the 17th hat. Conf. on Very Large Data Bases,
trast to the OPS5 models, triggers appearing in the pages 479-487, Barcelona (Catalonia, Spain), Septem-
marketplace are more procedural, & la Postgres [33], ber 1991.
[2] L. Brownston, R. Farrell, E. Kant, and N. Martin.
Alert [31] and Update Dependencies [4, 251. Once ac- Programming Expert Systems in OPS5: An Introduc-
tivated, a trigger will be eventually executed, and if a tion to Rule-Based Programming. Addison-Wesley,
trigger action causes an event that activates another Reading, Massachusetts, 1985.
trigger, the newly activated triggers are executed im- [31 S. Ceri and J. Widom. Deriving production rules for
mediately. The burden for controlling triggering based constraint maintenance. In Proc. of the 16th ht. Conf.
on Very Large Data Bases, pages 566-577, Brisbane,
on the net-effect of database modifications is placed on Australia, August 1990.
the user who can program this explicitly in the trigger
condition and action. [41 R. Cochrane. Issues in Integrating Active Rules Into
Database Systems. Ph.D. &sserta%on, University of
Maryland, Department of’computer Science, College
Park, MD, 1992.
8 Summary
[51 R. Cochrane and N. Mattos. ISO-ANSI SQL3 Change
Support for active data is crucial to the management of Proposal, ISO/IEC JTCl/SC21/WG3 DBL LHR-89,
X3H2-95-458, An Execution Model for After Triggers,
the world’s information. Declarative constraints and November 1995.
triggers are two essential features that have been in- PI Database Programming and Design. The 1996 Busi-
troduced to support user requirements in relational ness Rules Summit, February 1996.

577
171 C.J. Date
SQL Standard.
and Hugh Darwen. A Guide to The
Addison-Wesley Publishing Company,
P4 G. Koch and K. Loney. Oracle: The Complete Refer-
ence. Osborne McGraw-Hi& Berkeley, California, 3rd
Reading, Massachusetts, 3rd edition, 1993. edition, 1995.
PI U. DayaI, B. Blaustein, A. Buchmann, 1251L. Mark. Self-Describing Database Systems - Formal-
S. Chakravarthy, M. Hsu, R. Ladin, D. McCarthy, ization and Realization. Ph.D. dissertation, Depart-
A. Rosenthal, S. Sarin, M.J. Carey, M. Livny, and ment of Computer Science, University of Maryland,
R. Jauhari. The HiPAC project: Combining active College Park, Maryland, 1985. TR-1484.
databases and timing constraints. SIGMOD Record,
17(l), March 1988. WI V. M. Markowitz. Safe referential integrity structures
in relational databases. In Proc. of the 17th Int. Conf.
IQ1L.M.L. Delcambre and J.N. Etheredge. The Rela- on Very Large Data Bases, pages 123-132, Barcelona
tional Production Language: A production language (Catalonia, Spain), September 1991.
for relational databases. In L. Kerschberg, editor, Ez-
pert Database Systems - Proc. from the Second Int. P71 J. Melton and A. R. Simon. The New SQL: A Com-
Conf., pages 333-351, Redwood City, C&forma, 1989. plete Guide. Morgan Kaufmann Publishers, San Ma-
Benjamin/Cummings. teo, California, 1993.

PO1K.P. Eswaran. Specifications, implementations and 1281C. Mohan. CommitLSN: A Novel and Simple Method
interactions of a trigger subsystem in an integrated for Reducing Locking and Latching in Transaction
database system. IBM Research Report RJ 1820, Processing Systems. In Proc. of the 16th Int. Conf.
IBM Research Laboratory, San Jose, California, Au- on Very Large Data Bases, Brisbane, Australia, Au-
gust 1976. gust 1990.

WI K.P. Eswaran and D.D. Chamberhn. Functional spec- PQIC. S. MuIIins. The procedural DBA. Database Pro-
ifications of a subsystem for data base integrity. In gramming and Design, 8(7):40-45, December 1995.
Proc. of the 1st Int. Conf. on Very Large Data Bases,
pages 48-67, Framingham, Massachusetts, September
[301 Ron Ross. The Business Rule Book. Database Re-
search Group, 1994.
1975.
P21 Fosdick. WiII DB2 make the short list. Information
H. [311 UIf Scbreier, Hamid Pirahesh, Rakesh AgrawaI, and
Week, pages 56-64, August 28, 1995.
C. Mohan. Alert: An architecture for transforming a
passive DBMS into an active DBMS. In Proc. of the
[131 B. Von HaIIe. Uncovering business rules. Database 17th Int. Conf. on Very Large Data Bases, pages 469-
Programming and Design, 8(7):13-18, December 1995. 477, Barcelona (Catalonia, Spain), September 1991.
v41 E. N. Hanson. The design and implementation of the [321 E. Simon and A. Kotz-Dittrich. Promises and reah-
ariel active database rule system, 1995. ties of active database systems.In Proc. of the %lst
Int. Conf. on Very Large Data Bases, pages 642-653,
1151B. Horowitz. A rim-time execution model for referen- Zurich, Switzerland, September 1995.
tial integrity maintenance. In Proc. 8th International
Conf. on Data Engineering, pages 548-556, Tempe, [331 M. Stonebraker, M. Hearst, and S. Potamianos. A
Arizona, February 1992. commentary on the POSTGRES rules system. SIG-
MOD Record, Special Issue on Rule Management and
WI B. Horowitz. Intermediate states as a source of non- Processing in Expert Database Systems, 18(3):5-11,
deterministic behavior in triggers. In Fourth Inter-
national Workshoo on Research Issues in Data En- September 1989.
gineering~~Active~L)atabase Systems, pages 148-155,
[341 M. Stonebraker, A. Jhingran, J. Goh, and S. Potami-
Houston, TX, February 1994. anos. On rules, procedures, caching and views in data-
1171L. Howe. Sybase data integrity for on-line applica- base systems. In Proc. ACM SIGMOD Int. Conf. on
tions. Technical report, Sybase, Inc., EmeryviIIe, CA, Management of Data, pages 281-290, Atlantic City,
1986. New Jersey, June 1990.
WI M. Hsu, R. Ladin, and D. McCarthy. An execution [351 M. UbeII. The Montage extensible datablade. In Proc.
model for active database management systems. In ACM SIGMOD Int. Conf. on Management of Data,
Proc. Srd International Conf. on Data and Knowl- page 482, Minneapolis, Minnesota, May 1994.
edge Bases - Improving Usability and Responsiveness,
JerusaIem, June 1988. 1361J. Widom, R. Cocbrane, and B. Lindsay. Implement-
ing set-oriented production rules as an extension to
WI IBM Database 2 Referential Integrity Usage Guide. Starburst. In Proc. of the 17th Int. Conf. on Very
IBM Corporation, International Technical Support Large Data Bases, pages 275-285, Barcelona (CataIo-
Center - Santa Teresa, San Jose, California, 1988. nia, Spain), September 1991.
WI ISO-ANSI Database Language SQL2 Standard;
X3H2-92-154, 1992.
WI ISO-ANSI Working Draft: Database Language SQL
(SQLS), ISO/IEC JTCl/SC21/WGS DBL LHR-004,
X3H2-95-368, j. melton, editor, October 1995.
PM J. Kieman. C. de MaindreviIIe, and E. Simon. Mak-
ing deductive databases a practical technology: A step
forward. In Proc. ACM SIGMOD Int. Conf. on Man-
agement of Data, pages 237-246, Atlantic-City, New
Jersey, June 1990.
P31 J. King. QUIST: A system for semantic query opti-
mization in relational database. In Proc. 7th Inter-
national Conf. on Very Large Data Bases, Cannes,
France, September 1981.

578

Das könnte Ihnen auch gefallen