Vous êtes sur la page 1sur 168

Modern Database Techniques

Part 1: Object Oriented Databases


4. Concepts of Object Oriented
Databases

Chapter 4: Overview
4.1 Type constructors, complex objects
4.2 Classes: Type- and Set-View
4.3 Relations between Classes, Aggregation
4.4 Object Identity
4.5 Inheritance
4.6 Query Operations
4.7 OQL Object Query Language of ODMG
4.8 Methods
4.9 Integrity
2

Requirements for OODBS


object-oriented perspective
Complex objects
Object identity
Encapsulation
Types and classes
Class hierarchies
Overloading of methods

Database perspective
Persistance
Disk-storage organisation
Concurrent transactions
Recovery mechanisms
Query languages
Database operations

optional:
Multiple inheritance

optional:
Distributed databases
Version administration
3

4.1 Type constructors, complex objects

To be able to store many objects,


a set constructor is necessary
Type of a relational table
SET OF (TUPLE OF (Typ1 A1, . . . , Typn An))
In OODBS user defined classes can be used
besides basic types.
TUPLE OF corresponds aggregation.
There are different implementations of the set
operator in different OODBMs
4

Overview Type Constructors

Tuple constructor TUPLE OF

Set constructor SET OF

Many elements of the same type build a set.


Each element can only be contained once in the set.

Multi-set constructor BAG OF: like set but

Combines several components of possibly different type


Corresponds to aggregation

one element can have copies in the bag

List constructor LIST OF: like bag, but

Sequence is of interest
5

Overview Type Constructors (cont.)

Array constructor ARRAY OF: like list, but

Dictionary constructor
DICTIONARY OF (key, value)

0
1
2
may contain gaps
index of type long integer Atlanta Paris

unordered sequence of
(key, value)-pairs
lookup operation
returns value to a given key

Type constructors are used recursivly

London
Key Value
A

excellent

very good

good

satisfactory

sufficient

fail

Example: Type Construction for Persons


Graphical Representation
Set Persons

Tuple

Person

Name
Tuple

PhoneNumbers
date

Set Addresses

DOB
string

string

string

First
Second Last
Name Name Name

string

string

Title

Saluta
tion
string

string

Street City

Tuple Address

List

Tuple

Phone
Number

string

string

string

string

State

ZIP

Type

Phone Type
Nr

string

Example Type Construction in O2: Persons


SET OF
TUPLE OF (
Name: TUPLE OF (
FirstName: STRING, SecondName: STRING
LastName: STRING, Title: String ),
Adresses: SET OF TUPLE OF (
Street: STRING, City: STRING,
ZIP: STRING, State: STRING, Type: String),
PhoneNumbers: LIST OF TUPLE OF (
PhoneNr: STRING, Type: STRING),
DOB: DATE)
8

ODMG Standard

ODL (object definition language) for ODMG-types

All classes inherit from interface Object that


provides

extension of IDL (interface definition language)


similar to C++ but language independent

constructor function (interface ObjectFactory)


locking information and operation
identity comparison function same_as(object)
copy function
delete function

Different constructors for collection types

ODMG Standard (cont.)

Collections supported by
the ODMG-Model

Set <t>
Bag <t>
List <t>
Array <t>
Dictionary <t, v>
where t and v are any types

Collections supported for


objects and for literals

Atomic types

long, long long, short


float, double
boolean, octet
char, string
enum

type generator
can only take values listed in
declaration

Structured literals

date
time, timestamp
interval
user defined with struct
10

Example: Persons in ODMG-Model


set of objects

Class Person (extent Persons)


{attribute NameCl Name;
attribute date DOB;
attribute set <Address> Addresses;
attribute list <PhoneNr> PhoneNrs;}
Class NameCl
no own set
of objects
{attribute string FirstName;
attribute string SecondName;
attribute string LastName;
attribute string Title;
attribute string Salutation;}

11

Example: Persons in ODMG-Model


Class Address
{attribute string
attribute string
attribute string
attribute string
attribute string
attribute string
Class PhoneNr
{attribute string
attribute string

Country;
City;
Street;
ZIP;
State;
Type;}
PhoneNr;
Type;}
12

Type Construction with UML


Set Constructor

complex properties

Tuple Constructor

List or Array Constructor

No dictionary
constructor

13

Type Constructors in Cach

Tuple: Properties of a class


Set:

C A C
A C H
C H

Class automatically gets extent if it inherits from


%Persistent
No set-operator for components:
Property x As set Of Y; not possible
Use list- or array-constructor instead, or relations

Bag: not supported


List: list Of
14

Type Constructors in Cach

C A C
A C H
C H

Array: not directly supported, use dictionary with


integer key values
Dictionary: array Of
Array in Cach is Dictionary in ODMG-Model !

15

Example: Persons in Cach

C A C
A C H
C H

Class Person Extends (%Persistent)


{Property Name As NameCl;
Property DOB As %Date;
Property Addresses As list Of Address;
Property PhoneNumbers As list Of
PhoneNumber;}
Class NameCl Extends (%SerialObject)
{Property FirstName As %String;
Property SecondName As %String;
Property LastName As %String;
Property Title As %String;
Property Salutation As %String;}
back

16

Example: Persons in Cach

C A C
A C H
C H

Class Address Extends (%SerialObject)


{Property City As %String;
Property Street As %String;
Property ZIP As %String;
Property Country As %String;
Property State As %String;
Property Type As %String;}
Class PhoneNumber Extends (%SerialObject)
{Property PhoneNr As %String;
Property Type As %String;}
17

Type Construction: Saving Accounts

Practice: Define the object type of Saving Accounts


as complex type graphically:

Different types: fixed term, open term, compound interest


Interest rate may increase every year: 2% - 3% - 3.5%
Transactions on account

Define the same object type in Cach


What are the consequences of recursive types,
e.g. if Person contains a set Friends of type
Person?
18

Type Construction for Saving Accounts


Graphical Representation
Set Saving Accounts

Tuple

Saving Account
Transactions

string
Type

string

date

Account Begin
Number

date
End

float

Arr. Interest

Current
Amount
Index: int

redundant
information

List

Year

Tuple

Transaction

Value: float InterestRate

string

date

Sender Date

float

string

Amount Purpose

19

Operations on Complex Types

Tuple constructor

Access to components
Test two tuples on equality

All collection operators

Test if collection is empty


Test if collection contains a certain element
Access to all elements (iterator)
Insert, update, or delete element

20

Operations on Complex Types (cont.)

Set constructor

Bag constructor

Set comparisons: =,
Set operations: intersection, union, difference
Number of occurencies of an element
Set operations: intersection, union, difference
No set comparisons

List construktor

Access in sequence of list


Insert at certain position or after certain element
Concatenation of lists
21

Operations on Complex Types (cont.)

Array constructor

Access to elements at certain index

Dictionary constructor

Access to elements at certain key


Test whether certain key is in dictionary
Bind a value to a certain key (insert)
Unbind a value from a key (delete)

22

Operations on Complex Types


in Cach

C A C
A C H
C H

Persistent classes (tuple and set constructor)

