Sie sind auf Seite 1von 12

Oracle Database 10g: Manage

Business Rules with Expression


Filter
An Oracle White Paper
December 2003
Oracle Database 10g: Manage Business Rules with
Expression Filter

Executive Overview ..............................................................................3


Introduction ...........................................................................................3
Rules For Simple Events .......................................................................4
Implementing Rules In Oracle Database...........................................4
Incorporating Other Data In Rule Conditions...................................7
Rules for Composite Events..................................................................8
Rules With Time Constraints ..........................................................10
Rules for XML Events ........................................................................10
Conclusion...........................................................................................11

Oracle Database 10g: Manage Business Rules with Expression Filter Page 2
Oracle Database 10g: Manage Business Rules
with Expression Filter

EXECUTIVE OVERVIEW
Application developers use rules to integrate business processes and automate
workflows. Expression Filter is a feature of Oracle Database 10g. It allows
application developers to store, index, and evaluate rules in the database.
Applications involved in information distribution, demand analysis, and task
assignment can benefit from Expression Filter.
This white paper discusses how to store and evaluate business rules in Oracle
Database using Expression Filter. It assumes the reader is familiar with
Expression Filter concepts and features. Please refer to the Oracle Database 10g
technical whitepaper – Oracle Database 10g Expression Filter Overview and
the documentation Oracle Database Application Developer’s Guide -
Expression Filter for additional information on Expression Filter.

INTRODUCTION
Application developers use rules to integrate business processes and automate
workflows. Rules evaluate business process events. A rule comprises a simple
or complex condition and one or more actions. The rule condition is a
conditional expression (“expression”) that is compared to an event and its set of
attributes and perhaps to other data contained in the database. The rule action is
taken if the rule condition is met.
Expression Filter provides an Expression datatype, an EVALUATE operator, and
an Expression Filter indextype to store, evaluate, and index expressions in
Oracle Database. Expressions representing rule conditions can be stored in a
column of a rule action table. The EVALUATE operator can match these
expressions with event attributes passed by a SQL statement or stored in one or
more tables. Each expression is evaluated to be true or false. If the expression is
true for the event and its set of attributes then the values stored in other columns
of the rule action table are used to determine appropriate actions.
Optionally, expressions can be indexed when Oracle Database Enterprise
Edition is used.

Oracle Database 10g: Manage Business Rules with Expression Filter Page 3
Managing rules in Oracle Database with Expression Filter can save time and
labor. Expression Filter:
• Defines rules in standard SQL language
• Eliminates application changes for rule inserts, updates, and deletes
• Indexes rules for scaleable performance
• Enables other data in the database to be evaluated in the rule condition
• Permits XML expressions in a rule condition
The following sections describe how to evaluate events using rules in Oracle
Database with Expression Filter.

RULES FOR SIMPLE EVENTS


Business rules for simple events can be managed in Oracle Database using
Expression Filter. An example of a simple event might be a travel agent
application that makes a promotional offer if certain criteria are met. A business
rule that decides whether to offer this promotion might be as follows: “If the
customer chooses to fly ABC airlines to Orlando and if his stay in Orlando is
more than 7 days, offer XYZ rental car promotion”. Event-Condition-Action
(ECA) rule semantics can describe this rule as follows.
EVENT:
ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart, Return)

RULE CONDITION:
IF
Airline = ’ABC’ and ToCity = ’Orlando’ and Return–Depart >= 7

RULE ACTION:
THEN
OfferPromotion(’RentalCar’, ’XYZ’)

The event attributes used in the rule evaluation are: Airline, ToCity,
Depart, Return. When a new instance of the AddFlight event is detected the
following rule condition is compared to the event attributes:
Airline = ’ABC’ and ToCity = ’Orlando’ and Return–Depart >= 7

If the rule condition evaluates to true the rule action is executed:


OfferPromotion(’RentalCar’, ’XYZ’)

Implementing Rules In Oracle Database


Rules can be stored and evaluated in Oracle Database in four simple steps. The
first step is to use the Expression Filter API to create an Attribute Set that
describes the AddFlight event attributes. An Attribute Set defines all of the
variables and user-defined functions used in the rule conditions. It is created

Oracle Database 10g: Manage Business Rules with Expression Filter Page 4
using a special form of an object type. The example below creates an Attribute
Set for the AddFlight event.

