Upload
cora-reed
View
245
Download
2
Tags:
Embed Size (px)
Citation preview
Modern Database TechniquesPart 1: Object Oriented Databases
4. Concepts of Object Oriented Databases
2
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
3
Requirements for OODBS
object-oriented perspective Complex objects Object identity Encapsulation Types and classes Class hierarchies Overloading of methods
optional: Multiple inheritance
Database perspective Persistance Disk-storage organisation Concurrent transactions Recovery mechanisms Query languages Database operations
optional: Distributed databases Version administration
4
4.1 Type constructors, complex objects
To be able to store many objects, a set constructor is necessary
Type of a relational tableSET 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
5
Overview Type Constructors
Tuple constructor TUPLE OF Combines several components of possibly different type Corresponds to aggregation
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 one element can have copies in the bag
List constructor LIST OF: like bag, but Sequence is of interest
6
Overview Type Constructors (cont.)
Array constructor ARRAY OF: like list, but may contain gaps index of type long integer
Dictionary constructor DICTIONARY OF (key, value) unordered sequence of
(key, value)-pairs lookup operation
returns value to a given key
Type constructors are used recursivly
0 1 2 3 …
Atlanta Paris London
Key Value
A excellent
B very good
C good
D satisfactory
E sufficient
F fail
7
Example: Type Construction for PersonsGraphical Representation
List
Tuple
Set
string
SetTuple
Tuple
date
stringstringstringstring
FirstName
SecondName
LastName
Title Salutation
DOB
Tuple
string stringstringstringstring
Street City State ZIP Typestringstring
PhoneNr
Type
Name
Persons
Person
Addresses
Address
PhoneNumbers
PhoneNumber
8
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)
9
ODMG Standard
ODL (object definition language) for ODMG-types extension of IDL (interface definition language) similar to C++ but language independent
All classes inherit from interface Object that provides constructor function (interface ObjectFactory) locking information and operation identity comparison function same_as(object) copy function delete function
Different constructors for collection types
10
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
11
Example: Persons in ODMG-Model
Class Person (extent Persons){attribute NameCl Name; attribute date DOB; attribute set <Address> Addresses; attribute list <PhoneNr> PhoneNrs;}Class NameCl{attribute string FirstName; attribute string SecondName; attribute string LastName; attribute string Title; attribute string Salutation;}
no own set of objects
set of objects
12
Example: Persons in ODMG-Model
Class Address{attribute string Country; attribute string City; attribute string Street; attribute string ZIP; attribute string State; attribute string Type;}Class PhoneNr{attribute string PhoneNr; attribute string Type;}
13
Type Construction with UML
Tuple ConstructorSet Constructor
List or Array Constructorcomplex properties
No dictionary constructor
14
Type Constructors in Caché
Tuple: Properties of a class Set:
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
C H ÉA C HC A C
15
Type Constructors in Caché
Array: not directly supported, use dictionary with integer key values
Dictionary: array Of Array in Caché is Dictionary in ODMG-Model !
C H ÉA C HC A C
16
Example: Persons in Caché
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
C H ÉA C HC A C
17
Example: Persons in Caché
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;}
C H ÉA C HC A C
18
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?
19
Type Construction for Saving AccountsGraphical Representation
List
Tuple
Set
Arr.datestring
InterestRate
AccountNumber
Year
Begin
Tuple
floatdate
Date Amount
Index:
Saving Accounts
Saving Account
Interest
Transactions
Transaction
stringType
date
End
int
float
string
Sender
string
Purpose
Value:
float
CurrentAmount
redundant information
20
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
21
Operations on Complex Types (cont.)
Set constructor Set comparisons: =, Set operations: intersection, union, difference
Bag constructor 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
22
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)
23
Operations on Complex Types in Caché
Persistent classes (tuple and set constructor) Access to components by dot-syntaxp1.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()-methodp1.%Save()
Delete an element: class methods %Delete(oid) and %DeleteID(id)
Iterator to access all objects of a class: query Extent()
C H ÉA C HC A C
24
Methods for List- and Array- (Dictionary-) Collections
Method Purpose Success Failure
List: Insert(value)
InsertAt(value, index)
Array: SetAt(value,key)
Add value to collection
1 error status
List: InsertList(list) Appends list 1 error status
Find(element) Tests whether element is in list
index or key
""
GetAt(key) Get value at key value ""
C H ÉA C HC A C
25
Methods for List- and Array- (Dictionary-) Collections (cont.)
Method Purpose Success Failure
RemoveAt(key) Remove object key
value at key
""
Count() Count items integer
Clear() Empty collection 1 error status
C H ÉA C HC A C
26
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.
27
Concepts for Classes: Type-based
class Line
Point begin;Point end;int width;
Line a2
(3;0);(5;17);
2;
Line yxa
(3;15);(1;1);
6;
type of
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++
Line x
(3;15);(5;17);
6;
28
Concepts for Classes: Set-based
Line x
(3;15);(5;17);
6; Line a2
Line gt
"p1";"p2";
"thin";
A class is a container Types of the elements are not fixed
4 1
5 2
6 3
x k
29
Set-type-based
class Line
Point begin;Point end;int width;
Line x
(3;15);(5;17);
6;
Line a2
(3;0);(5;17);
2;
Line yxa
(3;15);(1;1);
6;
class defines a complex
type
AND class is container for objects (extent)
This is the solution in OODBMSs
30
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
31
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
32
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
33
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
34
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
35
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
37
Different Possibilities for Relationships:a) Encapsulated component class
Complex objects with encapsulated objects of component class
Suitable for für 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
38
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
39
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).
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
C H ÉA C HC A C
40
Relationships in Caché (cont.)
Relationship specified in both class definitions. Relationship statement:
specialized Property statement. One, many, parent, and children define cardinality of
each side of relationship.
C H ÉA C HC A C
41
Example: Branch and ATM Class Model
FCE.ATMBranchCurrencyBalances1
0..*PhoneOpensClosesATMs
FCE.Branch
StreetCityStateZip
FCE.RealEstate0..1
1
1
0..1
Practice: Discuss the possibilities to implement the relation "Branch has ATMs"
C H ÉA C HC A C
42
Cardinality of Relationships in Caché
Cardinality: number of elements on each side of a reference.
Describe cardinality in terms of classes. “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.”
C H ÉA C HC A C
43
OOP Relationship Advantages
Relationship is a combination of a reference and a list collection. 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.
C H ÉA C HC A C
44
SQL Relationship Advantages
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.
C H ÉA C HC A C
45
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:
Deletion of an object of class A deletes all related objects of class B.
Same is true for rows in tables.
C H ÉA C HC A C
46
Demonstration: Create a Relationship
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.
C H ÉA C HC A C
47
Caché: Simulate One-to-One Relationship
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 doesn’t prevent deletion of object on “many” side.
C H ÉA C HC A C
48
Using Relationships
Link objects in two equivalent ways: 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
C H ÉA C HC A C
49
Using Relationships (cont.)
From one/parent side, many/children side is a collection. To link, either: Insert many/children object into one/parent object’s
collection:do branch.ATMs.Insert(ATMOne)
Insert many object ID directly into one object’s collection, without opening object (only for one-to-many):do branch.ATMs.InsertObjectId(atmid)
Insert new many/children object into one/parent object’s collection:do branch.ATMs.Insert(##class(FCE.ATM).%New())
C H ÉA C HC A C
50
Using Relationships (cont.)
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)
C H ÉA C HC A C
51
Storing Relationships
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.
C H ÉA C HC A C
52
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: -> operator in SELECT clause creates LEFT OUTER
JOIN. -> operator in WHERE clause creates INNER JOIN.
Transmits efficiency of OO-model to SQL
C H ÉA C HC A C
53
Implicit Joins (cont.)
May be chained.select Branch->Address->Street
Options when querying tables of a parent-to-children relationship: childtable.parentforeignkey->columninparenttable parenttable.childtable->columninchildtable
Works even though childtable is not a column in parenttable. Specify childtable without schema.
C H ÉA C HC A C
54
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 H ÉA C HC A C
55
Different Possibilities for Relationships: c) Connection Class
Employee Customer
subject area
0..*0..*advises
advisers
relation with attribute
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
56
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
Employee Customeradvises
advisers0..* 0..*Customer
contacts1 employee
customer
subject area
attribute
connection class
57
Summary: Different Possibilities to Implement Relationships in Caché
Component class %Serializable Use for unidirectional, private, dependent, encapsulated
components Component class %Persistent
Use for unidirectional, private, dependent, standalone components Relationship one-to-many
Use for bidirectional, private, independent, standalone components Relationship parent-to-children
Use for bidirectional, private, dependent, standalone components Connection class
Use for bidirectional, shared, independent, standalone components Relations with own attributes
C H ÉA C HC A C
58
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.
59
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
60
Types of Object Identity
Physical addresses, direct references, pointers Pointers point to component-objects Pointers point to begin of a list for set attributes
User defined names of a name domain e. g. license numbers of cars
Automatic keys = surrogate keys = identifier attributes (implementation obvious)
Abstract objects (implementation hidden to user)
61
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
62
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?
63
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!
64
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.
65
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
…))))
66
Saving-Accounts with Identifier-Attributes
Account_Nr
Type Begin End Account_Holder
… Transactions
172963 variable
12. JUN 2002
54355 1; 456 $; 1.7.02;…
2; -63 $; 5.7.02;…
3; …
134584 incr. interest
1. AUG 2005
31. JUL 2009
37704 1; 456 $; 1.8.05;…
2; 11 $; 31.12.05;
3; …
67
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 Operations on objects
Create new object Delete object Test on identity You never can print or see
an object itself or its Id
Abstract objects can be implemented (more or less well) by
physical addresses Names Identifier-attributes
68
Hugo Ross1 May 89
Graphical Representation using State-Boxes
5 Garden AveSan Francisco, CA
88250
State of object 19
19
2
object 19
State of object 2
Representation is difficult, since objects cannot be printed.
69
Abstract Objects
Advantages independent of the implementation theoretically sound foreign key constraints automatically guaranteed
Disadvantage 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
70
Saving-Accounts with Abstract Objects and Disjoint Domains
1 is not the name of an account holder, not the key of an account holder, but the whole object of type customer.
Account
Acc.Nr Type Beg. End Acc.Holder
… Transactions
1172963 varia
ble12. JUN 2002
1 τ1; τ2 ; τ3 ; …
2 134584 incr. interest
1. AUG 2005
31. JUL 2009
1τ4 ; τ5 ; τ6 ; …
71
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
72
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
73
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?
76
Object Identity in Caché
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
Every class gets %New()-method to create objects in memory and %Save()-method to store them permanently in DB
Caché guarantees correspondence of orefs and object IDs
C H ÉA C HC A C
77
Object Identity in Caché (cont.)
An object Id behaves like an abstract object, because it … 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
C H ÉA C HC A C
78
Object Identity in Caché (cont.)
IDs are class specific; ObjectId = Id + ClassName Caché does not provide functions for
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
C H ÉA C HC A C
79
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
80
Inheritance (cont.)
Class (set) inheritanceLet 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
81
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
82
Class Tree and Class Graph
Specialize subclasses class tree
animals
vertebrates
mammals birds
invertebrates
83
Addresses
Class Graph
A subclass inherits from more than one superclass (multiple inheritance) class graph
Not allowed in all object oriented systems
Supported by Caché
Person
Name: StringDOB: DatePhone: StringEmail: String
Employee
Salary: FloatESince: DateQualification: String
Customer
Type: StringCSince: DateRating: String
EmpCust
InterestBonus: Float
84
Inheritance in ER-Diagrams
Example: ER-Diagram of a personal address-book
Person
FriendColleague
o
Name PhoneAddress
RoomNr WorkPhone HobbiesDOB
85
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
86
Inheritance in Caché
Single or multiple inheritance Overriding of properties or methods possible
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 SuperclassClass Subclass Extends (SC1, SC2, …)
C H ÉA C HC A C
87
Multiple Inheritance in Caché
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).
C H ÉA C HC A C
88
Multiple Inheritance in Caché (cont.)
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.
C H ÉA C HC A C
89
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. New Class Wizard also allows creation of an abstract class.
Application code instantiates objects from concrete (non-abstract) subclasses.
Suitable for Generalization, if the superclass only is created to
simplify programming disjoint partition of a superclass in subclasses
C H ÉA C HC A C
90
Discussion of Abstract ClassesExample: Person Class
Is FCE.Person abstract? If yes, application code can’t 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.
91
Abstract Methods
Methods of an abstract superclass may optionally contain code to be inherited.
Setting a superclass method’s Abstract attribute to True shows that method doesn’t contain code. Subclasses should override method and provide code
particular to the subclass. Application code can’t call an abstract method.
Similar to Private.
C H ÉA C HC A C
92
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
93
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
94
Generic Query Operations
Operation Object oriented concept Projection Supertype Selection Subclass (Subset) Join Subtype of two types Union Superclass (Superset) Intersection Subclass of two classes Difference Subclass Grouping Degrouping Object navigation
95
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.
96
Example for Grouping: Situation before Grouping
ATM Branch Brand SerialNr Address CurrencyBalances
15 3 UBX 123-5 102Euro 3075USD 4788…
16 4 UBX 123-7 370Pound 2350USD 5340…
17 3 Abam 112675 20Rupees 3900USD 3340…
18 4 T.C.C. 45-44-6 876Euro 5150USD 2500…
97
Example for Grouping: Situation after Grouping by Brand
Brand ATM Branch SerialNr Address CurrencyBalances
UBX 15 3 123-5 102Euro 3075USD 4788…
16 4 123-7 370Pound 2350USD 5340…
Abam 17 3 112675 20Rupees 3900USD 3340…
T.C.C. 18 4 45-44-6 876Euro 5150USD 2500…
98
Object Navigation
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 brchMainfor i=1:1:brchMain.ATMs.Count() { write ! brchMain.ATMs.GetAt(i)
.Address.Street}
C H ÉA C HC A C
99
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) Relational operation: The elements of the result set are no objects, the result set is a pure relation.
b) Object generating operations: Generate new objects of a new abstract class.
c) Object conserving operations: The elements of the result sets are the existing objects.
100
Example: Projection of ATMs to Brand and SerialNr
Brand SerialNr
UBX 123-5
UBX 123-7
Abam 112675
T.C.C. 45-44-6
New-Obj Brand SerialNr
15 UBX 123-5
16 UBX 123-7
17 Abam 112675
18 T.C.C. 45-44-6
a)
c) ATM Brand SerialNr
15 UBX 123-5
16 UBX 123-7
17 Abam 112675
18 T.C.C. 45-44-6
b)
101
Degrouping cannot be object conserving
ATM Branch Brand SerialNr Address CurrencyBalances
15 3 UBX 123-5 102Euro 3075
15? 3 UBX 123-5 102USD 4788
16 4 UBX 123-7 370Pound 2350
16? 4 UBX 123-7 370USD 5340
17 3 Abam 112675 20Rupees 3900
17? 3 Abam 112675 20USD 3340
18 4 T.C.C. 45-44-6 876Euro 5150
18? 4 T.C.C. 45-44-6 876USD 2500
102
Queries in Caché
Caché uses SQL for queries with extensions for object oriented access: 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.
C H ÉA C HC A C
103
Defining Class Queries
Class queries are SELECT queries only, saved with class. 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.
C H ÉA C HC A C
104
Class Queries (cont.)
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.
C H ÉA C HC A C
105
Example: Class Query
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}
C H ÉA C HC A C
106
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
108
Using the Predefined Query Extent() Example: Branch
Create new result setSet rset = ##class(%ResultSet).%New
("FCE.Branch:Extent") Execute query: Do rset.Execute() Step through result setWhile (rset.Next()) { set br = ##class(FCE.Branch).%OpenId
(rset.Data("ID")) if br.Closes < PIECE($HOROLOG,",",2) {write br.Name _ " already closed",!}}
C H ÉA C HC A C
109
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.
110
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.
111
Overview of OQL
Syntax structure of an OQL select-querySELECT defines data to be retrieved and structure of data
FROMspecifies 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
112
OQL and PATH EXPRESSIONS Navigation Through Objects
Path expressions are used to navigate from one object to another.
Use dot (".") or arrow (“") Example:SELECT p.Name.LastName
FROM Persons p
WHERE pNameTitle = "Dr." Equivalent: FROM p IN Persons Persons is extent of persistent class Person Result is a multiset of literals; type Bag <string>
DISTINCT
set Set
113
OQL:Traversing Attributes and Relationships
OQL does not allow path expressions to traverse over multivalued attributes and relationships.
Example: not allowedSELECT b.Name,b.ATMs.Address.StreetFROM b IN BranchWHERE b.ATMs.Address.ZIP = '022456'
Use instead variable a for ATMs
a
a, a IN b.ATMs
114
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] bLIST (a,b,c,d)[1:3] LIST (b,c,d)FIRST(LIST(a,b,c,d)) aLAST(LIST(a,b,c,d)) d
Convert a list to a setLISTTOSET(LIST(1,2,3,2)) {1,2,3}
115
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
116
OQL: Embedded Queries
Example: SELECT a.Address.StreetFROM a IN (SELECT a
FROM Branch b, a IN b.ATMsWHERE b.Opens < '08:00:00'
WHERE a.Brand = 'T.C.C' Subquery also possible in SELECT- and WHERE-
part
117
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 ATMGROUP BY Manufacturer: a.Brand
Result type: Struct <string, Set <string>>
118
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>
119
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'
120
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".
121
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
122
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 EmployeesWHERE NrSubs > 0
123
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.CurrencyOrdersWHERE c.Requestor = 'John Hog' AND
a.Branch = 'London Westend'
124
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
125
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
C H ÉA C HC A C
126
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.
127
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.
129
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.
ObjectScript can call Basic. Basic can call ObjectScript.
Both languages compile to same OBJ code.
C H ÉA C HC A C
130
Inherited Methods
Classes that extend other classes inherit their methods.
For example, new persistent classes inherit methods of %Persistent class.
C H ÉA C HC A C
131
Method Signature C H ÉA C HC A C
Method MyMethod (Arg1 As %String = 'abc', Arg2 As %Numeric)As %String
{ set x = …}
method name
arguments
argument name
argument type
default value
return type:• result of calculation or• object or• status
body
132
Method Arguments
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 }
}
C H ÉA C HC A C
133
ObjectScript Arguments
Pass by value. 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.
C H ÉA C HC A C
134
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. Period before argument specifies pass by reference.
For example: By value: do oref.Method(a,b) By reference: do oref.Method(.a,.b)
C H ÉA C HC A C
135
Objects as Arguments
Object arguments may be OREFs. If method changes properties of object only, object
argument may be passed by value. 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.
C H ÉA C HC A C
136
Method Overloading
Caché doesn’t provide method overloading in a way similar to other languages such as Java. Can’t 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.
C H ÉA C HC A C
137
Private Methods
Methods are public by default. 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.
C H ÉA C HC A C
138
Class and Instance Methods
ClassMethod attribute controls whether method is class or instance method. 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.
C H ÉA C HC A C
139
Relative Dot Syntax
Inside an instance method, use relative dot syntax (..) to refer to another property or method of current instance. Read as “this object’s...” In Caché Basic, use Me.
Examples: ..Property ..Method()
Instance or class method. ..#ClassParameter
ObjectScript only.
C H ÉA C HC A C
140
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)
C H ÉA C HC A C
141
Overriding Accessor Methods
For special property processing when getting or setting properties, override accessor methods. Last panel of New Property wizard allows this.
Also used for Computed Properties. Override has no effect on SQL operations.
C H ÉA C HC A C
142
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)
143
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 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.
C H ÉA C HC A C
144
SQL Stored Procedures (cont.)
To make class method available as stored procedure: Must be class method. SqlProc=True.
C H ÉA C HC A C
145
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). Be careful with return value and argument types.
Method can also return result set (refer to Query Extent() for an example).
C H ÉA C HC A C
146
%sqlcontext Object
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.
C H ÉA C HC A C
147
Calling a Stored Procedure
Returning result set:call Schema.Table_QueryOrMethodName(arguments)call Schema.Table_QueryOrMethodName arguments
Using return value as part of query. For example:select columnsfrom tableswhere column = Schema.Table_QueryOrMethodName(arguments)
Using ? as placeholder for return value and input/output arguments:? = Schema.Table_QueryOrMethodName(?, ?)
C H ÉA C HC A C
148
Instance Methods
Instance query-methods 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.
C H ÉA C HC A C
149
Computed Properties
Caché supports two types of computed properties/columns. Always-computed.
Property value computed whenever code references property. Triggered-computed.
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).
C H ÉA C HC A C
150
SqlComputeCode Examples
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}=""}
C H ÉA C HC A C
151
SqlComputeCode Attribute
Specify computation using SqlComputeCode attribute. ObjectScript containing {ColumnName} reference(s).
SQL analog for ..PropertyName syntax. Unlike regular ObjectScript, no extra spaces allowed.
{ColumnName} is: Property’s SqlFieldName attribute, if present. Otherwise, property’s name.
C H ÉA C HC A C
152
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: List of properties/columns that trigger computation.
Specify SqlComputeCode.
C H ÉA C HC A C
153
4.9 Integrity
The object oriented model has inherent integrity constraints. Foreign key constraints are not necessary, due to
component and subclass relation NOT-NULL-Constraint
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.
154
Integrity (cont.)
CHECK-Constraint In Caché use parameters like PATTERN, VALUELIST,
MINVAL, or MAXVAL Example Phone: PATTERN = "3n1""-""3n1""-""4n"
DEFAULT-Constraint 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.
155
Callback Methods and Triggers
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.
!
C H ÉA C HC A C
156
Callback Methods and Triggers
do ##class(X).%DeleteId(22) delete from X where %id = 22
Caché
class X
ClassMethod %DeleteId()
ClassMethod %OnDelete()
Trigger XBeforeDelete
SQL
X: 22, abc,
do ##class(Y).%DeleteId(5) delete from Y where %id = 5
C H ÉA C HC A C
157
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.
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")
C H ÉA C HC A C
158
Saving Object
%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.
C H ÉA C HC A C
159
Saving Object (cont.)
%Save() calls: Method %OnBeforeSave(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.
Method %OnAfterSave(insert). 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.
C H ÉA C HC A C
160
Deleting Object from Disk
%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.
C H ÉA C HC A C
161
Other Callback Methods
Method calls Callback Method Comment
%New() %OnNew() Good place for constructor code
%OpenId() %OnDetermineClass()
%OnOpen()
Class methodInstance method
%ConstructClone() %OnConstructClone(object, deep)
object is OREF of cloned object
deep is deep argument of %ConstructClone()
set oref = "" kill oref
%OnClose() Removing Object from Memory
C H ÉA C HC A C
162
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.
163
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
164
Practice Solution: Write Callback Method
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}}
C H ÉA C HC A C
165
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. Can also issue additional SQL statements (which may
trigger additional methods). Trigger code called after validation and constraint
checking.
C H ÉA C HC A C
166
SQL Triggers (cont.)
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 }
C H ÉA C HC A C
167
Row-Based Triggers
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.
C H ÉA C HC A C
168
Writing a Trigger
Trigger code can use embedded SQL and {ColumnName} references to access value of any column in current row. Triggers can’t 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.
C H ÉA C HC A C
169
Preventing Event
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.
C H ÉA C HC A C
170
Practice: Write Trigger
A branch must not close before it opens. Write a trigger that enforces the
constraint.
171
PracticeSolution: Write Trigger
A branch must not close before it opens. Write a trigger that enforces the constraint.create trigger FCE.BranchCheckOpenTimebefore insert on FCE.Branchlanguage OBJECTSCRIPT{if ({Closes*N} < {Opens*N}) { set %ok = 0 set %msg = "Branch closes before it opens" }}
C H ÉA C HC A C
Modern Database TechniquesPart 1: Object Oriented Databases
5. Application Development on Client Side
173
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.