Access to components by dot-syntax


p1.Name.FirstName if p1 is a Person object
Test if object exists:
class methods %Exists(oid) and %ExistsId(id)
Retrieve stored objects into memory:
class methods %Open(oid) and %OpenId(id)
Insert or update an element: %Save()-method
p1.%Save()
Delete an element:
class methods %Delete(oid) and %DeleteID(id)
Iterator to access all objects of a class: query Extent()

23

Methods for List- and Array(Dictionary-) Collections


Method

Purpose

C A C
A C H
C H

Success Failure

List: Insert(value)
Add value to
collection
InsertAt(value, index)
Array: SetAt(value,key)

error
status

List: InsertList(list)

Appends list

error
status

Find(element)

Tests whether
index or ""
element is in list key

GetAt(key)

Get value at key value

""

24

Methods for List- and Array(Dictionary-) Collections (cont.)


Method

Purpose

C A C
A C H
C H

Success Failure

RemoveAt(key)

Remove object
key

value at ""
key

Count()

Count items

integer

Clear()

Empty collection 1

error
status

25

4.2 Classes: Type- and Set-View


Class has different meanings:
Set of objects belonging together
Container for all hitherto created objects of the class
Type = construction schema of the objects
Domain for (abstract) objects

A state function maps each object to its value, an


element of the domain.

26

Concepts for Classes: Type-based


class Line

Line x

Point begin;
Point end;
int width;

(3;15);
(5;17);
6;

type of

Line a2

Line yxa
(3;15);
(1;1);
6;

(3;0);
(5;17);
2;

A class defines a complex type


Objects of the class are not gathered in a container
This is the situation in programming languages like C++
27

Concepts for Classes: Set-based

Line x

Line gt

(3;15);
(5;17);
6;

"p1";
"p2";
"thin";

Line a2
4
1
r

x 5 k 2
6


3

A class is a container
Types of the elements are not fixed
28

AND class is
container for
objects (extent)

Set-type-based
Line x
class Line
Point begin;
Point end;
int width;

class defines
a complex
type

(3;15);
(5;17);
6;
Line a2

Line yxa
(3;15);
(1;1);
6;

(3;0);
(5;17);
2;
This is the solution in OODBMSs
29

4.3 Relations between Classes

Every class consists of attributes


(= properties = components)
Their types can be atomic types or classes.
Class-componentclass-relations implement
relationships between different classes
Distinguish: class-subclass-relation see 4.5
Different semantics of component classses

shared/private component objects


dependent/independent component objects
encapsulated/standalone component objects
unidirectional/mutual component relation

30

Shared/Private Component Objects

Shared component objects:

A component object is component of many objects


An object can be component of objects of different
classes
M:N(1)-relation between component class and class
Example: Branch is shared component of ATM

Private component objects:

Each component object is component of only one object


1:N(1)-relation between class and component class
Example: ATM is private component of Branch
31

Dependent/Independent
Component Objects

Dependent component objects

only exist with object they are component of


are created/deleted with object they are component of
Shared dependent objects are deleted with last object they
are component of
Example: Name is dependent of Person

Independent component objects

can exist without another object


are created and deleted independently
If you delete a component object, take care of objects
which have it as a component.
Example: Branch is independent component of an ATM

32

Encapsulated/Standalone
Component Objects

Encapsulated component objects

are only accessible by their superior objects.


are always dependent
Redundancy when used for M:N-relations
Example: Name is encapsulated in Person

Standalone component objects

are accessible independently or


by the objects which have them as component.
Example: Branch is an standalone class. A branch is
accessible without an ATM- or employee-object
33

Unidirectional/Mutual Component Relation

Unidirectional component relation

One object is obviously the superior object, the other the


component
No direct way from the component to its superior object
Example: Person Name, Car Motor

Mutual component relation

Each of two objects has the other one as component.


Implements bidirectional relationship between two
classes
Example: Branch ATM
34

Different Types of
Component-Classes

Practice: Decide which is the type for the following


examples of classes and component classes:
shar

priv

enc

aut

dep

ind

dir

Buildings Rooms
Countries Towns
ATMs Currency Orders
Lectures Students
Books Publishers
Books Pages
Folders Files
Parents Children
35

Different Possibilities for Relationships:


a) Encapsulated component class
Complex objects with encapsulated objects of
component class

Suitable for fr 1:1- and 1:N-relations


Redundancy when used for M:N-Relations
Access not symmetrical:

Easy from object to component


Difficult from component to parent object
See example Person
NameCl is encapsulated in Person because it inherits from
%SerialObject

37

Different Possibilities for Relationships:


b) Mutual Component Classes
Two classes have each other as component

Can be used for 1:1-, 1:N- and M:N-Relations


Symmetrical access
System must ensure symmetry
The relation must not have attributes of its own. E. g. the
examination results of students in the relation "Students
attend Lectures" cannot be represented

Possibility c) later
38

Relationships in Cach

A relationship is a two-way link between an object of


one class and several objects of another (possibly
the same) class.
Relationship types:

Independent (One-to-many).
Dependent (Parent-to-children).

C A C
A C H
C H

Children stored together with parent


However not encapsulated (children get own object identifiers)
Classes must be different in this case.

Indirectly supported: One-to-one.


Not supported: Many-to-many, use connection class
39

Relationships in Cach (cont.)

C A C
A C H
C H

Relationship specified in both class definitions.

Relationship statement:
specialized Property statement.
One, many, parent, and children define cardinality of
each side of relationship.

40

Example:
Branch and ATM Class Model
FCE.Branch
Phone
Opens
Closes
ATMs

FCE.ATM
0..* Branch
CurrencyBalances

0..1
1

0..1

FCE.RealEstate
1

Street
City
State
Zip

C A C
A C H
C H

Practice: Discuss the


possibilities to implement
the relation
"Branch has ATMs"
41

Cardinality of Relationships in Cach

Cardinality: number of elements on each side of a


reference.
Describe cardinality in terms of classes.

C A C
A C H
C H

FCE.Branch has a parent-to-children relationship with


FCE.ATM. Multiple ATMs belong to each branch.

Specify cardinality in terms of properties.

The ATMs property of the FCE.Branch class has


cardinality/type Children. The Branch property of the
FCE.ATM class has cardinality/type Parent.

42

OOP Relationship Advantages

Relationship is a combination of a reference and a


list collection.

C A C
A C H
C H

Performance degrades as number of objects on


many/children side surpasses 900-1000.
In v4.1, use of CACHETEMP reduces degradation.

When classes are persistent, relationship provides


referential integrity for object deletions on
one/parent side.

43

SQL Relationship Advantages

C A C
A C H
C H

When classes are persistent:

Many/children table has foreign key from one/parent


table.
Relationship provides referential integrity for row
deletions on one/parent side.

44

Referential Integrity

For relationships between persistent classes from


A to B
One-to-Many:

Deletion of an object of class A fails as long as it points


to at least one object of class B.
To delete an object of class A, delete the references to it
from objects of class B.

Parent-to-Children:

C A C
A C H
C H

Deletion of an object of class A deletes all related objects