CREATE or REPLACE TYPE AddFlight AS OBJECT (


CustId NUMBER,
Airline VARCHAR2(20),
FromCity VARCHAR2(30),
ToCity VARCHAR2(30),
Depart DATE,
Return DATE);

BEGIN
dbms_expfil.create_attribute_set(attr_set => ’AddFlight’,
from_type => ’YES’);
END;

The second step is to create a column of Expression datatype to store rule


conditions in the rule action table. Other columns in the same table can be used
to store information pertaining to the actions associated with each rule. The
action information in our example is the type of promotion offered and the
company offering it. Rule conditions are stored in Oracle Database as
expressions. The rule condition in our example is an expression that comprises
three simple predicates:

Airline = ’ABC’ and ToCity = ’Orlando’ and Return–Depart >= 7

Expressions are stored in a column of Expression datatype. Assigning an


Attribute Set to a VARCHAR2 column in a rule action table creates a column of
Expression datatype. This assignment creates a constraint on the column that
ensures expressions use the variables defined in the Attribute Set and follow
SQL WHERE clause syntax. The set of expressions stored in the column of
Expression datatype form a logical group called an Expression Set.
The following commands configure the rule action OfferPromotion table to
store the rules for the travel agent application using the Condition column
and the event AddFlight Attribute Set.

CREATE TABLE OfferPromotion (PromoCode VARCHAR(10),


Condition VARCHAR2(200),
PromoType VARCHAR2(20),
OfferedBy VARCHAR2(20));

BEGIN
dbms_expfil.assign_attribute_set(attr_set => ’AddFlight’,
expr_tab => ’TravelPromotion’,
expr_col => ’Condition’);
END;

The third step is to add rules to the rule set. New rules are added to the
application by inserting rows into the rule action OfferPromotion table.

INSERT INTO TravelPromotion (PromoCode, Condition, PromoType,


OfferedBy)

VALUES
(’UN_AV_FL’, ’Airline = ’’ABC’’ and ToCity = ’’Orlando’’ and
Return–Depart >= 7’, ’RentalCar’, ’XYZ’);

Oracle Database 10g: Manage Business Rules with Expression Filter Page 5
The final step is to use the EVALUATE operator to query the rules set for an
event. When a new instance of the AddFlight event is detected the EVALUATE
operator compares rule conditions with event attributes to determine which rule
conditions are true. Once the rows containing rule conditions that evaluate to
true are identified the values stored in other columns of therule action
OfferPromotion table can be used to determine appropriate actions.
The following query identifies all rules (expressions) that are true for the
AddFlight event. The query also uses the STATIC getVarchar( ) method to
format event attributes into the name–value pair format required by the
EVALUATE operator. The STATIC getVarchar( ) method was implicitly created
for the AddFlight Attribute Set. Alternatively, the attribute names could be
specified in the query in name-value pair format.

SELECT PromoCode, PromoType, OfferedBy FROM OfferPromotion


WHERE EVALUATE (Condition,
AddFlight.getVarchar(987, ’ABC’,’Boston’,’Orlando’,
’01-APR-2003’,’08-APR-2003’)) = 1;

Optionally, An index can be defined on the column of Expression datatype. This


is most helpful when a large expression set is evaluated for a data item. The
EVALUATE operator determines whether or not to use the index based on its
access cost. The indextype, Expression Filter, is used to create and maintain
indexes.
In our example application, the rule action, OfferPromotion can be
implemented as a procedure that accepts the PromoCode and PromoType
values as arguments and performs appropriate actions. If the rule action for all
the rules cannot be captured as a single procedure, one of the columns in the
OfferPromotion table can store the exact action as dynamic SQL commands. If
the rule action should be executed asynchronously, DBMS_JOB package can be
used to submit jobs for parallel (or later) execution.
DECLARE
CURSOR matching_rules (addFlt AddFlight) IS
SELECT PromoCode, PromoType, OfferedBy FROM OfferPromotion
WHERE EVALUATE (Condition, addFlt.getVarchar()) = 1;
BEGIN
FOR mrule IN matching_rules(:addFltInstance) LOOP
OfferPromotion (mrule.PromoType, mrule.OfferedBy);
-- or any dynamic SQL using EXECUTE IMMEDIATE --
END LOOP;
END;

