Object Oriented and Object Relational Databases, Logical and Web Databases-1-32
Object Oriented and Object Relational Databases, Logical and Web Databases-1-32
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
• 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.
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
! healthcare
! finance
! multimedia
! 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
8
DATABASE DESIGN PROCESS
Application Domain
or Universe of Discourse
Data Modelling
Conceptual Model
Logical Model
DBMS specific
resource-based
optimization
Physical Model 9
LOGICAL & PHYSICAL LAYERS
Mapping directly
onto ODL classes
Object-Oriented
database schema Optimization OODBMS
in ODL
10
EXAMPLE OF UML CLASSES
age(): Integer
Operations
changeAddress(newAdd: string)
11
FIRST APPROACH: OBJECT-ORIENTED
MODEL
• Relations are not the central concept, classes and objects are
the main concept
• Main Features:
• Powerful type system
• Classes
• Object Identity
• Inheritance
• 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
14
FEATURE 3: OBJECT IDENTITY
15
FEATURE 4: INHERITANCE
is sub-class.
changeAddress(newAdd: string)
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
17
Overview of ODL & OQL
18
Figure 4.2: An ODL declaration of the class Movie
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
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
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
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
26
OQL: OBJECT-ORIENTED QUERY
LANGUAGE
• OQL is a query language designed to operate on
databases described in ODL.
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 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;
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
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 <