of class B.

Same is true for rows in tables.


45

Demonstration:
Create a Relationship

C A C
A C H
C H

Create two classes.


Add a property to one class.

Specify name.

Use plural name for property with cardinality many/children, and


singular name for property with cardinality one/parent.

Specify property as a relationship.


Specify cardinality: One, Parent, Many, Children.
Specify type: reference second class.
Specify name of relationship property to be added to
second class.

46

Cach:
Simulate One-to-One Relationship

C A C
A C H
C H

Create one-to-many relationship.


Change index added on property with cardinality =
one (in many class) to unique.
Results:

Prevents object on one side from being referenced by


more than one many object.
Prevents deletion of object on one side.

But doesnt prevent deletion of object on many side.

47

Using Relationships

Link objects in two equivalent ways:

C A C
A C H
C H

Insert many/children into one/parent collection.


Reference one/parent from many/children object.

No control over ordering of many/children in


one/parent collection.

To control ordering, use list- or array-constructor

48

Using Relationships (cont.)

C A C
A C H
C H

From one/parent side, many/children side is a


collection. To link, either:

Insert many/children object into one/parent objects


collection:
do branch.ATMs.Insert(ATMOne)

Insert many object ID directly into one objects


collection, without opening object (only for one-to-many):
do branch.ATMs.InsertObjectId(atmid)

Insert new many/children object into one/parent objects


collection:
do branch.ATMs.Insert(##class(FCE.ATM).%New())
49

Using Relationships (cont.)

C A C
A C H
C H

From many/children side, one/parent side is a


reference. To link, either:

Reference one/parent object from many/children object:


set ATMOne.Branch = branch

Set one/parent object ID into many/children object


directly, without opening one/parent object, using
PropertyNameSetObjectId() method.
do ATMOne.BranchSetObjectId(branchid)

50

Storing Relationships

C A C
A C H
C H

Calling %Save() on either one/parent or


many/children triggers save of entire relationship.
IDs of Children in Parent-to-Children relationship
depend on parent ID. Format: parentID||childID.

51

Implicit Joins

In a query, using -> operator on a foreign key


column allows direct references to columns in
foreign table.
Syntax:

table.foreignkey->column

Joins:

C A C
A C H
C H

-> operator in SELECT clause creates LEFT OUTER


JOIN.
-> operator in WHERE clause creates INNER JOIN.

Transmits efficiency of OO-model to SQL


52

Implicit Joins (cont.)

C A C
A C H
C H

May be chained.
select Branch->Address->Street

Options when querying tables of a parent-tochildren relationship:

childtable.parentforeignkey->columninparenttable
parenttable.childtable->columninchildtable

Works even though childtable is not a column in parenttable.


Specify childtable without schema.

53

Practice: Query with -> Operator

Write a query with join-conditions, that

finds the name and street of all branches


where the phone-number begins with 6
together with the streets of all ATMs

Define 2 queries for this task using the -> Operator

starting at the Branch-table


starting at the ATM-table

C A C
A C H
C H

54

Different Possibilities for Relationships:


c) Connection Class

The relation becomes an own class

Suitable for M:N-relations with attributes of their own


Two 1:N-relations from each class to connection class
In Cach necessary for every many-to-many relation

Example: Employees advise customers

Different employees advise customers in different areas


like loans, investments, or online banking

Employee

advises
0..*
relation with
attribute

0..*
Customer
advisers
subject area
55

Different Possibilities for Relationships:


c) Connection Class

The relation becomes an own class

Suitable for M:N-relations with attributes of their own


Two 1:N-relations from each class to connection class
In Cach necessary for every many-to-many relation

Example: Employees advise customers

Many employees advise many customers in different


areas like loans, investments, or online banking

advises
Employee
1

0..* Customer customer


employee contacts

connectio
n class

subject
area

attribu
te

0..*
Customer
advisers

56

Summary: Different Possibilities to


Implement Relationships in Cach

Component class %Serializable

Use for bidirectional, private, independent, standalone components

Relationship parent-to-children

Use for unidirectional, private, dependent, standalone components

Relationship one-to-many

Use for unidirectional, private, dependent, encapsulated


components

Component class %Persistent

C A C
A C H
C H

Use for bidirectional, private, dependent, standalone components

Connection class

Use for bidirectional, shared, independent, standalone components


Relations with own attributes
57

4.4 Object Identity


Disadvantage of Keys

No difference between update of an objects value


(content) and its identity (key), e. g. name of a
branch
Problem, when many objects contain the same
component object (e. g. ATMs of a branch)
It is not possible to have different objects with the
same key value.
Queries require inefficient joins.

58

Types of Object Identity

Sum of all values, not practical because:

Values can change


Object in DB only contains subset of values of real object

Values of characteristic attributes

E. g. fingerprint or DNA for real persons


Difficult to store in DB
Not applicable for all classes,
e. g. chairs in a lecture room

59

Types of Object Identity

Physical addresses, direct references, pointers

User defined names of a name domain

Pointers point to component-objects


Pointers point to begin of a list for set attributes
e. g. license numbers of cars

Automatic keys = surrogate keys = identifier


attributes (implementation obvious)
Abstract objects (implementation hidden to user)

60

Distinguish Objects and Values


Objects

Example:
Branch "City Hall"
are not printable
must be created and
defined
carry no information
itself
are described by the
values of their attributes

Values

Example :
number 182
printable
already exist
carry information
themselves
describe objects

61

Object Identity by Physical Addresses

Example: Identify buildings by their Addresses


Advantages

simple implementation
efficient access of components
address is not a value of the object

Disadvantages

physical data independence violated


object cannot be moved
Delete an object. Is physical address reusable?
62

Object Identity by Names

Example: Names of persons


Advantage

Name can be structured, easy to read: first- last name.

Disadvantages

can be interpreted as value


Name can change (e. g. marriage)
Uniqueness must be checked
keys!

63

Object Identity by Surrogate Keys

Examples: AutoNumber in Access, SEQUENCE in


Oracle
Advantages

Uniqueness guaranteed by system


cannot be changed
carries (nearly) no information, is substitute for object

Disadvantages

Foreign key constraints must be defined


Surrugate keys can be interpreted as values.

64

Example:
Saving Accounts with Identifier-Attributes
SET OF (TUPLE OF
(Account_Nr: IDENTIFIER,
Type: STRING,
Begin: Date,
End: Date
Account_Holder: IDENTIFIER,

Transactions: LIST OF(TUPLE OF


(Trans_ID: IDENTIFIER,
Amount: INT
))))
65

Saving-Accounts with Identifier-Attributes


Account Type Begin End
_Nr

Account Transactions
_Holder

172963 varia 12.


ble
JUN
2002

54355

1; 456 $; 1.7.02;
2; -63 $; 5.7.02;
3;

134584 incr. 1.
inter AUG
est
2005

31. 37704
JUL
2009

1; 456 $; 1.8.05;
2; 11 $; 31.12.05;
3;

66

Object Identity with Abstract Objects

Objects are elements of a

not structured,
countably infinite,
abstract set
with the only information that
the elements are different