This approach allows maximum flexibility with minimum coding. The rule
action table storing expressions and the query with the EVALUATE operator can
be enhanced to meet more complex requirements. For example, the customer
may be eligible for more than one promotion. However the Travel Agent
application should offer only one promotion of each type. In this case, the
following query can be used to identify the appropriate rules.
SELECT PromoCode, PromoType, OfferedBy FROM OfferPromotion
WHERE PomoCode IN
(SELECT MIN(PromoCode) FROM OfferPromotion WHERE

Oracle Database 10g: Manage Business Rules with Expression Filter Page 6
EVALUATE (Condition, AddFlight.getVarchar(<event
values>)) = 1
GROUP BY PromoType);

Incorporating Other Data In Rule Conditions


Rule conditions can make use of other data in the database as well as incoming
event attributes. For example, the offer promotion rule in our example can be
enhanced to offer a 10% discount if the customer has traveled at least 30,000
miles in the past year. Customer travel miles can be obtained from the customer
record in the customer table in the database with a user-defined function. The
ECA rule semantics below use the MilesInPastYear function to derive
travel miles for a customer

ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart, Return)
IF
Airline = ’ABC’ and ToCity = ’Orlando’ and Return–Depart >= 7
and MilesInPastYear(CustId) >= 30000

THEN
OfferPromotionWithDiscount(’RentalCar’,’XYZ’,10)

This does not change the query used to evaluate the expressions. The function
implementation can reference one or more database tables to compute the value.
A user-defined function must be added to the AddFlight Attribute Set before
it can be used in the rule set.

BEGIN
dbms_expfil.add_functions(attr_set => ’AddFlight’,
funcs_name => ’MilesInPastYear’);
END;

One or more table aliases can be used in a condition to point to data stored in
other tables. Table aliases are an alternative to user-defined functions. In the
following example, Customer is a database table in which the PYMiles
column stores the miles earned by the customer in the past year.

ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart,
Customer*)
IF
Airline = ‘ABC’ and ToCity = ‘Orlando’ and Return–Depart >= 7
and Customer.Id = CustId and Customer.PYMiles >= 30000

THEN
OfferPromotionWithDiscount(‘RentalCar’,‘XYZ’,10)

A table alias is included in the Attribute Set. In our example the AddFlight
attribute set would be modified to include a table alias that obtains values from
the Customer table (discussed further in the next section). Our example query
now includes the Customer table in its FROM clause and performs a join
between the OfferPromotion and the Customer tables.

Oracle Database 10g: Manage Business Rules with Expression Filter Page 7
SELECT tp.PromoCode, tp.PromoType, tp.OfferedBy
FROM OfferPromotion tp, Customer cust
WHERE EVALUATE (tp.Condition,
AddFlight.getVarchar(987, ’ABC’, ’Boston’,
’Orlando’, ’01-APR-2003’,’08-APR-2003’,
cust.rowid)) = 1
AND cust.Id = 987;

RULES FOR COMPOSITE EVENTS


A composite event consists of two or more simple events that are separated by
time. The conditions specified for a composite event cannot be evaluated
conclusively until all the simple events are available. For example the addition
of a flight and a rental car to an itinerary can be two different events separated
by some time. Our travel agent application example can be extended to allow
rules such as “If the customer chose to fly ABC airline to Orlando and he
selected a luxury car for his stay, offer a promotion at STU hotels ”. ECA rule
semantics can represent this rule as follows:

ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart, Return)
Flt,
AddRentalCar (CustId, CarType, CheckOut, CheckIn, Options) Car

IF
Flt.Airline = ’ABC’ and Flt.ToCity = ’Orlando’ and Flt.CustId =
Car.CustId and Car.CarType = ’Luxury’

THEN
OfferPromotion(’Hotel’, ’STU’)

An attribute set can be created for the composite event consisting of two simple
events, AddFlight and AddRentalCar for which two object types are
created in the database. The rule conditions needed to evaluate the composite
event are stored in a column of Expression datatype in the CompTravelPromo
rule action table.

-- AddFlight and AddRentalCar become embedded types in TACompEvent


--

