0% found this document useful (0 votes)
61 views32 pages

Object Oriented and Object Relational Databases, Logical and Web Databases-1-32

The document provides an overview of the evolution of database systems, highlighting the transition from hierarchical and network models in the 1960s to relational models in the 1970s and 80s, and finally to object-oriented databases (ODBMS) in the 1990s. It discusses the advantages of ODBMS, such as encapsulation, complex data types, and the ability to handle relationships and inheritance, making them suitable for applications in fields like CAD, telecommunications, and healthcare. The document also outlines the database design process, emphasizing the importance of object-oriented principles in modern database management systems.

Uploaded by

meetsatyajee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views32 pages

Object Oriented and Object Relational Databases, Logical and Web Databases-1-32

The document provides an overview of the evolution of database systems, highlighting the transition from hierarchical and network models in the 1960s to relational models in the 1970s and 80s, and finally to object-oriented databases (ODBMS) in the 1990s. It discusses the advantages of ODBMS, such as encapsulation, complex data types, and the ability to handle relationships and inheritance, making them suitable for applications in fields like CAD, telecommunications, and healthcare. The document also outlines the database design process, emphasizing the importance of object-oriented principles in modern database management systems.

Uploaded by

meetsatyajee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Object Oriented Databases

History of Databases
HISTORY OF DATABASES
! Back to the Beginning
file
! store data after process created it has ceased to
systems
exist
(1950s)
hierarchical/ ! concurrency
! recovery
network
! fast access
(1960s) ! complex structures
! more reliability
relational ! less redundancy
(1970-80s) ! more flexibility
! multiple views
! better simulation
! more (and complex) data types
! more relationships (e.g. aggregation,
ODBMS specialisation)
! single language for database AND
(1990s) programming
! better versioning
! no 'reconstruction' of objects
! other OO advantages (reuse, inheritance etc.) 2
STONEBRAKER’S
Stonebraker’sAPPLICATION MATRIX
Application Matrix

No Query Query

Complex Data OODBMS ORDBMS

Simple Data File System RDBMS

Thesis: Most applications will move to


the upper right.
3
Introduction to Database Systems 2
MOTIVATION
• Relational model (70’s):
• Clean and simple.
• Great for administrative and transactional data.
• Not as good for other kinds of complex data (e.g.,
multimedia, networks, CAD).

• Object-Oriented models (80’s):


• Complicated, but some influential ideas from Object
Oriented
• Complex data types.

• Idea: Build DBMS based on OO model.


Programming languages have evolved from Procedural to
Object Oriented. So why not DBMSs ???
4
RELATIONAL MODEL

• Relations are the key concept, everything else is around


relations

• Primitive data types, e.g., strings, integer, date, etc.

• Great normalization, query optimization, and theory

• What is missing??
• Handling of complex objects
• Handling of complex data types
• Code is not coupled with data
• No inherence, encapsulation, etc.

5
! Back to the Beginning

Object Oriented Databases (ODBMS) store data together with the appropriate methods for
RELATIONAL MODEL OF A ‘CAT’
accessing it i.e. encapsulation.

Relational databases " hammer the world flat" by normalisation.

Relational database of a cat:

At query time, try to put


things together as you
want !!!!

Object-oriented database of a cat:

6
OBJECT ORIENTED MODEL OF A ‘CAT’
Applications
! Back to the Beginning
Object-oriented database of a cat:
Object Oriented Databases The first areas where ODBMS were widely used were:
! CASE : Computer aided software engineering

! CAD : Computer aided design

! CAM : Computer aided manufacture

Increasingly now used in:


! telecommunications

! healthcare

! finance

! multimedia

!(2 oftext/document/quality management


This enables:
http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm 14) [10/13/2002 11:48:18 AM]

! complex data types to be stored (e.g. CAD These are the 'next-generation applications" where traditional IT
applications)
example, it has been estimated that up to 90% of the data held in
large amount of data is not 'record oriented'.
7
TWO APPROACHES

• Object-Oriented Model (OODBMS)


• Pure OO concepts

• Object-Relational Model (ORDBMS)


• Extended relational model with OO concepts

8
DATABASE DESIGN PROCESS
Application Domain
or Universe of Discourse

using ER model or UML

Data Modelling

Conceptual Model

using Data Model of the


target DBMS

Logical Database Design

Logical Model
DBMS specific
resource-based
optimization

Physical Database Design

Physical Model 9
LOGICAL & PHYSICAL LAYERS

Relational Normalization & SQL


ER diagram RDBMS
database design Physical design table definitions
Mapping onto
Relations
(no operations)

UML class Mapping onto Object-Relational Extended-SQL


Normalization &
Relations and Object
Physical design ORDBMS
diagram types database design table definitions

Mapping directly
onto ODL classes

Object-Oriented
database schema Optimization OODBMS
in ODL

10
EXAMPLE OF UML CLASSES

Person Class Name

name: {firstName: string,


middleName: string, Attributes
lastName: string}
address: string
birthDate: date

age(): Integer
Operations
changeAddress(newAdd: string)

p:Person A Person object

name: {Norman, William, Preston}


address: Stockport
birthDate: 11-JUN-70

11
FIRST APPROACH: OBJECT-ORIENTED
MODEL
• Relations are not the central concept, classes and objects are
the main concept

• Object-Oriented DBMS(OODBMS) are DBMS based on an Object-


Oriented Data Model inspired by OO programming languages

• Main Features:
• Powerful type system
• Classes
• Object Identity
• Inheritance

• OODBMS are capable of storing complex objects, I.e., objects


that are composed of other objects, and/or multi-valued
attributes.
12
FEATURE 1: POWERFUL TYPE SYSTEM

• Primitive types
• Integer, string, date, Boolean, float, etc.

• Structure type
• Attribute can be a record with a schema
Struct {integer x, string y}
• Collection type
• Attribute can be a Set, Bag, List, Array of other types

• Reference type
• Attribute can be a Pointer to another object

13
FEATURE 2: CLASSES

• A ‘class’ is in replacement of ‘relation’

• Same concept as in OO programming languages


• All objects belonging to a same class share the same
properties and behavior

• An ‘object’ can be thought of as ‘tuple’ (but richer


content)

• Classes encapsulate data + methods + relationships


• Unlike relations that contain data only

• In OODBMSs objects are persistency (unlike OO


programming languages)

14
FEATURE 3: OBJECT IDENTITY

• OID is a unique identity of each object regardless of


its content
• Even if all attributes are the same, still objects have different
OIDs

• Easier for references

• An object is made of two things:


• State: attributes (name, address, birthDate of a person)
• Behaviour: operations (age of a person is computed from
birthDate and current date)

15
FEATURE 4: INHERITANCE

• A class can be defined in terms of Person

another one. name: {firstName: string,


middleName: string,
lastName: string}
address: string
birthDate: date
• Person is super-class and Student age(): Integer

is sub-class.
changeAddress(newAdd: string)

• Student class inherits attributes


Student
and operations of Person.
regNum: string {PK}
major: string

register(C: Course): boolean

16
STANDARDS FOR OBJECT-ORIENTED
MODEL
• ODMG: Object Data Management Group (1991)
• provide a standard where previously there was none
• support portability between products
• standardize model, querying and programming issues

• Language of specifying the structure of object


database
• ODL: Object Definition Language
• OQL: Object Query Language

• ODL is somehow similar to DDL (Data Definition


Language) in SQL

17
Overview of ODL & OQL

18
Figure 4.2: An ODL declaration of the class Movie

The first attribute, on line (2), is named t i t l e . Its type is string-a


2. INTRODUCTION TO ODL 137