Abstract objects can be


implemented (more or less
well) by

physical addresses
Names
Identifier-attributes

Operations on objects

Create new object


Delete object
Test on identity
You never can print or see
an object itself or its Id
67

Graphical Representation using


State-Boxes
Representation is difficult, since objects cannot be printed.

object
19
19

State of object 19
Hugo Ross
1 May 89
2

State of object 2
5 Garden Ave
San Francisco, CA
88250
68

Abstract Objects

Advantages

Disadvantage

independent of the implementation


theoretically sound
foreign key constraints automatically guaranteed
implemented only in very few real OODBMS

Two versions

One infinite set with abstract objects for all classes


Disjoint domains of abstract objects for each class
69

Saving-Accounts with Abstract Objects and


Disjoint Domains
Acc Acc.Nr
ount

Type Beg.

End

Acc.
Transactions
Holder

172963 varia 12.


ble
JUN
2002

1; 2 ; 3 ;

134584 incr.
inter
est

4 ; 5 ; 6 ;

1.
31.
AUG JUL
2005 2009

1 is not the name of an account holder, not the key of an


account holder, but the whole object of type customer.
70

Operations on Objects

Create new or delete existing object


Dereference objects to get their values
Test on identity: o1 == o2
e. g. father of Peter == father of Susan
Test on shallow equality (of values)
Test on deep equality (of values)
Assignment: create a reference to an object and
assign it to a variable
Create shallow copy
Create deep copy

71

Comparison of Objects

Philosophical question:
When are two objects identical?
Different comparisons

Test on identity: Do two object-references refer to the


same object?
Test on equality: Have two possibly different objects the
same values?
If objects have component objects, compare whether the
component objects are identical: shallow equality
or whether the component objects have the same
values: deep equality

Similar questions when copying an object

72

Practice: Operations on Objects

Create a new saving-account 3


by shallow copying 1

Create a new saving-account 4 by deep copying 1

Test on shallow equality of 1 and 3?

Test on deep equality of 1 und 4?

Assign 1 to variable MyPrimaryAccount

1 == MyPrimaryAccount?

1 == 3?

Why are private component-objects a problem for


shallow copying?

73

C A C
A C H
C H

Object Identity in Cach

Every class gets

%New()-method to create objects in memory


and %Save()-method to store them permanently in DB

Difference between oref

An oref is a temporary
identifier for an object in
memory.
Remove object from memory
oref is no longer valid
cannot be printed

and object ID

An object ID is a permanent
identifier for a stored object
is automatically created by
%Save()-method
never changes
can be used to locate or
delete an object in the DB
can be printed

Cach guarantees correspondence of orefs and object IDs


76

Object Identity in Cach (cont.)

An object Id behaves like an abstract object,


because it

C A C
A C H
C H

is added as property for every class


is automatically created when an object is saved for the
first time
cannot be changed by the user

An object Id behaves different from an abstract


object, because it

only exists for stored objects


can be printed
can be used to retrieve a stored object into memory
carries information whether the object is encapsulated

77

Object Identity in Cach (cont.)

IDs are class specific; ObjectId = Id + ClassName


Cach does not provide functions for

C A C
A C H
C H

testing shallow equality


testing deep equality

If needed these functions must be programmed


Create a copy of an object with the method
%ConstructClone()

deep copy with parameter deep = 1


shallow copy with parameter deep = 0
private component-objects are cloned even with
parameter deep = 0; to avoid this, use deep = -1

78

4.5 Inheritance

Special relation between objects of different


classes "is a", e. g. Customer Miller is a Person
Type inheritance: Let T_super and T_sub be types.
T_super is super type of T_sub,
T_sub subtype of T_super

for atomic types if T_sub T_super


e. g. short int long int
for tupel-types, if T_sub has at least all components of
T_super hat, e. g. Customer and Person
for set-types, if the element-type of T_sub is subtype of
the element-type of T_super
79

Inheritance (cont.)

Class (set) inheritance


Let C_super und C_sub be classes

C_sub is more special than C_super, if


set of objects (C_sub) set of objects (C_super)
C_sub is subclass, C_super is superclass

Class and type hierarchy fit together, e. g.

Class hierarchy: Customers Persons


Type hierarchy: Customer has all attributes of Person
and additional ones Customer is subtype of Person
DBMS guarantees that every object in class Customer is
in class Person, too.
Define type inheritance, get set inheritance for free

80

Operations for Inheritance

Specialization

defines subclasses by inheritance of a superclass


Not all objects of a superclass must be elements of one
of its subclasses.

Generalization

combines classes to a collective superclass


All objects of all subclasses become elements of the
superclass
Often used to define abstract superclasses to simplify
programming, e. g. generalize Branch and ATM to
CashLocation
81

Class Tree and Class Graph

Specialize subclasses class tree


animals

vertebrates

mammals

invertebrates
birds

82

Class Graph
Person

A subclass inherits
from more than one
superclass
(multiple inheritance)
class graph
Not allowed in all
object oriented
systems
Supported by Cach

Addresses

Name: String
DOB: Date
Phone: String
Email: String

Employee
Salary: Float
ESince: Date
Qualification: String

Customer
Type: String
CSince: Date
Rating: String

EmpCust
InterestBonus:
Float

83

Inheritance in ER-Diagrams
Example: ER-Diagram of a personal address-book
Name

Address

Phone

Person

Colleague
RoomNr

WorkPhone

Friend
DOB

Hobbies

84

Problems

An object cannot be element of different classes

Store a colleague who is also your friend


new class ColleagueFriend necessary
Explosion of combination classes
Class with n subclasses 2n - n - 1 combination classes

Objects can't change their class to a subclass

E. g. colleague becomes friend


Object must be deleted and created anew

85

Inheritance in Cach

Single or multiple inheritance


Overriding of properties or methods possible

C A C
A C H
C H

To override a property, method argument, or method


return value datatype,
new datatype must be original datatype or its subclass.
To override a method, new method may have more
arguments than original method, but not fewer.

Abstract Classes (objects only in subclasses)


Syntax:
Class Subclass Extends Superclass
Class Subclass Extends (SC1, SC2, )
86

Multiple Inheritance in Cach

C A C
A C H
C H

Cach supports multiple inheritance.


Class FCE.ATM Extends (%Persistent, %Populate,
%XML.Adaptor)

In superclass list, order is important.

First superclass provides class parameters and


members to subclass.
Other superclasses provide class members only.
Member name conflicts resolved in favor of superclass
listed latest (reverse order of superclass list).

87

Multiple Inheritance in Cach (cont.)

C A C
A C H
C H

Additional superclasses can provide:

Complete methods for usage by subclasses.


Method generators to generate code specific to
subclass.
Empty methods for subclasses to implement.

Similar to Java's Interface concept.

88

Abstract Classes

Even though a superclass can define properties


and methods, it might not be meant for object
instantiation.

To prevent object instantiation from superclass, set


Abstract attribute to True.

C A C
A C H
C H

New Class Wizard also allows creation of an abstract class.

Application code instantiates objects from concrete (nonabstract) subclasses.