CREATE or REPLACE TYPE TACompEvent (Flt AddFlight,


Car AddRentalCar);
BEGIN
dbms_expfil.create_attribute_set(attr_set => ’TACompEvent’,
from_type => ’YES’);
END;

CREATE TABLE CompTravelPromo (PromoCode VARCHAR(10),


Condition VARCHAR2(200),
PromoType VARCHAR2(20),
OfferedBy VARCHAR2(20));
BEGIN
dbms_expfil.assign_attribute_set(attr_set => ’TACompEvent’,
expr_tab => ’CompTravelPromo’,
expr_col => ’Condition’);
END;

INSERT INTO CompTravelPromo VALUES (‘UN_AV_HT_FL’,


’Flt.Airline = ’’ABC’’ and Flt.ToCity = ’’Orlando’’
and Flt.CustId = Car.CustId
and Car.CarType = ’’Luxury’’’, ’Hotel’, ’STU’);

Oracle Database 10g: Manage Business Rules with Expression Filter Page 8
Using this configuration, the values for the composite event TACompEvent can
be constructed in the application and the following query can be issued to
identify all the conditions that match the event.

SELECT PromoCode, PromoType, OfferedBy FROM CompTravelPromo

WHERE EVALUATE (Condition,


AnyData.convertObject(:TACompEvent_instance)) = 1

Applications that support simple events separated by time may need to fetch the
related events from the database to construct the composite event. For example,
in the Travel Agent application, the user may add the flight and a rental car in
different login sessions. Two tables, FlightData and RentalCarData are
used to store information about these events. When the AddRentalCar or
AddFlight event is raised, the other event attribute information is obtained
from one of these tables to construct the composite event as shown in the
following query below.
SELECT PromoCode, PromoType, OfferedBy
FROM CompTravelPromo ctp, FlightData fd, RentalCarData rcd
WHERE EVALUATE (ctp.Condition,
AnyData.convertObject(TACompEvent( -- construct the
event --
AddFlight(fd.CustId, fd.Airline,
fd.FromCity, ..),
AddRentalCar(rcd.CustId, rcd.CarType,
rcd.CheckOut, ..)
))) = 1

An alternative approach is to use table aliases in the attribute set to point to the
data stored in these tables. The TACompEvent attribute set for the composite
event can be created to make use of this configuration as shown below.
BEGIN
dbms_expfil.create_attribute_set(attr_set => ’TACompEvent’);
dbms_expfil.add_elementary_attribute(
attr_set => ’TACompEvent’,
attr_name => ’Flt’,
tab_alias =>
exf$table_alias(’FlightData’));
dbms_expfil.add_elementary_attribute(
attr_set => ’TACompEvent’,
attr_name => ’Car’,
tab_alias=>
exf$table_alias(’RentalCarData’));

END;

The table storing expressions remains unchanged with the new definition for the
TACompEvent attribute set. When a new AddRentalCar event is generated in
the application, the corresponding data is inserted into the RentalCarData
table and the corresponding rules are identified as follows.
-- store the AddRentalCar event in the corresponding table --

INSERT INTO RentalCarData (CustId, CarType, CheckOut, CheckIn,


Options)
VALUES (987, ’Luxury’, ’01-APR-2003’, ’08-APR-2003’, NULL)
RETURNING rowid into :ridvar;

-- Evaluate the conditions for the new rental car added to the
table --

Oracle Database 10g: Manage Business Rules with Expression Filter Page 9
SELECT PromoCode, PromoType, OfferedBy
FROM CompTravelPromo ctp, FlightData fd, RentalCarData rcd
WHERE rcd.rowid = :ridval and fd.CustId = rcd.CustId and
EVALUATE (ctp.Condition, TACompEvent.getVarchar(fd.rowid,
rcd.rowid)) = 1

The query evaluating the conditions obtains the data from the corresponding
tables and processes the expressions. Although the join predicate “fd.CustId
= rcd.CustId” is not required in the query above, it will improve
performance by limiting the evaluations to the composite events that match this
predicate.

Rules With Time Constraints