nd length4.2: declared
ODL: CLASSES & ATTRIBUTES
haracter string of unknown length. U'e expect the value of the t i t l e attribute
any Movie object to be the name of the movie. The next two attributes, year
xample In Fig. on 4.2
linesis (3)
an and
ODL(4), declaration
have integerof the
typeclass
andofrepresent
movies. the
It
not
ar ina which
complete the declaration;
movie was made we shall
and add more toin itminutes,
its length later. Line (1) declarw
respectively. On
ovie
ne (5)tois be a class.
another Following
attribute line (1)which
f ilmType, are the
tellsdeclarations
whether theofmovie
four attributes
was filmed
at all Movie objects will have.
color or black-and-white. Its type is an enumeration, and the name of the
numeration is Film. Values of enumeration attributes Keyword
are chosenattribute
from a list
le'terals,
1) color
c l a s s and
Movie blackAndWhite
{ in this example.
An2)object in a t t r i b u t e s t r i n g t i t l ehave
the class Movie as we ; defined it so far can be thought of
a record
3) or atuple
t t r i bwith
u t e four g e r year; one for each of the four attributes.
i n t ecomponents,
4) a t t r i b u t e i n t e g e r length;
5) a t t("Gone
r i b u t e With
enum tFilm Ccolor,blackAndMite)
h e Wind", 1939, 231, color) filmType;
a Movie object. 0

xample 4.3Figure 4.2: An 4.2,


: In Example
Two
ODLalldeclaration classes
the attributes with
of thehave their
classatomic attributes
Movie types. Here is
example with a nonatomic type. We can define the class S t a r by
The first attribute, on line (2), is named t i t l e . Its type is string-a
1) string
aracter t a r C length. U'e expect the value of the t i t l e attribute
c l a s sof Sunknown
any2)Movie object
a t t r i to
b ubet ethe
s t rname of the movie. The next two attributes, year
i n g name;
d length
3) declared
a t t r i b on S t r (3)
u t elines u c tand
Addr (4), have integer type and represent the
ar in which the movie { s t r iwas
n g smade
t r e e and
t , sits
t r ilength
n g c i tin
y )minutes,
address; Attribute
respectively. On as a structure
e (5) is another attribute f ilmType, which tells whether the movie was filmed
color or black-and-white. Its type is an enumeration, and the name of the
umeration
ne is Film.
(2) specifies Values of name
an attribute enumeration
(of the attributes
star) that are is achosen
string.from a list
Line (3)
ecifies another
le'terals, color attribute address. This
and blackAndWhite in this attribute
example. has a type that is a record
An object
ucture. Thein name
the class Movie
of this as we have
structure defined
is Addr, andit the
so far canconsists
type be thought of
of two 19
a record or tuple with four components, one for each of the four attributes.
D
; 2.
o r , b l a c k ~ n d W h i t efilmType; ~
Note, t
tars ODL:
r : : s t a r r e d I n ; CHAPTER 4. OTHER DATA MODELS
RELATIONSHIPS 4.2. INTRODUCTION t o incl
TO
instanc 3.OD
dBy
n g1) cc il ats syMovie
) address; 1. If we have a value
many-manyo r
C class C the type of the rela
dio::owns; 4. b
starredIn
2) attribute s t r i n g t i t l e ; could
3) attribute integer year;
to be e
ng city) address;
ovie::stars;
4) a t t r i b u t e integer length;
5)
6)
attribute enum F i l m {color,black~ndWhite~
relationship Set<Star> s t a r s
filmType;
2. If the relationship is many
Keyword relationship
tionship in C is just D,wh
Note,
3. If the relationship is many
Exam
are reversed in t(2)
oabove.
inc
inverse Star::starredIn;
Keyword set
starredIn
7)

n g c 1;
relationship Studio ownedBy

i t y ) address;
inverse Studio::owns; and
instan
4. If the relationship St
is one-o
D, and in D it value
4.2 an
is just C.
starredIn Set: set of unsorted unique could
Since
E/R modele
vie::stars;
8) c l a s s Star C Note, that as in the
s;
vie::stars;
9) a t t r i b u t e s t r i n g name;
objects to be
to include the case where for so
owns10) a t t r i b u t e Struct Addr instance, a many-one many
relationshr
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
ovie::ownedBy;
11) relationship Set<Movie> starredIn Bag: set of unsorted objects
could be associated E xany
with Stu
asem
to be empty for someand D objectsS
with possible duplication and (1
inverse Movie::stars;
3;
Example 4.6 : In Fig. 4.24.3 wean
ha
and Studio. The first
structu
two of th
12) c l a s s Studio i
; 13) List: set of sorted list Since
attribute s t r i n g name; 4.2 and 4.3. ?Ve also There
discussed
many
Since each of their types uses
sowns
14)
and
15)
their
r
attribute s t r i n g address;
e l a t i o
relationships
n s h i p Set<Movie> owns list typesStar
many relationship between
Array: set of sorted Sti
vie::ownedBy; Studio objects have attribute
1;
inverse Movie::ownedBy;
referenced byand index(14). Notice that and Intyp(l
the
structure as was used struct
20for the
type of
There is nothing wrong with us
ODL: RELATIONSHIPS & INVERSE
RELATIONSHIPS
CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION TO OD

1. If we have a many-many r
1) c l a s s Movie C class C the type of the rela
2) attribute s t r i n g t i t l e ;
3) attribute integer year;
4) a t t r i b u t e integer length; 2. If the relationship is many
5) attribute enum F i l m {color,black~ndWhite~ filmType; tionship in C is just D,wh
6) relationship Set<Star> s t a r s
3. If the relationship is many
inverse Star::starredIn;
7) relationship Studio ownedBy
Keyword inverse
are reversed in (2) above.
inverse Studio::owns; 4. If the relationship is one-o
1; D, and in D it is just C.
8) c l a s s Star C Note, that as in the E/R model
9) a t t r i b u t e s t r i n g name; to include the case where for so
10) a t t r i b u t e Struct Addr instance, a many-one relationsh
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
11) relationship Set<Movie> starredIn could be associated with any se
inverse Movie::stars; to be empty for some D objects
3;
Example 4.6 : In Fig. 4.3 we ha
and Studio. The first two of th
12) c l a s s Studio i Inverse of4.3. ?Ve also discussed
4.2 and
13) attribute s t r i n g name;
14) attribute s t r i n g address; each other
Since each of their types uses
15) r e l a t i o n s h i p Set<Movie> owns many relationship between Star
inverse Movie::ownedBy; Studio objects have attribute
1; and (14). Notice that the typ
structure as was used21for the
There is nothing wrong with us
ODL: MULTIPLICITY OF RELATIONSHIPS
CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION TO OD

1. If we have a many-many r
1) c l a s s Movie C class C the type of the rela
2) attribute s t r i n g t i t l e ;
3) attribute integer year; Based on the use of collection
4) a t t r i b u t e integer length; types (set, bag,
2. If theetc.)
relationship is many
5) attribute enum F i l m {color,black~ndWhite~ filmType; tionship in C is just D,wh
6) relationship Set<Star> s t a r s
3. If the relationship is many
inverse Star::starredIn;
are reversed in (2) above.
7) relationship Studio ownedBy
inverse Studio::owns; Many-to-Many relationship
4. If the relationship is one-o
1; D, and in D it is just C.
8) c l a s s Star C Note, that as in the E/R model
9) a t t r i b u t e s t r i n g name; to include the case where for so
10) a t t r i b u t e Struct Addr One-to-Many
instance,relationship
a many-one relationsh
( s t r i n g s t r e e t , s t r i n g c i t y ) address; value of the relationship in som
11) relationship Set<Movie> starredIn could be associated with any se
inverse Movie::stars; to be empty for some D objects
3; What about multiway
Example 4.6 : In Fig. 4.3 we ha
12) c l a s s Studio i relationships???
and Studio. The first two of th
13) attribute s t r i n g name; 4.2 and 4.3. ?Ve also discussed
14) attribute s t r i n g address; --Not supportedSince each of their types uses
many relationship between Star
15) r e l a t i o n s h i p Set<Movie> owns --Need to convertStudio
a multiway toattribute
objects have
inverse Movie::ownedBy;
multiple binary and
relationships
(14). Notice that the typ
1;
22for the
structure as was used
There is nothing wrong with us
is the equivalent in hours. Note that this method takes no parameters.
Movie object to which the method is applied is the "hidden" argument,
it is from this object that a possible implementation of 1engthInHours
ould obtain the length of the movie in minute^.^