Suitable for

Generalization, if the superclass only is created to


simplify programming
disjoint partition of a superclass in subclasses

89

Discussion of Abstract Classes


Example: Person Class

Is FCE.Person abstract?

If yes, application code cant create a Person object;


only Customer and Employee objects.
If no, application code can create Persons, Customers,
and Employees.

If abstract, FCE.Person class contains properties


and methods common to all types of persons.

FCE.Customer and FCE.Employee concrete subclasses.

90

Abstract Methods

Methods of an abstract superclass may optionally


contain code to be inherited.
Setting a superclass methods Abstract attribute to
True shows that method doesnt contain code.

C A C
A C H
C H

Subclasses should override method and provide code


particular to the subclass.

Application code cant call an abstract method.

Similar to Private.

91

Practice: Create Class Graph

A car dealer not only sells cars but also journeys.


Create a class graph with UML for the following
classes:

Vehicle
Car
Truck
Journey
Person
Customer
Employee
Sale
92

4.6 Query Operations

Class specific operations:

Each class has its own methods.


A programmer has to implement these methods.
Disadvantages:

A lot of work to do.


It is not possible to decide whether set of operations is complete.
Possibly bad performance.

Generic Operations:

General database operations provided by the system


generate class specific operations for every class
Disadvantage: Encapsulation of objects violated
93

Generic Query Operations

Operation
Projection
Selection
Join
Union
Intersection
Difference

Object oriented concept


Supertype
Subclass (Subset)
Subtype of two types
Superclass (Superset)
Subclass of two classes
Subclass
Grouping
Degrouping
Object navigation
94

Grouping

Properties of a relation are combined to a new


property.

The new property is a set.


This can be interpreted as nested relation.

Degrouping is the opposite operation.

95

Example for Grouping:


Situation before Grouping
ATM Branch Brand SerialNr Address CurrencyBalances
15

UBX

123-5

102

Euro 3075
USD 4788

16

UBX

123-7

370

Pound 2350
USD 5340

17

Abam 112675

20

Rupees 3900
USD 3340

18

T.C.C. 45-44-6 876

Euro 5150
USD 2500

96

Example for Grouping:


Situation after Grouping by Brand
Brand ATM Branch SerialNr Address CurrencyBalances
15

123-5

102

Euro 3075
USD 4788

16

123-7

370

Pound 2350
USD 5340

Abam 17

112675

20

Rupees 3900
USD 3340

T.C.C. 18

45-44-6 876

UBX

Euro 5150
USD 2500

97

Object Navigation

C A C
A C H
C H

If you have a certain object, you can directly


access related objects.
Use dot-syntax.
Example: Print the street names of all ATMs
belonging to the branch in object brchMain
for i=1:1:brchMain.ATMs.Count() {
write ! brchMain.ATMs.GetAt(i)
.Address.Street
}

98

Result Sets in Class Hierarchy

Results of a query are organized in result sets.


An iterator provided by the result set allows to
step through the elements of the result set.
Three possibilities for the elements of result sets:
a)

b)

c)

Relational operation: The elements of the result set


are no objects, the result set is a pure relation.
Object generating operations: Generate new objects
of a new abstract class.
Object conserving operations: The elements of the
result sets are the existing objects.
99

Example:
Projection of ATMs to Brand and SerialNr
b)
a)

New-Obj Brand SerialNr

Brand SerialNr

15

UBX

123-5

UBX

123-5

16

UBX

123-7

UBX

123-7

17

Abam 112675

18

T.C.C. 45-44-6

Abam 112675
T.C.C. 45-44-6
c)

ATM Brand SerialNr


15

UBX

123-5

16

UBX

123-7

17

Abam 112675

18

T.C.C. 45-44-6
10

Degrouping cannot be object conserving


ATM Branch Brand SerialNr Address CurrencyBalances
15

UBX

123-5

102

Euro 3075

15? 3

UBX

123-5

102

USD 4788

16

UBX

123-7

370

Pound 2350

16? 4

UBX

123-7

370

USD 5340

17

Abam 112675

20

Rupees 3900

17? 3

Abam 112675

20

USD 3340

18

T.C.C. 45-44-6 876

Euro 5150

18? 4

T.C.C. 45-44-6 876

USD 2500

10

Queries in Cach

Cach uses SQL for queries with extensions for


object oriented access:

C A C
A C H
C H

Implicit join operator "->"


Calculated properties
Encapsulated components are automatically unfolded as
columns in the corresponding table in the form
ParentTableColumn_ComponentColumn e. g.
Name_FirstName in Person

Advantages:

Well known standard.


Object view by implicit join operator.
10

Defining Class Queries

Class queries are SELECT queries only, saved


with class.

C A C
A C H
C H

New Query toolbar button provides wizard to help build


proper SQL statement.
Build complex statement by hand.

Query can use input parameters, to be supplied at


runtime. For example:
where amount > :variable

Host variables replaced with value of parameter when


query runs.
10

Class Queries (cont.)

C A C
A C H
C H

You can use relational or object conserving


operations, depending whether the object id is
retrieved by the query.
Code generated when class is compiled.
%ResultSet class provides OOP access to any
class query.
ODBC/JDBC access as Stored Procedure.
Every persistent class has Extent class query that
returns every ID in extent.

Add EXTENTQUERYSPEC class parameter to specify


additional columns for Extent query.
10

Example: Class Query

C A C
A C H
C H

Retrieve all branches with ATMs in the area with a


certain ZIP code

Query HasATMinZIP(ZIP As %String)


As %SQLQuery(CONTAINID = 1)
{
SELECT %ID,Name,Phone,ATM->Address->Zip
FROM Branch
WHERE ATM->Address->Zip = :ZIP
}

10

Practice: Create Class Query

Create a class query to find all ATMs that have


a certain currency, e. g. Indian Rupees, in their
CurrencyBalances

currency is a parameter
Use Implicit join operator
(for more information refer to slide Implicit Joins)
You have to use the SQL-Name of the property
CurrencyBalances: ATM_CurrencyBalances
The currencies' names are stored in the column
element_key of ATM_CurrencyBalances
10

Using the Predefined Query Extent()


Example: Branch

C A C
A C H
C H

Create new result set


Set rset = ##class(%ResultSet).%New
("FCE.Branch:Extent")

Execute query: Do rset.Execute()


Step through result set
While (rset.Next()) {
set br = ##class(FCE.Branch).%OpenId
(rset.Data("ID"))
if br.Closes < PIECE($HOROLOG,",",2)
{write br.Name _ " already closed",!}
}
10

Class Queries used as Views

Object conserving operations define virtual classes


Example: Select all ATMs manufactured by UBX;
call the class query UBX-ATM.
UBX-ATM is subset of ATM.
UBX-ATM is automatically updated when ATM is
updated.
Virtual classes correspond to VIEWS in the
relational model.
Object conserving operations avoid explosion of
new classes.
10

4.7 OQL Object Query Language of


ODMG

Superset of SQL SELECT


Differences and enhancements to SQL:

OQL is orthogonal i. e. the result of a query, operator or