Often, rules defined on Composite Events include constraints on the order or the
time window in which the simple events occur. For example, the travel agent
rule described above can be enhanced to offer the promotion only if the flight
and the car reservations are made within 24 hours. To support such rules, the
simple events constituting the composite event can be enhanced to include
attributes that store event creation times. The timestamp attribute is populated
by the application.

ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart, Return,
CrtTime) Flt,
AddRentalCar (CustId, CarType, CheckOut, CheckIn, Options,
CrtTime)Car
IF
Flt.Airline = ’ABC’ and Flt.ToCity = ’Orlando’ and Flt.CustId =
Car.CustId and Car.CarType = ’Luxury’ and ABS(Flt.CrtTime –
Car.CrtTime) <= 1
THEN
OfferPromotion(‘Hotel’,‘STU’)

Similarly, predicates can be specified on the creation time attributes to support


absolute time constraints and sequencing. For example the car rental should be
added after the flight for the promotion to be valid. By including the creation
time attributes in the corresponding attribute sets, the conditional expressions
for such rules can be stored in user tables and processed with EVALUATE
operator.

RULES FOR XML EVENTS


If an event consists of XML data, the conditional expression in the rule
definition may contain XPath predicates on the XML data. For example, in the
Travel Agent application, let a Details attribute in the AddFlight event
store additional details about the flight reservation. A rule on such event can be
defined as follows.
ON
AddFlight (CustId, Airline, FromCity, ToCity, Depart, Return,
Details)

IF
Airline = ’ABC’ and ToCity = ’Orlando’ and Return–Depart >= 7 and

Oracle Database 10g: Manage Business Rules with Expression Filter Page 10
1
Extract (Details, ’/Preferences/Seat[@class=”economy”]’) is not
null
THEN
OfferPromotion(‘RentalCar’,‘XYZ’)

The new AddFlight attribute set can be created to include the Details
(XMLType) attribute as shown below.
CREATE or REPLACE TYPE AddFlight AS OBJECT (
CustId NUMBER,
Airline VARCHAR2(20),
FromCity VARCHAR2(30),
ToCity VARCHAR2(30),
Depart DATE,
Return DATE,
Details sys.XMLType);

This attribute set can be used to create an expression column in a user table as
described in the Rules for Simple Events section. This column can now store
expressions with XPath predicates defined on the Details attribute. The event
for which these expressions are evaluated consists of the values for all the
attributes, including the XMLType (Details) attribute.

SELECT PromoCode, PromoType, OfferedBy FROM TravelPromotion


WHERE EVALUATE (Condition,
AnyData.convertObject(
AddFlight(987,‘ABC’,‘Boston’,’Orlando’,
’01-APR-2003’,’08-APR-2003’,
XMLType(’<preferences>
<seat class=”economy”> …
</seat>
<meals/>

</preferences>’)))) = 1;

The Expression Filter index uses a variety of positional and value filters on
XML elements and attributes to process a set of XPath predicates for XML data
efficiently. For applications using purely XML data events, an attribute set with
a single XMLType attribute can be used.

CONCLUSION
Application developers integrate business processes and automate workflows
through the use of rules that evaluate business process events. Expression Filter
is a feature of Oracle Database 10g that provides an Expression datatype, an
EVALUATE operator, and an Expression Filter indextype to store, evaluate, and
optionally index expressions that represent rule conditions. Both simple and
composite events can be evaluated. Predicates in an expression can include:
event attributes; other data derived from the database, either by function or table
alias; event time constraints and XML attributes.

1
Extract is an Oracle operator that operates on an XMLType attribute to find an XML
Element that matches the given XPath pattern. The Expression Filter index can efficiently
process the XPath predicates specified using ExistsNode and Extract operators.

Oracle Database 10g: Manage Business Rules with Expression Filter Page 11
Oracle Database 10g Manage Business Rules with Expression Filter
December 2003
Author: Aravind Yalamanchi
Contributing Author: Bill Beauregard

Oracle Corporation
World Headquarters
500 Oracle Parkway
Redwood Shores, CA 94065
U.S.A.

Worldwide Inquiries:
Phone: +1.650.506.7000
Fax: +1.650.506.7200
www.oracle.com

Oracle Corporation provides the software


that powers the internet.

Oracle is a registered trademark of Oracle Corporation. Various


product and service names referenced herein may be trademarks
of Oracle Corporation. All other product and service names
mentioned may be trademarks of their respective owners.

Copyright © 2003 Oracle Corporation


All rights reserved.

Das könnte Ihnen auch gefallen