ODL: METHODS
thod 1engthInHours may raise an exception called noLengthFound, Pre-
ly this exception would be raised if the length attribute of the object

ue that could not represent a valid length (e.g., a negative number).

1) c l a s s Movie {
2) attribute string t i t l e ;
3) a t t r i b u t e integer year;
4) a t t r i b u t e i n t e g e r length;
5) a t t r i b u t e enumeration(color,blackAndWhite) filmType;
6) r e l a t i o n s h i p Set<Star> stars Three methods declarations
inverse S t a r : : s t a r r e d I n ;
7) r e l a t i o n s h i p Studio ownedBy
inverse Studio::oms;
8) f l o a t lengthInHours() raises(noLengthF0und);
9) void starNames(out Set<String>);
LO) void otherMovies(in S t a r , out Set<Movie>) Parameters are either
raises(noSuchStar); IN, OUT, or INOUT

Figure 4.4: Adding method signatures to the Movie class

In line (9) we see another method signature, for a Definition


method called (implementation)
starNames. is
This method has no return value but has an output not partwhose
parameter of the
typeclass
is a
set of strings. We presume that the value of the output paramet,er is computed
by starNames to be the set of strings that are the values of the attribute name
for the stars of the movie to which the method is applied. However, as always 23
there is no guarantee that t,he method definition behaves in this particular way.
There
is that is
seta issimilar
objects
the belong capability
to one
essentially and
a triple ODL
in consisting
only to
onedeclare
that one
ofclass. Thus,
movie, aC
classto to and
be aasubclass
represent
star, movies
studio, ome possible ap
of usanother class D. We follow the name C in its declaration with the keyword
are the
thatextends salary
bothand that and
cartoons
the name
is paid to the star by the studio for acting in that movie.
D.murder mysteries, we need a fourth class for these
movies.
ODL: INHERITANCE . Disallow m
Example
The 4.10: Recall Example 2.10,
classSubclasses
CartoonMurderMystery mustwhereinheritweproperties
declared cartoons
from both to Car-
be a
3.2
toonsubclass of movies, with as
and MurderMystery, in ODL
thesuggested
additionalby
property
Fig. 4.7. of aThat
relationship from a cartoon
is, a ~artoonMurder-
:tLeta us
setrecall
of stars that are its "voices." Iinr ethe
canE/R
create a subclass Cartoon for
garded as t
the discussion of subclasses model from Section 2.1.11.
Mystery
hlovie object
There with
has
the ODLall the properties
declaration: of a Movie object, plus the relationship
in ODL to declare one class C to be a subclass
voices and
is a similar
the
capability
attribute weapon.
of another class D. We follow the name C in its declaration with the keyword
. Indicate wh
c l a s s Cartoon extends Movie i subclass. F
extends and the name D.
• Same Idea as in OO
r e l a t i o n s h i p Set<Star> Movieprogramming (C++ or Java)
voices; romance we
• Subclass inherits all attributes, relationships, and methods
Example 4.10: Recall Example 2.10, where we declared cartoons to be a ending than
subclass of movies, with the additional property of a relationship from a cartoon
ITe
:t ahave
set of
technically
• we
not Plus
indicated
stars adding
that
must doare
nameadditional
the its of the inverse offields
relationship voices, although
so. "voices." I r e can create a subclass Cartoon for
would spec
hlovie with the ODL declaration: Keyword extends from superc
A subclass inherits Cartoon
all the propertiesMurderMystery
of its superclass. Thus, each cartoon
objectc lhas
a s sattributes
Cartoon textends i t l e , year, length,
Movie i and f ilmType inherited from ~ o v i e
(recall Fig. a t i o nand
r e l4.3), s h iitp inherits
Set<Star> relationships
voices; s t a r s and ownedBy from Cartoon
Movie, movie is a movie
3. Give a new
in addition to its own relationship voices. with voices of characters ties in the s
Also in that esample. we defined a class of murder mysteries with additional
CartoonMurderMyster~ ance inheri
ITe have
attribute not indicated
weapon. the name of the inverse of relationship voices, although
technically we must do so. specify that
Ac lsubclass
a s s Figure
MurderMystery
inherits
4.7: all theextends
Diagram Movie
properties
showing of multiple
its superclass. Thus, each
inheritance Murder
cartoon movie is a movie verdict, w
object hasa t tattributes
r i b u t e sttirtilneg, year, length, and f ilmType inherited from ~ o v i e
weapon; Courtroom.
(recall Fig. 4.3), and it inherits relationships s t a r s and ownedBy from with the weapons used
Movie,
in ODL, wetomay
In addition its ownfollow the keyword
relationship extends by several classes, separated
voices.
is a suitable declaration of this subclass. Again, allby:
t,he properties of additional
movies are
Also in that esample. we
by colons.3 Thus, we may declare the fourth
inherited
defined a class ofclass
murder mysteries with 4.3.4 Exten
attribute by MurderMystery.
weapon.
class
c l a s sCartoonMurderMystery
MurderMystery extends Movie Inherits from two other When an ODL cla
extends
a t t r i b u t MurderMystery
e s t r i n g weapon;: Cartoon; classes the class definitio
given time. The
isWhen a class
a suitable C inherits
declaration fromsubclass.
of this several classes, there
Again, all is t,he potential
t,he properties for are
of movies con- and a relation in
24
fiietsinherited
amongby names. Two or more of the superclasses of C may have a
MurderMystery.
property
a(extent
t t r i b u t eMovies
s t r i n gkey ( t i t l e , year))
name;
...
a t t r i b u t e string t i t l e ;
...
Itcould have used
is possible ODL: INSTANCES & KEYS
thatkeys
severalin place
sets ofof attributes
key, even arethough
keys.only onethen
If so, key following
is declared.
the Similarly,
word key(s) we may
if name is a place
key forseveral keys separated
class Star, by commas.
then we could begin itsAsdeclaration:
usual, a
key that consists of more than one attribute must have parentheses around the
list of class Star so we can disambiguate a key of several attributes from
its attributes,
several Instance
• keys of one attribute
(extent of akey
Stars class
each.name)are all objects currently exist of that class
Example DDITIONAL In :ODL
• 4.14 anthat
AsODL. example is called
CONCEPTS extent
of a situation where(and is given toa have
it is appropriate name)
153
more•than Keys
a t t r i are
one b u t e not
key, s t r i nas
consider a important for referencing objects
class
g name;Employee, whose complete set of attributes
andtributes forming
relationships we
... keys.
shall If there
not describe here. than
is more one attribute
However, in atwo
suppose that key,ofthe
its
of •
attributes Because
must be each
surrounded object
by already
parentheses. The
attributes are empID, the employee ID, and ssNo, the Social Security number. has
key a unique
declaration OID
itself
ears, along with the extent declaration, inside parentheses that may follow
Then • weDefining
can declare each keys in ODL
of these attributes is optional
to be a key by itself with
name of the class itself in the first line of its declaration.
ODL
• class
mple 4.13 : allows
To declare defining
Employee that the set of multiple
two attributeskeys (Comma
t i t l e and year form separated)
yItfor
is class
possible
(extent that
Movie, weseveral
Employees sets
key of
could begin itsattributes
empID, ssNo)are keys. If so, then following
declaration:
the word
c l a s skey(s)
Movie. . .we may place several keys separated by commas. As usual, Keywords
a extent & key
key that consists
(extent ofMovies
more than key one t i attribute
(around
t l e , the must have parentheses around the
year))
Because there are no parentheses list of attributes, ODL interprets
list
the of its attributes,
above as saying that we can
so each of thedisambiguate
two attributesa keyis aofkey
several attributes
by itself. If we putfromThe key is the pair of (title, year)
several
parentheseskeysaround
a t t of.one
r i b u t attribute
e
. . the
s t r i n g each. ssNo) , then ODL would interpret the two
t
list (empID,
i t l e ;

attributes together
Example : As asan
forming
example one key.a situation
That is, the implication of writingto have
could have 4.14 used keys in place ofofkey, where
even though it isoneappropriate
only key is declared.
more than
classone
Similarly, key, isconsider
ifEmployee
name a key for a class
class Star,
Employee, whose
then we couldcomplete
begin itsset of attributes
declaration:
and relationships S t a r we
c l a s s(extent shall not key
Employees describe(empID,here.ssNo))
However, suppose that two of its
are .empID,
attributes(extent . . S t athe employee
r s key name)ID, and ssNo, the Social Security number. The key is the pair of (empID, SSN)
Then we can declare each of these attributes to be a key by itself with
a t t r i b u t e s t r i n g name;
...
class Employee Two keys empID and SSN
(extent Employees key empID, ssNo)
...
It is possible that several sets of attributes are keys. If so, then following
the word key(s) we may place several keys separated by commas. As usual, a 25
Because
key there are
that consists no parentheses
of more around the
than one attribute listhave
must parenthesesODL
of attributes, interprets
around the
WHAT’S NEXT

• First Approach: Object-Oriented Model


• Concepts from OO programming languages
• ODL: Object Definition Language
• What about querying OO databases???
• OQL: Object Oriented Query Language

26
OQL: OBJECT-ORIENTED QUERY
LANGUAGE
• OQL is a query language designed to operate on
databases described in ODL.

• Tries to bring some concepts from the relational model to


the ODBMs
• E.g., the SELECT statement, joins, aggregation, etc.

• Reference of class properties (attributes, relationships,


and methods) using:
• Dot notation (p.a), or
• Arrow notation (p->a)

• In OQL both notations are equivalent

27
If it makes sense, we can form expressions with several dots. For example,
if myMovie denotes a movie object, then myMovie. ownedBy denotes the Studio
object that owns the movie, and mynovie. ownedBy .name denotes the string
that is the name of that studio.
INTRODUCTION TO OQL OQL: EXAMPLE QUERIES
Select-From-Where I OQL
Expressions in 9.1.3
OQL permits us to write expressions using a select-from-where syntas similar
. to SQL's familiar query form. Here is an example asking for the year of the
N IN QUERY
c l a s s MovieLANGUAGES movieINTRODUCTION
9.1. Gone IVzth the Wind. T O Reference
OQL the extent (instance of class)
( e x t e n t Movies key ( t i t l e , y e a r ) )
C SELECT m. yearWHERE and a boolean-valued expression. This expression,
attribute string t i t l e ; 3. The keyword
ts a t t r i b u t e integer year; FR OM Movies
the expression m following the SELECT, may only use as operands const
a t t r i b u t e integer length; WHERE
and those i t l e = "Gone
m . t variables declaredWith in t h the
e Wind"FROM clause. The comparison opera
he dot. This
a t t r i b uconvention
t e enum Film is (color,blackAndWhite> filmType; are like SQL's, except that ! =, rather than <>, is used for "not equal
arrow both
r e l a tobtain
i o n s h i p Scompo-
et<Star> s t a r s XoticeSelect the year
that,logical
The escept for the of movie
operators are‘Gone
double-quotes Owith
AND, around R, and the
theNO wind’
string
T, likeconstant,
SQL's.this query
ow and dot operators i n v ehave
rse Star::starredIn;
r e l a t i o n s h i p S t u d i o ownedBy
could be SQL rather than OQL.
the same. 111 C, expression The querythe
In general, produces a bag of objects.
OQL select-from-where We compute
expression consists of: this bag by conside
i n v e r s e Studio::owns;
pects p to be a pointer to a
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ; all possible values of the variables in the FROM clause, in nested loops. If
N INthat
f of QUERY structure. LANGUAGES 9.1. INTRODUCTION
combination of values TO OQL
void starNames(out S e t < S t r i n g > ) ; 1. The keylvord SELECTfor these
follolved variables
by satisfies the condition of the WH
a list of expressions.
void otherMovies(in S t a r , o u t Set<Movie>) clause, then the object described by the SELECT clause is added to the bag
For each movie a m,
list sof isone
theorset of variable
stars in declarations.
-

raises(noSuchStar); 2. The
3.
is the The
resultkeyrvord
keyword
of the FRO WM H Efollowed
RE and
select-from-where abyboolean-valued
statement. more
expression. This expression,
ts I ; dthe expression
variable that
is declared movie
following (follow
by giving a relationship)
the SELECT, may only use as operands const
Example and those9.2 :variables
Here is adeclared more complex in the FR OQL query:The comparison opera
OM clause.
he dot. This convention is 430 CH..IPTER 9.(a)
are OBJECT-ORIENTATION
.A
liken expression
SQL's, whose
except value
that I,V! QUERY
has
=, a
rather LANGUAGES
collection
than <>, is
type, e.g.used
a setfor
or "not
bag. equal
th c l a s sdots.
several S t a r For example,
arrow both obtain compo-
( e x t e n t S t a r s key name)
SELECT s.name
The logical operators are AND, OR, and NOT, like SQL's.
. ownedBy
ow and< dot denotes
operators the Studio have (b)
FROM The optionalm,
Movies keyn-ord
m . s t aAS, r s and
s
edBy .name denotes
the same. a t1t1r1i bC, the
u t eexpression string W HER E m . t i t of
l ethe "Casablanca"
=avariable.
s t r i n g name; The (c) The
query name
produces bag of objects. We compute this bag by conside
pects p toa be t t r i baupointer
t e S t r u c t to Addr a Alternative Form of FROM Lists
all possible values of the variables in the FROM clause, in nested loops. If
f of that structure. { s t r i n g s t r e e t , s t r i n g c i t y ) a d d r e s s ; ThisSelect
query star
Typically. asks names
the for thefrom
expression names movie
of (a) is‘Casablanca’
ofvariables
the thestars of of
extent Casablanca.
some class, Notice
such as ofthe sequ
thethe
r e l a t i o n s h i p Set<Movie> s t a r r e d I n In addition combination
to the
of termsSQL-style
in
ofelements
the
values
FR O M offor
clause.FROthese
M clauses,
First wewhere
define
satisfies
the collection
m to be
the
an
condition
arbitrary object
WH
in
ons in OQL inverse Movie::stars; clause, extent
then Movies
the objectfor class
describedMovie in
by the
the example
SELECT above.
clause An
is extent
added is
to the
the bag
is follo~vedclass
by a name
Movie, forby a typical
saying element,
m is in OQLextent
the allo~vsof a completely
that class, which is Movies. T
is theanalog
result ofofathe select-from-where
relation in an SQL FRO Mstatement.
clause.
1;
ect-from-where syntas similar equivalent, for
moreeach
logical,
valueyet of less mSQL-is11
we let Another
form.
s be We a Scan
t notation
a give
r the However,
object typical
in the
it is possible to
set m.stars of star
ple asking for the year of the element name, usethe
then in keyword
a variable I N declaration
, and any collection-producing expression, such as
movie
Example m. That
another 9.2 :is,Here n-e
select-from-where is afinally
consider more the
in name
two
complex
expression.
of the
nested OQL collection.
loops
query: all pairs (m, s ) such that
c l a s s Studio For instance,
a movie and s a star of that movie. The evaluation can be sketched as:
th several(dots. e x t e n t SFor t u d i example,
o s key name) SELECT s.name
. ownedBy
C denotes the Studio FR
ROR
O
OMeach
M m i m,
I N Movies,
mMovies n Movies
m r DO
s . IsNt am.stars
s s
edBy .namea tdenotes t r i b u t e s t the r i n g string
name;
W HE R EFORm .each
t i t l e s= i n m.stars DO
"Casablanca"
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns
is an equivalent FROM clause for IFthe mquery
. t i t l in
e Example
= "Casablanca" 9.2. THEN
i n v e r s e Movie::ownedBy; This query asks for add
the s.name
names of t
theo t h e
stars output
of Casablanca.
bag Notice 28the sequ
he string constant, this query of terms in the FR O M clause. First we define m to be an arbitrary object in
ons in OQL
I ;
class The WHERE
Movie, byclause
saying restricts
m is in our the consideration
extent of thatto thosewhich
class, pairs isthat have mTe
Movies.
a star appeared in several Disney movies.
allow a variable representing a typical element of that collectio
SELECT DISTINCT s.name each member of the collection.
FROM Movies m , m.stars s Example 9.6 : Let us redo the query of Example 9.3, which ask
To make
WHERthe result
E m. a list, add
ownedBy. namean =
ORDER BY ofclause
"Disney" at the end of the query,
the movies made by Disney. First, the set of Disney movies co
again as in SQL. by the query, as was used in Example 9.4.

OQL: EXAMPLE QUERIES II


The strategy of this query is similar to that of Example 9.2. We again
INTRODUCTION TO OQL The followingall
consider pairs ofwill
examples a movie and
illustrate thea correct
star ofsyntax.
that movie
SELECT m in two nested loops as in
Example 9.2. But now; the condition on thatFROM pairMovies m is that "Disney" is the
(m, s)
name of the studio whose S t u d i o object is m. ownedBy.movies. =The
Example 9.3: Let us ask for the names of the WHERE
stars of m.ownedBy.name
Disney "Disney"
following query does the job, eliminating duplicateWenames inuse
can now thethis
situation
query as where
a subquery to define the set over w
The ORDER BY clause in OQL is quite similar to the same clause in SQL.
a star appeared in several Disney movies. d. representing the Disney movies; can range.
c l a s s Movie Keywords ORDER BY are followed by a list of expressions. The first of these
( e x t e n t Movies key ( t i t l e , y e a r ) ) expressions is evaluated for each object in the SELECT DISTINCT
result of thes.namequery, and objects
SELECT DISTINCT s.name FROM (SELECT m
C areFRordered by this
OM Movies m, m.stars s value. Ties, if any, are broken by the value of the second
FROM Movies m
attribute string t i t l e ; expression. then the third, and so on. By default, the order is ascending. but
a t t r i b u t e integer year; WHERE m. ownedBy. name = "Disney" WHERE m.ownedBy.name = "Disney") d,
a choice of ascending or descending order can be d. indicated
stars s
by the keyword ASC
a t t r i b u t e integer length; or DESC, respectively. following an attribute. as in SQL.
NTATION aI,V t t r QUERY
i b u t e enum LANGUAGES
Film (color,blackAndWhite> filmType;
9.1. IAiTRODUCTION TO OQL
The strategy of this query is similar to thatThis Exampleof9.2.
of expression We again 43 1
consider Select
all pairs distinct
of :a Let
movie star names in movies owned by
the query ‘Disney’
"Find the stars of Disney movi
relationship Set<Star> s t a r s Example 9.4 us and
finda thestarset
of that movie
of Disney
succinctinmovies,
two nested
than thatbut loops
let the
of Example as9.3.
in and be
result a listless so. Ho
perhaps
inverse Star::starredIn; Example
Inofthe 9.2. But
first
movies. three now;
ordered the
lines,
by wecondition
consider
length. Ifonthere
that pair
each are
Movie(m, s)
ties, isa new
object
illustrate let thatm.
the "Disney"
If
movies
form theofis
of building the
name
equal oflength
queries the be
available in OQL. In th
m of FROMr e lLists a t i o n s h i p S t u d i o ownedBy
i n v e r s e Studio::owns;
ordered
name
studioof the
thatalphabetically.
studio
oxnswhosethis movie
S t u The
d i is
o queryisis:
object
"Disney," m. the the
then
ownedBy. clause has two
FROM complete object subquery
nestedmloops. In the first, the variabl
becomes
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ; a member of the output bag. The fourth allline Disney movies, the result of the subquery in the FROM clause
specifies that the object,s m
The SELECT m
clause in OQL is quite similarloop,
to nested
the withinclause
same the first,
in the variable s ranges over all star
of FROM clauses, where the collection
void starNames(out S e t < S t r i n g > ) ; produced ORDER
FR O
by
M
BY
the select-from-where
Movies m
query are to
lnovie d. ordered
'
be Sotice thatfirst by SQL.
no WHERE the value
clause of in the outer qu
is needed
element, OQL allo~vs a completely
void otherMovies(in S t a r , o u t Set<Movie>) Keywords ORDER BY are followed
t h (i.e., m.ownedBy.name
m. l e n gWHERE the length of the movie)by a list of expressions. The first of
and then, if there are ties, by the value these
= "Disney"
-is11 form. We can giver the a i s e stypical
(noSuchStar); expressions
of m. t i O lisD evaluated
(i.e., for each object in the result of the query, and objects
tR eE R BY m.length, m . t i t l e The value produced by this query is
the title of the movie).
nd finally
I ; the name of the collection. are
thusordered
a listbyof this
Movie value. Ties, if any, are broken by the value of the second
objects.
expression. then the
order third, and
movies so on.by
owned By‘Disney’
default, thebased
order ison
ascending.
lengthbutand title
class Star a 9.1.5
choice of ascending or descending
Complex Output Types order can be indicated by the keyword ASC
, s I N m . s(teaxrt se n t S t a r s key name) or DESC, respectively. following an attribute. as in SQL.
<
uery in Example
The elements in the SELECT clause need not be simple variables. They can
a t t r i b9.2.
u t e s t r i n g name; Example 9.4 : Let us find
be any expression, the setexpressions
including of Disney movies,
built but let the
using result
type be a list
constructors. For
a t t r i b u t e S t r u c t Addr weReport
{string s t r e e t , s t r i n g c i t y ) address;
ofexample,
movies. ordered
canbyapplyset
length.theof structures
If Sthere
t r u care ties,constructor
t type let the movies
toofseveral
equal length be
expressions and
r e l a t i o n s h i p Set<Movie> s t a r r e d I n
ordered alphabetically. The query
get a select-from-where query that
is: produces a set or bag of structures.
RDER BY clause at the end iof n vthe
e r s equery,
Movie::stars;
1; Example m
SELECT 9.5: Suppose we want the set of pairs of stars living at the same
FROM \ire
address. can mget this set with the query:
Movies Join two classes
e correct syntax. WHERE m.ownedBy.name = "Disney"
c l a s s Studio SELECT
ORDER DISTINCT m
BY m.length, S t. rt iutcl et ( s t a r l : s l , s t a r 2 : s 2 )
s of the stars
( e xoft e nDisney
t S t u d imovies. The
o s key name) FROM S t a r s s l , S t a r s s 2
C names in the situation where
duplicate WHERE s l . a d d r e s s = s 2 . a d d r e s s AND s1.name < s2.name
a t t r i b u t e s t r i n g name;
.
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns Report
That is, pairs of
1%-econsider all stats who
pairs of have
stars, the s2.
s l and sameTheaddress
WHERE clause checks
i n v e r s e Movie::ownedBy; that they have the same address. It also checks that the name of the first star 29
I; p~ecedesthe name of the second in alphabetic order, so ~3-edon't produce pairs
y"
In addition to the SQL-style elements of FROM clauses, where the collection produced
example, we by the
can select-from-where
apply the S t r u c tque
typ
is follo~vedby a name for a typical element, OQL allo~vsa completely getl eanselect-from-where
m. g t h (i.e., the lengthquery
of thethat pro
movie
equivalent,
To make themore logical,
result a list,yet
add anSQL-is11
less ORDER BY form. Weatcan
clause the give thethe
end of typical
query, of m. t i t l e (i.e., the title of the movi
element name, then
again as in SQL. the keyword I N , and finally the name of the collection. E x a m p l e 9.5: Suppose we want the
TER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES thus a list of Movie objects.
9.1. IAiTRODUCTION TO OQL
For instance, address. \ire can get this set with the

OQL OUTPUT
The following examples will illustrate the correct syntax.
In the first three lines, we consider each
9.1.5 Movie object
Complex
SELECT DISTINCT m. IfS tthe
Output r u cnames t ao
t (Typ
Example 9.3:
Alternative usFR
Let of
Form OM for
ask
FROM Ithe
N Movies,
mLists I N stars
names ofs the m.stars
of Disney movies. The
studio that oxns this movie is "Disney,"FROthen
M Sthe
t a rcomplete t a r s sm2 bec
s s l , Sobject
following query does the job, eliminating duplicate names in the situation where a member of the output bag. The The fourthelements
WHERE lines in
lspecifies
. athe e sthat
s = the
d d r SELECT 2 . aobjec
sclause d d rn
o the SQL-style
a star anelements
is appeared
equivalent FR
FR OO clause
MMclauses,
inofseveral Disney for
where the
thequery
movies. in Example 9.2.
collection produced by the select-from-where query are to be ordered
be any expression, including expressi first by the val
y a name for a typical element, OQL allo~vsa completely m . l e n g t h (i.e., the length of the movie) That is, consider all pairs of star
more logical, SELECT DISTINCT
yet less SQL-is11 form.s.name
We can give the typical example, we can apply the S t r u c t typv
and then,
1%-e if there are ties, by the
of m. t i t l e (i.e., the title of the that movie). The value theproduced by this It que
FROM Movies
e, then the keyword I N , and m , m.stars
finally the names of the collection. thus a list of Movie objects.
get a they have
select-from-where samequery address.
that pro a
p~ecedesthe name of the second in alp
• Unlike SQL which produces relations, OQL produces
WTo
again
E m. ownedBy.
HERmake
as
the resultname
in SQL.
a list,=add "Disney"
an ORDER BY clause at the end of the query,
9.1.5 Complex Output address.
consisting of the same star t~viceand
Example 9.5: Suppose we want the
in two different orders.
Types
The m Istrategy of sthis m . s t a r sis similar to that of Example 9.2. We again
I N query
collection (set, bag, list) of objects
FROM N Movies, \ire can get this set with the
For every pair that passes the t ~
consider all pairs of a movie and a star of that movie in two nested loops as in
The following examples will illustrate the correct syntax. The elements in the SELECT clause typeneed of thisnot structure
be simpleisvariables.a record with They
M clause 9.2.
ent FROExample for the But now;inthe
query condition
Example 9.2. on that pair (m, s) is that "Disney" is the be any expression, including expressions SELECTbuilt DISTINCT
using type Sconstructors.
truct(star
name of the 9.3: studioLet whose object is m. type of each field is the class S t a r . s
• The object can be of any type
Example us askS t ufor d i othe names of ownedBy.
the stars of Disney movies. The
9.1. IAiTRODUCTION TO OQL 43 1
example, we can apply the S t r u cand t type s 2FR OM Sprovide
constructor
that t a r s tos lvalues
, S t afor
several r s the
s 2 two
expressions
following
The ORD query
ER BYdoes the job,
clause in OQL eliminating
is quiteduplicate
similar to names in the clause
the same situationin where
get a select-from-where query that
SQL. W
produces H E R Ea s
setl . a
or d d
bagr e s
ofs s2.addre
structures.
=
structure is
he result a astar
Keywordslist,appeared
addORan DER ORinDER
BY several
BY clause
are Disney
followed at the movies.
by end of the
a list of query,
expressions. The first of these
n SQL. In the first three
expressions lines, wefor
is evaluated consider
each object each Moviein theobject
resultm. If the
of the nameand
query, the Example 9.5: Suppose we want
of objects Thatthe is, set of
u cpairs
S t r1%-e ( s t aof
tconsider r 1stars
: all living
S tpairs at
a r , sof the
t a star
r2:
studio
are ordered SELECT
that oxns by thisDISTINCT
thisvalue.
movie is s.name
Ties,"Disney,"
if any,thenare thebrokencomplete
by theobjectvaluemofbecomes
the second address. \ire can get this set with the query:
xamples will illustrate theoutput
correct syntax. that they have the same address. It a
aexpression.
member FROM Movies
ofthenthe m , bag.
the third, m.stars
andThe so son.fourth
By line specifies
default, that Set
the order the of strings
object,s
is ascending. m but The typethe
p~ecedes of thename result
of of second
the the query in is
alp
SELECT DISTINCT S t r u c t ( s t a r l : s l , s t a r 2 : s 2 )
Let usproduced
a choice
ask for W H
ofby
the m.select-from-where
Eascending
REthe
names ownedBy.
ofor nameof=query
thedescending
stars "Disney"
order
Disney are to be
can
movies. ordered
beThe indicated firstbybythe
thekeyword
value of ASC FROM S t a r s s l , S t a r s s 2consisting of the same star t~viceand
m.or ljob, (i.e., theduplicate
e n geliminating
DESC, t hrespectively. length ofnames
followingthe movie)an and
attribute. then, ifinthere
aswhere SQL.are ties, by the value Set<Struct{starl: S t a r , sta
does the in the situation WHERE s l . a d d r e s s = s 2 . ain d dtwor e s sdifferent
AND s1.name orders.< s2.name
The
of m.Disney
in several strategy of this query is similar to that
(i.e., the title of the movie). The value produced by this query is
t i t l e movies. of Example 9.2. We again
Example
consider 9.4pairs: Letofusa find theand set aofstarDisney movies,
moviebut in let
twothe result be aaslist For every pair that passes the t ~ t
thus a list all of Movie movie
objects. of that nested loops in is, 1%-econsider all pairs of stars,
That s l and s2. The WHERE clause ch
ISTINCT ofExample
movies.
s.name ordered
9.2. Butby now;length. If there are
the condition on ties,
that let
pairthe (m,movies
s) is thatof equal length
"Disney" be
is the type of this structure is a record with
that they have the same address. It also checks that the name of the first
vies mordered
, name
m.stars alphabetically.
s The query is: type of each field is
of the studio whose S t u d i o object is m. ownedBy. p~ecedesthe name of the second in alphabetic order, so the
~3-edon't Star. s
class produce
ownedBy. 9.1.5name =Complex "Disney" Output Types 9.1.6
and 2 that Subqueries
SELECT m consisting of the same star t~vice and swe don'tprovide
producevalues the same for the
pairtwo of
The The
elements
FROM O R D E R
in BY
the clause
SELECT in OQL
clause is
need
m that of Example 9.2. We again quite
not similar
be simpleto the same
variables. clause
They in
canSQL.
in two different orders. structure is
y of this query is Movies
similar to Ure can use a select-from-whereexpres
s of a be Keywords
anyWHERE
movie and aO RDER BY
m.ownedBy.name
expression,
star are
including
of that moviefollowed
expressions
in=two by
"Disney" a built
nested list
loopsof expressions.
using
as Set
Theoffirst
in type constructors. objects
of ofFor
Forthese typeevery Movie
pair that passes the\Ye t ~ shall
tests,
o we giveproduce a record structure.
one example: in the
ut now; expressions
example, O R D
the condition E R is
BY evaluated
we canonapply m.length, for
the S(m,
that pair m each
. t i t
u cist type
t r s) object
l e in the
constructor
that "Disney" result
is the of the query,
to several expressions andand objects
type of this structure is a record subquery use appear sintSaSection
with S
two t r u c
fields,t ( s t a
named r 1 : tralrand
, s tsa9.2.
t ra2r 2: .
dio whose areaSordered
get by this
t u d i o object
select-from-where is m.value.
query Ties,
ownedBy. if any, are
that produces broken
a set or bag byofthe value of the second
structures. type of each field is the class S t a r . since that is the type of the variable
expression. then the third, and so on. By default, the order is ascending. but and s 2 that provide values for the The twotypefields. of That
the result of the the
is. formally, querytypeiso
BY clause in
Example OQL is quite similar
Suppose to the same clause in SQL. structure is
a choice of9.5: ascending orwe want the order
descending set of can
pairsbeofindicated
stars living at the
by the same ASC
keyword
R BY are followed by a list of expressions. The first of these Set<Struct{starl: S t a r , sta
address. \ire can get this set with the query:
valuatedorfor DESC, object in the following
each respectively. result of the an query,
attribute. as in SQL.
and objects S t r u c t ( s t a r 1 : S t a r , s t a r 2 : star)
his value. Ties, if any, are broken t r ubythe
c tthe t value of the second
Example
SELECT 9.4 : Let us Sfind
DISTINCT ( sseta rof
l :Disney
s l , s tmovies,
a r 2 : s 2but
) let the result be a list
2 there are ties, let the movies of equal length be Set of structures
the third, and so on. By default, the order is ascending. but The type of the result of the query is a set of these structures, that is:
of FROM S
movies. t a r s s by
ordered S t a r s s If
l , length.
nding or descending order can be indicated by the keyword ASC
WHEalphabetically.
ordered RE s l . a d d r e s s = s 2query s s AND s1.name < s2.name
. a d d r eis:
vely. following an attribute. as inThe SQL. Set<Struct{starl: S t a r , star2: Star)>
9.1.6 Subqueries 30
Let usThat is,SELECT
find the 1%-e consider
set of m
Disney all pairsbut
movies, of stars, l andbes2.
let the sresult a listThe WHERE clause checks
that they
ed by length. have are
If there the ties,
sameletaddress. It also
the movies checks
of equal thatbethe name of the first star
length
HAVING <condition>

i t i o n p) serves t o eliminate some of t h e groups created by the GROUP BY. The condition
applies t o the value of the p a r t i t i o n field of each structure in the intermedi-
e first realize that variable p rangcs
a t e collection. If true, then this structure is processed as in Section 9.2.3, t o
of the structure in the GROUP BY
form a structure of the output collection. If false, then this structure does not

OQL: AGGREGATION
e of the form S t r u c t (m: o ) , t+-hereo
contribute t o the output collection.
efore refers to this object
INTRODUCTION o. Thus.
TO OQL
of this Movie object E x a m p l e 9.11 : Let us repeat Example 9.10, but ask for t h e sum of the lengths
ces the bag of lengths of the movies of movies for only those studios and years such that the studio produced a t lewt
has t h e value "Disney" and y r has one movie of over 120 minutes. The query of Fig. 9.7 does the job. Notice t h a t
from is the bag of t h e lengths of the in t h e HAVING clause we used t h e same query as in the SELECT clause to obtain
apply thec l a sSsUM operator t o this bag
Movie the bag of le~lgtlisof movies for a given studio and year. In the HAVING clause,
s in the group. nThus,
( e x t e t Movies
onekey ( t i t l e , year))
member tve take the maximum of those lengths Aggregate
and compareover
it tthe partition
o 120.
C
attribute string t i t l e ;
a t t r i b u t e integer year;
a t t r i b u t e integer length; SELECT s t d o , y r , sumlength: SUM(SELECT p.m.length
Disney movies a t t r i bof enum Film (color,blackAndWhite> filmType;
u t e1990. FROM p a r t i t i o n p)
relationship Set<Star> s t a r s
FROM Movies m
inverse Star::starredIn;
M u l t i p l e rCe loaltlieocntsihoi n
p sS t u d i o ownedBy GROUP BY s t d o : m.ownedBy.name, y r : m.year
i n v e r s eaStudio::owns; HAVING MAX(SELECT p.m.length FROM p a r t i t i o n p) > 120
variable in the FROM clause. f e ~
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ;
y are necessary, but the principles
void starNames(out S e t < S t r i n g > ) ;
e above. Suppose that the variables
void otherMovies(in S t a r , o u t Set<Movie>) Figure 9.7: Restricting the groups considered
:xk. Then:
raises(noSuchStar);
I;

class Star Intermediate result


( e x t e n t S t a r s key name)
< Grouping fields
Struct{
a t t r i b u t e s t r i n g name;
a t t r i b u t e S t r u c t Addr
{string s t r e e t , s t r i n g c i t y ) address; stdo: …,
r e l a t i o n s h i p Set<Movie> s t a r r e d I n
inverse Movie::stars; yr: …,
1; partition: bag(struct {m: …})
};
c l a s s Studio
( e x t e n t S t u d i o s key name)
C
a t t r i b u t e s t r i n g name;
a t t r i b u t e s t r i n g address;
r e l a t i o n s h i p Set<Movie> owns
Bag of structures with members
i n v e r s e Movie::ownedBy; follow what’s in the FROM clause 31
I;
Raise the exception n o s i s t e r s if the ship FOR ALL x IN S : C(x)

The result of this expression is TRUE if every x in S satisfies C(x) and is FALSE
eter, and applying the method to a ship s, otherwise. Similarly, the expression

OQL: COLLECTION OPERATORS


le b, provided s participated in that battle.
articipate if ship s did
INTRODUCTION TO not
OQLfight in battle EXISTS x I N S : C(x)

has value TRUE if there is at least one x in S such that C(X) is TRUE and it has
ched as parameters, add a ship of this name value FALSE otherwise.
h the method is applied.
c l a s s Movie
Example 9.7 : Another way to express the query "find all the stars of Disney
of Exercise
C
( e x t e n t Movies key ( t i t l e , y e a r ) )
9.1.2 using at least one subquery Likeis in
• movies" SQL,
shown we
in Fig. 9.4. have
Here, ANY,
we focus on ALL,
a star s and ask if they are

allEXISTS
attribute string t i t l e ; the star of some movie rn that is a Disney movie. Line (3) tells us to consider
a t t r i b u t e integer year; movies m in the set of movies s. starredIn, which is the set of movies in
a t t r i b u t e integer length;
chema of Exercise which star s appeared. Line (1)then asks whether movie m is a Disney movie.
a t t r i b u t e 9.1.3
enum and Film Fig. 9.3, xvritc
(color,blackAndWhite> filmType;
relationship Set<Star> s t a r s If we find even one such movie m , the value of the EXISTS expression in lines
inverse Star::starredIn;
r e l a t i o n s h i p S t u d i o ownedBy
• OQL has similar operators
(3) and (4) is TRUE; otherwise it is FALSE.
of ships with at least nine i n v e rguns.
s e Studio::owns;
f l o a t lengthInHours() r a i s e s ( n o ~ e n g t h F 0 u n d ) ;
hip names)void withstarNames(out
at least nineS eguns. t<String>); 1) SELECT s
void otherMovies(in S t a r , o u t Set<Movie>)
r a i 30,000
s e s ( n o Stons.
u c h S t aNake
r);
2) FROM S t a r s s
ith a displacement under 3) WHERE EXISTS m IN s . s t a r r e d I n :
I;
rliest launch year first, and if there are ties. 4) m. ownedBy .name = "Disney"

class Star
( e x t (i.e.,
e n t Sships
t a r s key name)
Select stars who participated in a
are sister ships of the same class). Figure 9.4: Using an existential subquery
< movie made by ‘Disney’
ves are wanted, not the names of the ships.
a t t r i b u t e s t r i n g name; 438 CHAPTER 9. OBJECT-ORIENTATlOiV IN QUERY LANGUAG
a t t r i b u t e S t r u c t Addr
es in which ships { s t r of
i n gats t rleast
e e t , two
s t r i ndifferent
g c i t y ) address; Example 9.8 : Let us use the for-all operator to write a query asking for the
r e l a t i o n s h i p Set<Movie> s t a r r e d I n stars that have appeared only in Disney movies. Technically, that set includes
inverse Movie::stars; SELECT
.'stars" who appears in no movies at all (as far as we can tell from our database).
1; no ship was listed as damaged.
sin which It is possible to aadd
FROM S t r s sanother condition to our query, requiring that the star
appear inWHERE FOR one
at least ALLrnovie.
m I N but
s . s tTW
a r rlealr
e d I nthat
: improvement as ail exercise.
c l a s s Studio m. ownedBy
Figure 9.5 shows the query. .name = "Disney"
s of QQL
( e x t e Expressions
n t S t u d i o s key name)
C
a t t r i b u t e s t r i n g name; Select stars who participated only
of the othera toperators, besides select-from- Figure 9.5: Using
9.2.2 in Aggregation a subquery with universal quantification
t r i b u t e s t r i n g address; movies made by ‘Disney’
Expressions
us build expressions. These
r e l a t i o n s h i p Set<Movie> operators
owns in-
and there-exists - aggregation operators,
i n v e r s e Movie::ownedBy; OQL uses the same five aggregation operators that SQL does: AVG, COUNT.
32 SUM.
ators - I ;union, intersection, and difference. applying to a designated column of a table, the same operators
MIN. and MAX. However, while these operators in SQL may be thought in OQL
of asap
SELECT DISTINCT m
Movie. We can use the title and (to break9.3. ties)OBJECT
the year ofASSIGAr1IENT
the movie, since-4ND CR
44.1 CHAPTER 9. OBJECT- 0RIENT;LTION
FROM Movies m I N QUERY LANGUAGES
vies made before 1920. Its type is Set<Movie>. (title, year) is a key for Movie. Example The statement
9.15: Suppose we want a list of all the movie objects in the class
variable of the same type, then weWHERE maym.year write< 1920 Movie. We can use the title
9.3.1 Assigning Values to Host-Language VariablesmovieList = SELECT m (title, year) isthen theandtype (to break
of theties) the year of theand
variable movie,the
sinceexp

Unlike
STINCT m
es language
m
SQL, which needs INTEGRATING OQL & EXTERNAL
variables, OQL fits
produces the set of all those movies made before 1920. Its type is Set<Movie>.
If
to oldMovies
move is
data
(in C++naturally
a host-language
between
extended withinto
variable of
components the same type,
of
OQL):its host language. That is: the
then
tuples we may
and write
host-
FROM Movies m
ORDER BY m.title, movieListm.year;
a key
legal. for

= SELECT m
Movie. The statement

LANGUAGES
9.3.3FROM MoviesObtaining
mall the MovieEach Membe
arexpressions
< 1920; of OQL that we have learned, such as select-from-where, assigns produce
to host-language variable movieList a list of objects,
oldMovies = SELECT DISTINCT m ORDER BY m.title,
objects as values. It is possible to assign to any host-language variable sorted byoftitle the and year. Obtaining each m.year;
member of a set or bag is
become the set of these Movie objects. FROM Movies
proper type a value that is the result of one of these OQL expressions. m
the cursor-based algorithms we needed in
WHERE m.year < 1920; Once x-e haye a list, sortedassigns to host-language variable
or not. we can or bag access movieList
each
into list.a list\Ye
a element of all
by dotheso
number; Movie objects,
with a se
Example 9.13
ents of Collections : The OQL expression
the ith element of the list L is sorted
obtainedby titleby
andORDER
year.- 11.BY.
L[i Note that lists and arrays
Recall from Section 9.1.4 that
• OQL fits naturally in OO host languages
and the value of oldMovies will become the set of these Movie objects.
are assunled numbered starting at 0, as in C or C++.
group-bySELECT DISTINCT
expressions m
each produce collections Once x-e haye list
a list,ofsorted
theor selected objects
not. we can access or values.
each element by number;
FROM Movies m
we must do something extra if we 9.3.2 Extracting Elements of Collections E x a m p l e 9.16 : Suppose we want to write
want a single the ith element of the list L is obtained by L[i - Note that lists and arrays
• Returned objects are assigned in variables in the
11.
WHERE m.year < 1920 E xaa C++ m p l efunction
9.15: Suppose that printswethe want a lis
statement is true even if we have a collection title. year, and length of eacharemovie. assunled numbered
-1Movie.
sketch starting
ofWe at 0, can
the in Cuse
asfunction or C++.is shown in (to bre
Since the select-from-where the title and
e element. OQL provides the operator ELEMENT and group-by expressions each produce collections
isifFig. 9.9.
host program
produces the set of all those - movies
either sets, made
bags, or before
lists - we 1920.
must do Its type
something extra Set<Movie>.
we want a single (title, year) is a key for Movie. The s
o its lone member. This operator can be applied. Example 9.16 : Suppose we want to write a C++ function that prints the
If oldMovies is a host-language
uery that is known to return a element variable of the same type, then we may
of that collection. This statement is true even if we have a collection
singleton. write
title. year, and length of each movie. -1sketch
movieList of the function is shown in
= SELECT m
(in C++ extended with OQL): that n-e are sure contains only one element. OQL provides the operator1) ELEMENTmovieList = SELECT Fig. m9.9. FROM Movies m
ould like to assign to the variable gwtw.
to turn of type
a singleton collection into its lone member. This operator can be applied. FROM Movies m
s type) the oldMovies = SELECT
object representing the DISTINCT
movie Gone m ORDER BY m.title,
for instance, to the result of a query that is known to return a singleton. ORDER BY m.title, m.year;
he query FROM Movies m
2) number0fMovies = ~0UNT(Movies); 1) movieList = SELECT m
WHEREExample
m.year 9.14 <: Suppose
1920; we would like to assign to the variable gwtw. 3) for(i=O; i<numberOfMovies; assigns
of type i++) FROM to host-language variable movie
( Movies m
sortedORDER by BYtitle andm.year;
year.
and the value of oldMovies will become the set of these Movie objects.4) Gone movie = movieList [i] ;
Movie (i.e., the Movie class is its type) the object representing the movie m.title,
lllth the Wind. The result of the query year << I' "
WithVariable
the Wind"in host 5) cout << movie.title << " 'I << =movie.
2) number0fMovies
Once
~0UNT(Movies);
x-e haye a list, sorted or not. we
language (C++ or Java) 6 << movie. length << "\nl' ;
3) for(i=O; i<numberOfMovies; i++) (
9.3.2 Extracting Elements SELECT m of Collections
ne object. 11-e cannot assign this bag to variable 1 4)
the ith element of the list L is obtained b
movie = movieList [i] ;
FROM Movies m are assunled numbered starting at 0, as i
ld get
Sincea type error. However.
the select-from-where Array x e of
if and applyobjects of type Movie
the expressions cout << movie.title << " 'I << movie.year << I' "
WHEREgroup-by
m.title = "Gone With the Wind" each produce collections 5)
- either sets, bags, or lists - we must do something extra if we want a single Figure 9.9: Exanlining 6
and E x<<amovie.
printing llength
m p each e 9.16 << :"\nl'
movie
;
Suppose we want to w
m
element of that collection. is This
the bag statement
containing just is
this true
one even
object. 11-e if we
cannot have
assign this a
bag collection
to variable 1 title. year, and length of each movie. -
that n-e are sure contains only
gvtv one element.
directly, because we OQL
n-ould provides
get a type the
error. operator
However. if xe ELEMENT
apply the
ovies m Line (1) sorts theIterate over the list
Movie class, placing theinresult
Fig. a
9.9. natural
into variableway movielist,
to turn a singleton collection into
ELEMENT its
operatorlone
first,member. This operator can be applied.
~vhosetype is List<Movie>. Line (2) computes
m.title = "Gone With the Wind"
for instance, to the result of a query that is known to return a singleton. Figure 9.9: the number
Exanlining of movies.
and printing using
each movie
the OQL operator COUNT. Lines (3) through ( 6 ) are a for-loop in which integer
gwtw = ELEMENT(SELECT m 1) movieList = SELECT m
Example 9.14 : Suppose we would like to FROMassign
Movies to m the variable gwtw. of type Line (1) sorts the Movie class, placing the result intoFROM variable Movies
movielist, m
Movie (i.e., the Movie class is its type) the object
WHERE m.titlerepresenting
= "Gone With the theWind"movie Gone ~vhosetype is List<Movie>. Line (2)computes the number ORDER BY using
of movies. m.ti
lllth the Wind. The result of the query 1; the OQL operator COUNT. Lines 2) (3)number0fMovies
through (6) are a for-loop in= which integer
~0UNT(Mo
3) for(i=O; i<numberOfMovies
SELECT m
FROM Movies m
4) movie = movieList 33 [i] ;
WHERE m.title = "Gone With the Wind" 5) cout << movie.title <

You might also like