function can be used as part of other queries as long as
the types fit.
A dot (".") or an arrow (") can be used to access
components (implicit join)
Access to methods
OQL not only can query sets but also other structures:
bags, lists, arrays, and dictionaries
Constructor or destructor operations instead of insert or
update respectively.
11

Overview of OQL

Syntax structure of an OQL select-query


SELECT defines data to be retrieved and structure of data
FROM
specifies collections referenced by the query and
variables to iterate over those collections
WHERE specifies conditions for selecting objects

Following slides present examples how to use OQL


More information

R.G.G. Cattell. The Object Database Standard: ODMG 2.0. Morgan


Kaufmann, San Francisco, California, 1997.
http://www.openquasar.de/de/components/quasar_persistence/oql.html
http://www.eas.asu.edu/~cse494db/notes/oodbNotes/odmg_oql_mar2002.ppt
111

OQL and PATH EXPRESSIONS


Navigation Through Objects

Path expressions are used to navigate from one


object to another.
Use dot (".") or arrow (")
Example: DISTINCT
SELECT p.Name.LastName
FROM Persons p
WHERE pNameTitle = "Dr."
Equivalent: FROM p IN Persons
Persons is extent of persistent class Person
Set <string>
Result is a set
multiset of literals; type Bag

11

OQL:
Traversing Attributes and Relationships

OQL does not allow path expressions to traverse


over multivalued attributes and relationships.
Example: not allowed
SELECT b.Name,b.ATMs.Address.Street
a
FROM b IN Branch , a IN b.ATMs
a
WHERE b.ATMs.Address.ZIP
= '022456'
Use instead variable a for ATMs

11

OQL Extracting from Lists and Arrays

OQL provides an explicit notation for extracting the


ith element from lists and arrays.
The first element in any indexed collection is
assumed to be 0.
OQL also provides the operations: first and last
Examples:
LIST(a,b,c,d)[1]
LIST (a,b,c,d)[1:3]
FIRST(LIST(a,b,c,d))
LAST(LIST(a,b,c,d))

b
LIST (b,c,d)
a
d

Convert a list to a set

LISTTOSET(LIST(1,2,3,2)) {1,2,3}
11

OQL: Access Single Elements and


Complete Extent

The ELEMENT-operator converts a set with one


element into this element :
ELEMENT(
SELECT a
FROM a IN ATM
WHERE a.SerialNr = '543-346-XX')
Select all objects of class Person:
Persons

11

OQL: Embedded Queries

Example:
SELECT a.Address.Street
FROM a IN (SELECT a
FROM Branch b, a IN b.ATMs
WHERE b.Opens < '08:00:00'
WHERE a.Brand = 'T.C.C'

Subquery also possible in SELECT- and WHEREpart

11

OQL: Structuring Results and Grouping

GROUP BY provides explicit reference to the


collection of objects within each group or partition.
Example:
SELECT STRUCT
(Manufacturer,
ATMSerialNr: (SELECT p.a.SerialNr
FROM p IN PARTITION)
)
FROM a IN ATM
GROUP BY Manufacturer: a.Brand

Result type: Struct <string, Set <string>>


11

OQL: Aggregate Functions

OQL provides aggregate operators (min, max,


count, sum, avg) over a collection.
Example:
SELECT STRUCT(BranchObj: b,
NrATMs: COUNT(b.ATMs))
FROM b IN Branch

Result type: Struct <Branch, integer>

11

OQL Quantification

Existential quantification: exists x in e1: e2

TRUE if at least one element of e1 satisfies e2


Example: Select Branches with at least one ATM from
UBX?
SELECT b FROM Branch b
WHERE EXISTS a IN b.ATMS: a.Brand = 'UBX'

Universal quantification: for all x in e1: e2

TRUE if all elements in e1 satisfy e2


Example: Select Branches with ATMs only from UBX
SELECT b FROM Branch b
WHERE FOR ALL a IN b.ATMS: a.Brand = 'UBX'
11

Practice:
Define OQL Queries

Find all ATMs which can supply at least 1000


"Indian Rupees".
Find all managers with the number of employees
they supervise; result should be a structure.
Managers supervise at least one employee.
Find serial numbers and streets of all ATMs
belonging to branch "London Westend" which have
at least one currency order that was approved by
"Martin Holmes".
12

Practice Solution:
Define OQL Queries

Find all ATMs which can supply at least 1000 "Indian


Rupees".
SELECT a FROM a IN ATM
WHERE EXISTS c IN a.CurrencyBalances:
c.Currency = 'Indian Rupees' AND
c.Balance >= 1000

12

Practice Solution:
Define OQL Queries

Find all managers with the number of employees


they supervise; result should be a structure.
SELECT STRUCT (
Manager: m,
NrSubs: COUNT(m.Subordinates))
FROM m IN Employees
WHERE NrSubs > 0

12

Practice Solution:
Define OQL Queries

Find serial numbers and streets of all ATMs


belonging to branch "London Westend" which have
at least one currency order from Mr. "Hog".
SELECT STRUCT (
SerialNr: a.SerialNr,
Street: a.Address.Street)
FROM a IN ATM, c IN a.CurrencyOrders
WHERE c.Requestor = 'John Hog' AND
a.Branch = 'London Westend'
12

4.8 Methods

perform class specific operations


are a major difference to pure relational model
allow to combine structural and operational
development of an application.
can be class methods or instance methods
can be inherited from superclasses
Polymorphism: Subclass overrides method
inherited from superclass

12

C A C
A C H
C H

Generic Update Methods


Operation

Object oriented operation

Operation in Cach

Insert

Constructor

%New() classmethod
%Save() instancem.

Update

Access to attribute

set obj.property =
NewVal

Delete

Persistent destructor

%DeleteId(Id)
classmethod

Insert Copy

Copy

%ConstructClone(d)
d: deep or shallow
copy
12

Where to Code User Specific Methods?


In Database or in Client Application?

Code methods in database classes, if they

are used by many different client applications


access other persistent objects
query database or perform database operations
build a unity with the attributes

Code methods in client application, if they

perform time consuming calculations


need a large amount of main memory
belong to the user interface
are invoked concurrently by many clients to use parallel
processing on many client computers.
12

Practice:
Client or Server Side Method

Where would you code the following methods?


Discuss with your neighbor. Find other examples for
client side and for server side method.

Sum up the amounts of available money for each


currency in all ATMs
A currency exchange transaction is prepared at home.
Calculate the amount of money to be supplied for a
certain requested currency value.
A CAD application stores data of the developed machines
in a database. The engineer can view a drawing of the
machine from different perspectives, turn it etc. Calculate
the drawing.
12

Methods in Cach

Code written in ObjectScript:

allows use of embedded SQL and


macros.

or in Cach Basic (similar to Microsoft VBScript).


Set Language attribute of a class (for all methods)
or individual method(s).
Can be mixed.

C A C
A C H
C H

ObjectScript can call Basic.


Basic can call ObjectScript.

Both languages compile to same OBJ code.


12

Inherited Methods

C A C
A C H
C H

Classes that extend other classes inherit their


methods.
For example, new persistent classes inherit
methods of %Persistent class.

13

C A C
A C H
C H

Method Signature
arguments
method name

argument name

default value

Method MyMethod (Arg1 As %String = 'abc', Arg2 As %Numeric)


As %String
{
argument type
set x =
}

body

return type:
result of calculation or
object or
status

13

Method Arguments

C A C
A C H
C H

Arguments are private to method.


Caller is not required to supply all arguments to a
method:
do ##class(Package.Class).Method(1,,3,,4)

Method must either provide default value for each


argument, or use $data or $get to check argument.
Method Test(a as %String = 1, b as %String)
as %String
{
if '$data(b) { code here }
}
13

ObjectScript Arguments

Pass by value.

C A C
A C H
C H

Default. Use ByVal in Code Window to make explicit.


Value passed in for input only.

Pass by reference.

Optional. ByRef in Code Window required.

Inspector uses & before name.

Reference passed in for input and/or output.


Optionally, use Output in Code Window to document that
argument is for output only.

Use * before name in Argument dialog.

13

ObjectScript Arguments (cont.)

Pass by reference/value is for documentation


purposes only.

Shows user how to call method.

Caller, not signature, determines whether argument


is passed by reference or by value.

C A C
A C H
C H

Period before argument specifies pass by reference.

For example:

By value: do oref.Method(a,b)
By reference: do oref.Method(.a,.b)

13

Objects as Arguments

Object arguments may be OREFs.


If method changes properties of object only, object
argument may be passed by value.

C A C
A C H
C H

Argument inside method references same object as


calling method.

If method changes object argument to reference a


different object, argument must be passed by
reference, in order to return new object to caller.

13

Method Overloading

Cach doesnt provide method overloading in a


way similar to other languages such as Java.

C A C
A C H
C H

Cant create multiple methods with the same name in the


same class.

To simulate method overloading in Cach:

Use $data/$get to check arguments.


Call different code depending on which arguments are
sent.

13

Private Methods

Methods are public by default.

C A C
A C H
C H

Methods of other classes can use a public method.

Set Private attribute to True to make method


private.

Only methods in same class or subclasses can use a


private method.

13

Class and Instance Methods

ClassMethod attribute controls whether method is


class or instance method.

C A C
A C H
C H

True: Call without an object in memory. Use ##class


syntax.
False: Call on a specific object in memory.

Examples:
set branch = ##class(FCE.Branch).%New()
set status = branch.%Save() // save THIS branch

ClassMethod=True and SQLProc=True: method


projected as SQL stored procedure.

13

Relative Dot Syntax

Inside an instance method, use relative dot syntax


(..) to refer to another property or method of current
instance.

C A C
A C H
C H

Read as this objects...


In Cach Basic, use Me.

Examples:

..Property
..Method()

Instance or class method.

..#ClassParameter

ObjectScript only.
13

C A C
A C H
C H

Accessor Methods

All properties have hidden getter and setter


accessor methods.

PropertyGet() and PropertySet() instance methods.


Called automatically when code references property.
Not visible in Studio.

Each pair of statements is equivalent:


write oref.Property

write oref.PropertyGet()

set oref.Property = value

do oref.PropertySet(value)

14

Overriding Accessor Methods

For special property processing when getting or


setting properties, override accessor methods.

C A C
A C H
C H

Last panel of New Property wizard allows this.

Also used for Computed Properties.


Override has no effect on SQL operations.

14

Practice: Develop Method(s) to


Process a Request

A person wants to change money. He/she provides


data for the requested currency, requested amount,
and supplied currency.These data are sent to the
database application and must be processed there.
Discuss the following questions

Which data must the ATM send to the server?


In which class would you implement the method(s) to
process a request?
What is/are the method's signatures?

Develop a concept for the method(s)


(flow chart, sequence diagram, or pseudo code)
14

SQL Stored Procedures

Stored procedure is nothing more than a class


method that is made available to SQL
Stored procedure may be called from an external
tool via ODBC/JDBC.
Class queries are stored procederes

C A C
A C H
C H

Class queries return result set only.


They can't have side effects
SqlProc=True causes query to be listed in catalog for
external tool.

Method Stored Procedures do not return a set of


records

may have side effects.


14

SQL Stored Procedures (cont.)

C A C
A C H
C H

To make class method available as stored


procedure:

Must be class method.


SqlProc=True.

14

Stored Procedure Code

Code can be ObjectScript (with or without


embedded SQL) or Basic.
Method can return value and/or have input/output
arguments (simple data, streams, or objects).

C A C
A C H
C H

Be careful with return value and argument types.

Method can also return result set (refer to


Query Extent() for an example).

14

%sqlcontext Object

C A C
A C H
C H

Code should check %sqlcontext to determine


whether or not method called as stored procedure.
if $IsObject($get(%sqlcontext)) { code here }

Use properties of %sqlcontext to return information


to external tool:

SQLCode: SQLCODE error number, or 0 if no error.


Message: error message text.
RowCount: %ROWCOUNT.

14

Calling a Stored Procedure

C A C
A C H
C H

Returning result set:


call Schema.Table_QueryOrMethodName(arguments)
call Schema.Table_QueryOrMethodName arguments

Using return value as part of query. For example:


select columns
from tables
where column =
Schema.Table_QueryOrMethodName(arguments)

Using ? as placeholder for return value and


input/output arguments:
? = Schema.Table_QueryOrMethodName(?, ?)

14

Instance Methods

Instance query-methods

C A C
A C H
C H

do not have side effects


provide a value of the object
can be interpreted as additional property of the object
In Cach use computed properties for convinient access
by SQL and object code

Instance update-methods

change the status of the object


test, whether an operation is allowed
In Cach SQL access not possible, use stored
procedures instead, with object-id as argument.
14

Computed Properties

C A C
A C H
C H

Cach supports two types of computed


properties/columns.

Always-computed.

Triggered-computed.

Property value computed whenever code references property.


Triggered-computed property/column is stored.
Computation triggered when new object is created/inserted,
or existing object is changed/updated
(properties listed in SqlComputeOnChange attribute).
Not triggered when object is opened, nor when row is selected.

Both types compute property/column value based on


another property/column (or other properties/columns).
14

SqlComputeCode Examples

C A C
A C H
C H

Age calculated based on DOB and $horolog:


set {Age}=$select(({DOB}'=""):((+$h-{DOB})\365.25),1:"" )

$select is a line based if- or case-statement


This code means
if {DOB} '= ""
{set {Age} = ($piece($horolog,",",1)-{DOB})\365.25}
else
{set {Age}=""}

15

SqlComputeCode Attribute

Specify computation using SqlComputeCode


attribute.

ObjectScript containing {ColumnName} reference(s).

C A C
A C H
C H

SQL analog for ..PropertyName syntax.


Unlike regular ObjectScript, no extra spaces allowed.

{ColumnName} is:

Propertys SqlFieldName attribute, if present.


Otherwise, propertys name.

15

How To:
Create a Computed Property

Create new property.


Set SqlComputed attribute = True.
Set Calculated attribute:

For always-computed, set = True.


For triggered-computed, set = False.

For triggered-computed, optionally specify


SqlComputeOnChange attribute:

C A C
A C H
C H

List of properties/columns that trigger computation.

Specify SqlComputeCode.

15

4.9 Integrity

The object oriented model has inherent integrity


constraints.

NOT-NULL-Constraint

Foreign key constraints are not necessary, due to


component and subclass relation
In Cach use the Required attribute for a property

UNIQUE-Constraint:

A combination of attributes must be unique for each


object.
In Cach use an index with the Unique attribute.
An Index is also used for access optimization.
15

Integrity (cont.)

CHECK-Constraint

DEFAULT-Constraint

In Cach use parameters like PATTERN, VALUELIST,


MINVAL, or MAXVAL
Example Phone: PATTERN = "3n1""-""3n1""-""4n"
In Cach use InitialExpression attribute of a property

Use set- and get-methods to access private


properties instead of public properties

You can code difficult constraint-checks in these


methods.
15

Callback Methods and Triggers

C A C
A C H
C H

Use Callback methods or triggers for sophisticated


constraint checking or consistency operations.
Callback methods are used on object side.
Triggers are used on SQL side.
!
Triggers do not check object operations!
Callback methods do not check SQL operations!
To unify the functionality for both OOP and SQL,
create class method that callback method and
trigger both call.
15

Callback Methods and Triggers


do ##class(X).%DeleteId(22)

C A C
A C H
C H

delete from X where %id = 22

Cach

SQL

class X
ClassMethod %DeleteId()
ClassMethod %OnDelete()
Trigger XBeforeDelete
do ##class(Y).%DeleteId(5)

delete from Y where %id = 5


X: 22, abc,
15

OOP Callback Methods

Events during lifetime of an object can call back


to methods you supply.
Each callback method can check object and affect
outcome of its event.
Naming convention: %OnEventName().
Object classes inherit callback method signatures.

C A C
A C H
C H

Override with your code.

To prevent operation (e.g. prevent saving an


object) return an error in the appropriate callback
method (e.g. in %OnValidateObject()):
quit $$$ERROR($$$GeneralError, "My error message")

15

Saving Object

C A C
A C H
C H

%Save() calls:

Method %OnAddToSaveSet(depth,insert).

The save set is the set of objects to be saved.


Argument: insert = 1 for a new object.
Return error status to prevent save of object.
Use this pre-validation callback for creating new objects,
modifying properties of existing objects, or adding objects to the
save set.

Method %OnValidateObject().

Use this pre-validation callback for custom object validation.


Return error status to cause object to fail validation.

15

Saving Object (cont.)

C A C
A C H
C H

%Save() calls:

Method %OnBeforeSave(insert).

Method %OnAfterSave(insert).

Use this post-validation callback for time-sensitive object


changes, such as setting Creation/Edited timestamp properties.
Argument: insert = 1 for a new object.
Return error status to prevent save of object.
Argument: insert = 1 for a new object.
Return error status to rollback save of object.

Method %OnRollBack().

Called when rollback occurs.


Return error status to prevent rollback.
15

Deleting Object from Disk

C A C
A C H
C H

%DeleteId() calls:

ClassMethod %OnDelete().

Argument: OID (not ID) of object to be deleted. Use $$


$oidPrimary macro to get ID from OID.
Return error status to prevent deletion.

16

C A C
A C H
C H

Other Callback Methods


Method

calls Callback Method

Comment

%New()

%OnNew()

Good place for


constructor code

%OpenId()

%OnDetermineClass()
%OnOpen()

Class method
Instance method

%ConstructClone()

%OnConstructClone
(object, deep)

object is OREF of
cloned object
deep is deep argument
of %ConstructClone()

set oref = "" %OnClose()


kill oref

Removing Object from


Memory

16

Practice: Write Callback Method

A branch must not close before it opens.


Discuss different possibilities to enforce
that constraint.
Write a callback method that enforces the
constraint.

16

Practice Solution:
Write Callback Method

A branch must not close before it opens.


Discuss different possibilities to enforce that
constraint.

Set MINVAL parameter for Closes greater than


MAXVAL parameter for Opens
Instead of Closes property Branch gets OpenTime
property with MINVAL > 0; implement Closes as
computed property Closes = Opens + OpenTime
Callback method %OnValidateObject()
and Trigger BranchCheckOpensCloses
16

Practice Solution:
Write Callback Method

C A C
A C H
C H

A branch must not close before it opens.


Write a callback method that enforces the constraint.

Method %OnValidateObject() As %Status[Private]


{
if (..Closes < ..Opens) {
quit $$$ERROR($$$GeneralError,
"Branch closes before it opens")
}
else {Quit $$$OK}
}
16

SQL Triggers

Events during lifetime of a row can trigger


methods you supply:

Events: Insert, Update, Delete by SQL

Each trigger can check current row and affect


outcome of its event.

C A C
A C H
C H

Can also issue additional SQL statements (which may


trigger additional methods).

Trigger code called after validation and constraint


checking.

16

SQL Triggers (cont.)

C A C
A C H
C H

Trigger events: Insert, Update, Delete.


Trigger timings: Before, After.
For multiple combinations of the same event and
timing, specify an Order attribute. For example:
Trigger T1 [Event = INSERT, Time = AFTER, Order =
1]
{ code here }
Trigger T2 [Event = INSERT, Time = AFTER, Order =
2]
{ code here }
Trigger T3 [Event = UPDATE, Time = BEFORE]
{ code here }
16

Row-Based Triggers

C A C
A C H
C H

Cach triggers are row-based rather than


statement-based.
For example, an update of 20 rows will trigger an
after update trigger for each row.
Some other relational products triggers would
trigger after update trigger once after updating all
rows.

16

Writing a Trigger

Trigger code can use embedded SQL and


{ColumnName} references to access value of any
column in current row.

C A C
A C H
C H

Triggers cant change value of columns in current row.

For UPDATE triggers, code can use:

{column*o} to access old value.


{column*n} to access new value.
{column*c} true if data changed.

16

Preventing Event

C A C
A C H
C H

To prevent event from occurring:


set %ok = 0, %msg="ErrorMessageText"

Used in before triggers, event changes never


happen.
Used in after triggers, causes rollback of changes.

16

Practice: Write Trigger

A branch must not close before it opens.


Write a trigger that enforces the
constraint.

17

PracticeSolution:
Write Trigger

C A C
A C H
C H

A branch must not close before it opens.


Write a trigger that enforces the constraint.

create trigger FCE.BranchCheckOpenTime


before insert on FCE.Branch
language OBJECTSCRIPT
{if ({Closes*N} < {Opens*N})
{
set %ok = 0
set %msg = "Branch closes before it opens"
}
}
17

Modern Database Techniques


Part 1: Object Oriented Databases
5. Application Development on
Client Side

5. Client Application Development


Self study project for students:
Develop a client application for the FCE example,
simulating an ATM.
Java application or web application.
Use Cach language binding techniques.
Tutorial with detailed instructions available.
Starter files for GUI available.
Solution available.

17

Vous aimerez peut-être aussi