<<

OBJECT-ORIENTED & OBJECT- RELATIONAL

CS561-SPRING 2012 WPI, MOHAMED ELTABAKH 1

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 AND (1990s) programming ! better versioning ! no 'reconstruction' of objects ! other OO advantages (reuse, inheritance etc.) 2

How do ODBMS Work?

! Relational Model ! Object Model ! Back to the Beginning

Example:

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (5 of 14) [10/13/2002 11:48:18 AM] STONEBRAKER’SStonebraker’s APPLICATIONApplication Matrix 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 26 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, , 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 Object Oriented Databases What is an Object Oriented Database?

! Back to the Beginning

Object Oriented Databases (ODBMS) store data together with the appropriate methods for accessingRELATIONAL it i.e. encapsulation. MODEL OF A ‘CAT’ 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

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (2 of 14) [10/13/2002 11:48:18 AM] Object Oriented Databases Object Oriented Databases What is an Object Oriented Database?

! Back to the Beginning

Object Oriented Databases (ODBMS) store data together with the appropriate methods for accessing it i.e. encapsulation.

Relational databases " hammer the world flat" by normalisation.

Relational database of a cat:

OBJECT ORIENTEDApplications MODEL OF A ‘CAT’

! Back to the Beginning

Object-orientedObject Oriented Databases database of a cat: 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

! http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htmThis enables: (2 oftext/document/quality 14) [10/13/2002 11:48:18 AM] management ! complex data types to be stored (e.g. CADThese applications) are the 'next-generation applications" where traditional IT methods have often not impacted. For example, it has been estimated that up to 90% of the data held in businesses is still paper-based, because a large amount of data is not 'record oriented'. 7

! a wide range of data types in the same database (e.g. multimedia applications)

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

! easier to follow objects through time (e.g. "evolutionary applications")

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (3 of 14) [10/13/2002 11:48:18 AM] TWO APPROACHES

• Object-Oriented Model (OODBMS) • Pure OO concepts

• Object-Relational Model (ORDBMS) • Extended relational model with OO concepts

8 PROCESS

Application Domain or Universe of Discourse

using ER model or UML

Data Modelling

Conceptual Model

using of the target DBMS

Logical Database Design

Logical Model

DBMS specific resource-based optimization Physical Database Design

Physical Model 9 LOGICAL & PHYSICAL LAYERS

Relational SQL ER diagram Normalization & RDBMS database design Physical design definitions

Mapping onto Relations (no operations)

Mapping onto UML class Object-Relational Normalization & Extended-SQL Relations and Object Physical design ORDBMS diagram types database design table definitions

Mapping directly onto ODL classes

Object-Oriented 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 , 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 ‘

• 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 ‘’ (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 name: {firstName: string, another one. 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 • ODL: Object Definition Language • OQL: Object

• ODL is somehow similar to DDL () in SQL

17 Overview of ODL & OQL

18 CHAPTER 4. OTHER DATA IVODELS 4.2. INTRODUCTION TO ODL 137 that suggested by Fig. 4.1. Objects have fields or slots in which values are Example 4.2: In Fig. 4.2 is an ODL declaration of the class of movies. It placed. These values may be of common types such as integers, strings, is not a complete declaration; we shall add more to it later. Line (1) declarw or arrays, or they may be references to other objects. Movie to be a class. Following line (1) are the declarations of four attributes that all Movie objects will have. When specifying the design of ODL classes, we describe properties of three 1) class Movie { 1. Attributes, which are values associated with the object. We discuss the 2) attribute string title; legal types of ODL attributes in Section 4.2.8. 3) attribute integer year; 4) attribute integer length; 2. Relationships, which are connections between the object at hand and an- 5) attribute enum Film Ccolor,blackAndMite) filmType; other object or objects. 3. Methods, which are functions that may be applied to objects of the class. Figure 4.2: An ODL declaration of the class Movie Attributes, relationships, and methods are collectively referred to as properties. The first attribute, on line (2), is named title. Its type is string-a CHAPTER 4. OTHER DATA IVODELS 4.2. INTRODUCTION TO ODL 137 4.2.2 Class Declarations character string of unknown length. U'e expect the value of the title attribute in any Movie object ODL:to be the name CLASSES of the movie. The next two& attributes, ATTRIBUTES year A declarationthat suggested of a class by Fig.in ODL, 4.1. Objectsin its simplest have fields form, or consists slots in whichof: values are Exampleand length 4.2: declared In Fig. on 4.2lines is (3)an andODL (4), declaration have integer of the type class and of represent movies. theIt placed. These values may be of common types such as integers, strings, isyear not in a whichcomplete the declaration;movie was made we shall and add its lengthmore to in itminutes, later. Line respectively. (1) declarw On 1. Theor arrays, keyword or theyclass, may be references to other objects. Movieline (5) to is beanother a class. attribute Following f ilmType, line (1) which are the tells declarations whether the of movie four attributeswas filmed inthat color all Movieor black-and-white. objects will have. Its type is an enumeration, and the name of the 2.When The specifyingname of the the class, design and of ODL classes, we describe properties of three enumeration is Film. Values of enumeration attributesKeyword are chosen attributefrom a list 3. A bracketed list of properties of the class. These properties can be at- of le'terals,1) colorclass andMovie blackAndWhite { in this example. tributes, relationships, or methods, mixed in any order. An2) object inattribute the class Moviestring as title; we have defined it so far can be thought of 1. Attributes, which are values associated with the object. We discuss the as a record or tuple with four components, one for each of the four attributes. legal types of ODL attributes in Section 4.2.8. 3) attribute integer year; That is, the simple form of a class declaration is 4) attribute integer length; 2. Relationships, which are connections between the object at hand and an- 5) attribute("Gone With enum theFilm Wind", Ccolor,blackAndMite) 1939, 231, color) filmType; other object or objects.class { { ("Gone With the Wind", 1939, 231, color)

Example 4.3 : In Example 4.2, all the attributes have atomic types. Here is 4.2.3 Attributes in ODL an example with a nonatomic type. We can define the class Star by The simplest kind of property is the attribute. These properties describe some 1) class Star C aspect of an object by associating a value of a fixed type with that object. 2) attribute string name; For example, person objects might each have an attribute name whose type is 3) attribute Struct Addr string and whose value is the name of that person. Person objects might also {string street, string city) address; have an attribute birthdate that is a triple of integers (i.e., a record structure) representing the year, month, and day of their birth. In ODL, unlike the E/R model, attributes need not be of simple types, such Line (2) specifies an attribute name (of the star) that is a string. Line (3) as integers and strings. lie just mentioned birthdate as an example of an specifies another attribute address. This attribute has a type that is a record attribute with a structured type. For another example, an attribute such as structure. The name of this structure is Addr, and the type consists of two phones might have a set of strings as its type, and even more complex types fields: street and city. Both fields are strings. In general, one can define are possible. \Ire summarize the type system of ODL in Section 4.2.8. record structure types in ODL by the keyword Struct and curly braces around CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION TO ODL 141

1. If we have a many-many relationship between classes C and D, then in 1) class Movie C class C the type of the relationship is Set,and in class D the type is 2) attribute string title; 3) attribute integer year; 4) attribute integer length; 2. If the relationship is many-one from C to D, then the type of the rela- 5) attribute enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 6) relationship Set stars CHAPTER 4. OTHER DATA MODELS 4.2. INTRODUCTION3. If the TO relationshipODL is many-one from D to C,141 then the roles of C and D inverse Star::starredIn; 1. If we have a many-manyare reversed relationship in (2) betweenabove. classes C and D, then in 1) class Movie C class C the type of the relationship is Set,and in class D the type is 7) 2)relationship attribute Studiostring title; ownedBy 3) attribute integer year; 4) attribute inverseinteger length; Studio::owns; 2. If the relationship4. If the is many-one relationship from Cis toone-one, D, then thenthe type the of type the rela-of the relationship in C is just 5) attribute enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 6) relationship Set stars CHAPTER 4. OTHER DATA MODELS 4.2.3. IfINTRODUCTION the relationship is TOmany-one ODL from D to C, then the roles of C and D141 1; inverse Star::starredIn; D, and in D it is just C. are reversed in (2) above. 7) relationship Studio ownedBy 1. If we have a many-many relationship between classes C and D, then in 1) class Movie C inverse Studio::owns; 4. Ifclass the relationshipC the type ofis one-one,the relationship then the is type Set, of the andrelationship in class inD Cthe is justtype is 2) 1;attribute string title; D, and in D it is just C. 3) attribute integer year; Note, that as in the E/R model, we allow a many-one or one-one relationship 8) class4) Starattribute C integer length; 2. If the relationship is many-one from C to D, then the type of the rela- 8) class Star Note, that as in the E/R model, we allow a many-one or one-one relationship 5) attributeC enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 6)9) relationshipattribute string Set name; stars to include theto case include where forthe some case objects where the for "one" some is actually objects "none." the "one"For is actually "none." For 9) attribute string name; ODL:CHAPTER 4. RELATIONSHIPSOTHER DATA MODELS 4.2. INTRODUCTION TO3. ODL If the relationship is 141many-one from D to C, then the roles of C and D 10) attribute Structinverse Addr Star::starredIn; instance, a many-one relationship from C to D might have a missing or "" are reversed in (2) above. 7) relationship(string street,Studio ownedBystring city) address; 1. If we have a valuemany-many ofrelationship the relationshipbetween classes C and D, in then some in of the C objects. Of course, since a D object inverse Studio::owns;1) class Movie C class C the type of the relationship is Set,instance,and in class D the a type many-one is relationship from C to D might have a missing or "null" 10) 11)attribute relationship Struct Set Addr starredIn2) attribute string title; could4. beIf theassociated relationship with any is one-one, set of C then objects, the typeit is alsoof the permissible relationship for inthat C isset just 1; 3) attribute integer year; D, and in D it is just C. inverse Movie::stars;4) attribute integer length; 2. If the relationshipto beis many-one empty from C for to D, some then the type D of objects. the rela- attribute enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 5) Keyword relationship Note, that asvalue in the of E/R the model, relationship we allow ina many-onesome of orthe one-one C objects. relationship Of course, since a D object 8) class(string Star street, string6) city)relationship address; Set stars 3; C 3. If the relationship is many-one from D to C, then the roles of C and D inverse Star::starredIn; : 9) attribute string name; are reversed inExample to(2) above. include 4.6 the Incase Fig. where 4.3 we for have some the objects declaration the of"one" three is classes, actually Movie, "none." Star, For 7) relationship Studio ownedBy Keyword set andinstance, Studio. a many-oneThe first tworelationship of these havefrom alreadyC to D beenmight introduced have a missing in Examples or "null" 10)12) classattribute Studio Structi Addr inverse Studio::owns; 4. If the relationship is one-one, then the typecould of the relationship be inassociated C is just with any set of C objects, it is also permissible for that set 11) relationship(string Set street, string starredIn city)1; address; D, and in D it valueis just C. of the relationship in some of the C objects. Of course, since a D object 13) attribute string name; 4.2 and 4.3. ?Ve also discussed the relationship pair stars and starredIn. 11) relationship Set starredIn8) class Star C Set: set of unsortedNote, that unique as in theSince couldE/R model, each bewe allow associated of a many-one their or one-onetypes with relationship usesany setSet, of weC objects,see that itthis is also pair permissible represent.^ fora many- that set 14) attribute stringinverse address; Movie::stars; 9) attribute string name; objects to include the case whereto befor some empty objects the for "one" someis actually "none."D objects. For inverse Movie::stars;10) attribute Struct Addr instance, a many-onemany relationship relationship from C to Dto might be have between aempty missing or "null" Star for andsome Movie. D objects. 15) 3; relationship Set owns (string street, string city) address; value of the relationship in some of the C objects. Of course, since a D object inverse Movie::ownedBy;11) relationship Set starredIn Bag: set of unsortedcould be associated objects withExample anyStudio set of C objects, objects 4.6 it is also: In permissiblehave Fig. attributes for 4.3 that set we have name the and declaration address; of these three appear classes, in Movie, lines (13) Star, inverse Movie::stars; to be empty for some D objects. 12) class Studio i with possible duplication andand (14). Studio. Notice The that first thetwo type of these of addresses have already here been is a introduced string, rather in Examplesthan a 1; 3; 3;13) attribute string name; Example 4.6 : In structureFig.4.2 4.3 weand have the 4.3.declarationas was ?Veof threeused classes,also Movie,for discussed Star,the address the relationship attribute of pair class stars Star andon linestarredIn. (10). 12) class Studio i and Studio. The firstSince two of these each have already of beentheir introduced types in Examples uses Set, we see that this pair represent.^ a many- 14) attribute string address; List: set of sorted4.2 andlist 4.3. ?Ve also discussed the relationship pair stars and starredIn. : 13) attribute string name; Theremany isrelationship nothingExample wrong between with 4.6 Star using In and attributes Fig. Movie. 4.3 weof the have same the name declaration but different of three classes, Movie, Star, 15) relationship Set owns14) attribute string address; Since each of their types uses Set, we see that this pair represent.^ a many- Figure 4.3: Some ODL classes and15) theirrelationship relationships Set owns Array: set of sortedmany relationship list betweentypes StarStudio in and different Movie. objects classes. have attributes name and address; these appear in lines (13) inverse Movie::ownedBy; Studio objects have attributes name and address; these appear in lines (13) inverse Movie::ownedBy; referenced by index andIn (14).line (7) Notice we see that a relationship the type ofownedBy addresses from here movies is ato string, studios. rather Since than the a 1; 1; and (14). Notice that the type of addressesand here is a Studio. string, rather than a The first two of these have already been introduced in Examples 12) class Studio i structure as was usedtypestructure20 for the of address the attributeasrelationship was of class used Star on is linefor Studio, (10). the address and not Set,attribute of classwe are Star declaring on line that (10). There is nothing wrongThere with using is attributes nothing of the same wrong name but different with using attributes of the same name but different DIC Figure 4.3: Some ODL classes and their relationships types in different classes.for each movie there is one studio that owns it. The inverse of this relationship Figure 4.3: Some ODL classes and their relationships In line (7) we seetypes a relationship in ownedBy different from4.2 movies and classes.to studios. 4.3. Since the ?Ve also discussed the relationship pair stars and starredIn. type of the relationshipis found is Studio,In line andon not line (7)Set, (15).we seewe are There declaringa relationship thatwe see the ownedByrelationship from owns movies from tostudios studios. to movies. Since the 13) attribute string name; DIC for each movie there is one studio that owns it. The inverse of this relationship is found on line (15).Thetype There wetype seeof thethe ofrelationship thisrelationship owns relationship from studios to is movies. Studio, is Set, and not indicating Set, that eachwe are studio declaring o~vns thata The type of this relationshipsetfor of each is movies-perhapsSet, movieindicating Since there that each each is studio0, one perhapso~vns of studioa their 1, that or types perhaps owns usesit. a Thelarge Set, inverse number we of seeofthis movies. thatrelationship this pair represent.^ a many- DIC set of movies-perhaps 0, perhaps 1, or perhaps a large number of movies. 14) attribute string address; is found on line (15). There we see the relationship owns from studios to movies. Notice that this rule works even if C and D are the same class. There are some 4.2.7 MethodsThe in ODL type of this relationship is Set,indicating that each studio o~vnsa Notice that this rule works even if C and Drelationships are the that samelogically run class. from a class There to itself, suchare as some"child of" from 4.2.7 Methodsmany relationship in ODL between Star and Movie. the class "Persons" to itself. The third kind of propertyset of ODL movies-perhaps classes is the method. As in other0, object- perhaps 1, or perhaps a large number of movies. 15) relationshipsrelationship that logically Set run from a class owns to itself, such as "child of" from oriented languages, a method is a piece of executable code that may be applied to the objects of theThe class. third kind of property of ODL classes is the method. As in other object- Noticethe class that "Persons" this rule worksto itself. even if C and D4.2.6 are Multiplicitythe same of class.Relationships There are some In ODL, we can declare4.2.7 the names of theMethods methods associated with in a class andODL the input /output typesoriented of those methods. languages, These declarations,Studio a calledmethod signatures, objects is a piece have of executable attributes code name that andmay beaddress; applied these appear in lines (13) relationships that logicallyinverse run from aMovie::ownedBy; classLike theto binary itself, relationships such of the asE/R model,"child a pair ofof" inverse from relationships '~ctuall~,the Set couldThe be replaced third by another kind "collection of type," property such as list or bag, of ODL classes is the method. As in other object- the class "Persons" to itself. in ODL can be classified as either many-many, many-one in either direction, or as discussed in Sectionto 4.2.8. the We shall objects assume all collections of the are sets inclass. our exposition of one-one. The type declarations for the pair of relationships tells us which. relationships, however. oriented languages, a method is a piece of executable code that may be applied 4.2.6 Multiplicity of Relationships In ODL, weand can declare(14). theNotice names that of the methodsthe type associated of addresses with a class here and is a string, rather than a theto inputthe objects /output of types the class. of those methods. These declarations, called signatures, 4.2.61; Multiplicity of Relationships In ODL, we can declare the names of the methods associated with a class and Like the binary relationships of the E/R model, a pair of inverse relationships the'~ctuall~, input /outputthestructure Set typescould be ofas replacedthose was methods. byused another for These "collection the declarations, address type," such calledattribute as list signatures, or bag, of class Star on line (10). Likein ODL the binarycan be relationshipsclassified as either of the many-many, E/R model, many-one a pair of ininverse either relationshipsdirection, or as discussed'~ctuall~, in theSection Set 4.2.8.could beWe replacedshall assume by another all collections "collection are setstype," in oursuch exposition as list or of bag, inone-one. ODL can The be typeclassified declarations as either for many-many, the pair of many-onerelationships in eithertells us direction, which. or relationships,as discussed however.in Section 4.2.8. We shall assume all collections are sets in our exposition of one-one. The type declarations for the pair of relationships tells us which. relationships, however.There is nothing wrong with using attributes of the same name but different Figure 4.3: Some ODL classes and their relationships types in different classes. In line (7) we see a relationship ownedBy from movies to studios. Since the type of the relationship is Studio, and not Set,we are declaring that DIC for each movie there is one studio that owns it. The inverse of this relationship is found on line (15). There we see the relationship owns from studios to movies. The type of this relationship is Set,indicating that each studio o~vnsa set of movies-perhaps 0, perhaps 1, or perhaps a large number of movies.

Notice that this rule works even if C and D are the same class. There are some 4.2.7 Methods in ODL relationships that logically run from a class to itself, such as "child of" from the class "Persons" to itself. The third kind of property of ODL classes is the method. As in other object- oriented languages, a method is a piece of executable code that may be applied to the objects of the class. 4.2.6 Multiplicity of Relationships In ODL, we can declare the names of the methods associated with a class and the input /output types of those methods. These declarations, called signatures,

Like the binary relationships of the E/R model, a pair of inverse relationships '~ctuall~,the Set could be replaced by another "collection type," such as list or bag, in ODL can be classified as either many-many, many-one in either direction, or as discussed in Section 4.2.8. We shall assume all collections are sets in our exposition of one-one. The type declarations for the pair of relationships tells us which. relationships, however. ODL: RELATIONSHIPS & INVERSE CHAPTERRELATIONSHIPS 4. OTHER DATA MODELS 4.2. INTRODUCTION TO ODL 141 1. If we have a many-many relationship between classes C and D, then in 1) class Movie C class C the type of the relationship is Set,and in class D the type is 2) attribute string title; 3) attribute integer year; 4) attribute integer length; 2. If the relationship is many-one from C to D, then the type of the rela- 5) attribute enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 6) relationship Set stars 3. If the relationship is many-one from D to C, then the roles of C and D inverse Star::starredIn; are reversed in (2) above. 7) relationship Studio ownedBy Keyword inverse inverse Studio::owns; 4. If the relationship is one-one, then the type of the relationship in C is just 1; D, and in D it is just C.

8) class Star C Note, that as in the E/R model, we allow a many-one or one-one relationship 9) attribute string name; to include the case where for some objects the "one" is actually "none." For 10) attribute Struct Addr instance, a many-one relationship from C to D might have a missing or "null" (string street, string city) address; value of the relationship in some of the C objects. Of course, since a D object 11) relationship Set starredIn could be associated with any set of C objects, it is also permissible for that set inverse Movie::stars; to be empty for some D objects. 3; Example 4.6 : In Fig. 4.3 we have the declaration of three classes, Movie, Star, 12) class Studio i Inverseand Studio. of The first two of these have already been introduced in Examples 13) attribute string name; 4.2 and 4.3. ?Ve also discussed the relationship pair stars and starredIn. 14) attribute string address; eachSince other each of their types uses Set, we see that this pair represent.^ a many- 15) relationship Set owns many relationship between Star and Movie. inverse Movie::ownedBy; Studio objects have attributes name and address; these appear in lines (13) 1; and (14). Notice that the type of addresses here is a string, rather than a structure as was used21 for the address attribute of class Star on line (10). There is nothing wrong with using attributes of the same name but different Figure 4.3: Some ODL classes and their relationships types in different classes. In line (7) we see a relationship ownedBy from movies to studios. Since the type of the relationship is Studio, and not Set,we are declaring that DIC for each movie there is one studio that owns it. The inverse of this relationship is found on line (15). There we see the relationship owns from studios to movies. The type of this relationship is Set,indicating that each studio o~vnsa set of movies-perhaps 0, perhaps 1, or perhaps a large number of movies.

Notice that this rule works even if C and D are the same class. There are some 4.2.7 Methods in ODL relationships that logically run from a class to itself, such as "child of" from the class "Persons" to itself. The third kind of property of ODL classes is the method. As in other object- oriented languages, a method is a piece of executable code that may be applied to the objects of the class. 4.2.6 Multiplicity of Relationships In ODL, we can declare the names of the methods associated with a class and the input /output types of those methods. These declarations, called signatures,

Like the binary relationships of the E/R model, a pair of inverse relationships '~ctuall~,the Set could be replaced by another "collection type," such as list or bag, in ODL can be classified as either many-many, many-one in either direction, or as discussed in Section 4.2.8. We shall assume all collections are sets in our exposition of one-one. The type declarations for the pair of relationships tells us which. relationships, however. ODL: MULTIPLICITYCHAPTER 4. OTHER DATA MODELSOF RELATIONSHIPS4.2. INTRODUCTION TO ODL 141

1. If we have a many-many relationship between classes C and D, then in 1) class Movie C class C the type of the relationship is Set,and in class D the type is 2) attribute string title; 3) attribute integer year; Based on the use of collection 4) attribute integer length; types (set, bag,2. If the etc.) relationship is many-one from C to D, then the type of the rela- 5) attribute enum Film {color,black~ndWhite~filmType; tionship in C is just D,while the type of the relationship in D is Set. 6) relationship Set stars 3. If the relationship is many-one from D to C, then the roles of C and D inverse Star::starredIn; are reversed in (2) above. 7) relationship Studio ownedBy Many-to-Many relationship inverse Studio::owns; 4. If the relationship is one-one, then the type of the relationship in C is just 1; D, and in D it is just C.

8) class Star C Note, that as in the E/R model, we allow a many-one or one-one relationship 9) attribute string name; to include the case where for some objects the "one" is actually "none." For 10) attribute Struct Addr One-to-Manyinstance, relationship a many-one relationship from C to D might have a missing or "null" (string street, string city) address; value of the relationship in some of the C objects. Of course, since a D object 11) relationship Set starredIn could be associated with any set of C objects, it is also permissible for that set inverse Movie::stars; to be empty for some D objects. 3; What aboutExample multiway 4.6 : In Fig. 4.3 we have the declaration of three classes, Movie, Star, 12) class Studio i relationships???and Studio. The first two of these have already been introduced in Examples 13) attribute string name; 4.2 and 4.3. ?Ve also discussed the relationship pair stars and starredIn. 14) attribute string address; --Not supportedSince each of their types uses Set, we see that this pair represent.^ a many- 15) relationship Set owns many relationship between Star and Movie. --Need to convertStudio a multiway objects have to attributes name and address; these appear in lines (13) inverse Movie::ownedBy; multiple binary relationships 1; and (14). Notice that the type of addresses here is a string, rather than a structure as was used22 for the address attribute of class Star on line (10). There is nothing wrong with using attributes of the same name but different Figure 4.3: Some ODL classes and their relationships types in different classes. In line (7) we see a relationship ownedBy from movies to studios. Since the type of the relationship is Studio, and not Set,we are declaring that DIC for each movie there is one studio that owns it. The inverse of this relationship is found on line (15). There we see the relationship owns from studios to movies. The type of this relationship is Set,indicating that each studio o~vnsa set of movies-perhaps 0, perhaps 1, or perhaps a large number of movies.

Notice that this rule works even if C and D are the same class. There are some 4.2.7 Methods in ODL relationships that logically run from a class to itself, such as "child of" from the class "Persons" to itself. The third kind of property of ODL classes is the method. As in other object- oriented languages, a method is a piece of executable code that may be applied to the objects of the class. 4.2.6 Multiplicity of Relationships In ODL, we can declare the names of the methods associated with a class and the input /output types of those methods. These declarations, called signatures,

Like the binary relationships of the E/R model, a pair of inverse relationships '~ctuall~,the Set could be replaced by another "collection type," such as list or bag, in ODL can be classified as either many-many, many-one in either direction, or as discussed in Section 4.2.8. We shall assume all collections are sets in our exposition of one-one. The type declarations for the pair of relationships tells us which. relationships, however. 142 CHAPTER 4. OTHER DATA MODELS 2. lXTRODUCTIOAr TO ODL 143

Line (8) declares a method 1engthInHours. We might imagine that it pro- Why Signatures? uces as a return value the length of the movie object to which it is applied, but erted from minutes (as in the attribute length) to a floating-point number The value of providing signatures is that when we implement the schema is the equivalent in hours. Note that this method takes no parameters. in a real programming language, we can check automatically that the Movie object to which the method is applied is the "hidden" argument, implementation matches the design as was expressed in the schema. We it is from this object that a possible implementation of 1engthInHours cannot check that the implementation correctly implements the "meaning" ould obtain the length of the movie in minute^.^ of the operations, but we can at least check that the input and output thod 1engthInHours may raise an exception called noLengthFound, Pre- parameters are of the correct number and of the correct type. ly this exception would be raisedODL: if the length METHODS attribute of the object ue that could not represent a valid length (e.g., a negative number). are like function declarations in C or C++ (as opposed to function definitions, which are the code to implement the function). The code for a method would 1) class Movie { be written in the host language; this code is not part of ODL. 2) attribute string title; Declarations of methods appear along with the attributes and relationships 3) attribute integer year; in a class declaration. As is normal for object-oriented languages, each method . 4) attribute integer length; is associated with a class, and methods are invoked on an object of that class. 5) attribute enumeration(color,blackAndWhite) filmType; Thus, the object is a "hidden" argument of the method. This style allows the 6) relationship Set stars Three methods declarations same method name to be used for several different classes, because the object inverse Star::starredIn; upon which the is performed determines the particular method meant. 7) relationship Studio ownedBy Such a method name is said to be overloaded. inverse Studio::oms; The syntax of method declarations is similar to that of function declarations 8) float lengthInHours() raises(noLengthF0und); in C, with two important additions: 9) void starNames(out Set); LO) void otherMovies(in Star, out Set) Parameters are either 1. Method parameters are specified to be in, out, or inout, meaning that raises(noSuchStar); IN, OUT, or INOUT they are used as input parameters, output parameters, or both, respec- tively. The last two types of parameters can be modified by the method; in parameters cannot be modified. In effect, out and inout parameters are passed by reference, while in parameters may be passed by value. Figure 4.4: Adding method signatures to the Movie class Note that a method may also have a return value, which is a way that a result can be produced by a method other than by assigning a value to In line (9) we see another method signature, for a Definitionmethod called (implementation)starNames. is an out or inout parameter. This method has no return value but has an output notparameter part whose of the type class is a set of strings. We presume that the value of the output paramet,er is computed 2. Methods may raise ezceptions, which are special responses that are out- by starNames to be the set of strings that are the values of the attribute name side the normal parameter-passing and return-value mechanisms by which for the stars of the movie to which the method is applied. However, as always methods communicate. An exception usually indicates an abnormal or 23 there is no guarantee that t,he method definition behaves in this particular way. unexpected condition that will be "handled" by some method that called Finally, at line (10) is a third method, otherMovies. This method has an it (perhaps indirectly through a sequence of calls). Division by zero is an input parameter of type Star. A possible implementation of this method is as example of a condition that might be treated as an exception. In ODL: a follows. We may suppose that otherMovies expects this star to be one of the method declaration can be follo~vedby the keyword raises, followed by stars of the movie; if it is not, then the exception nosuchstar is raised. If it is a parenthesized list of one or more exceptions that the method can raise. one of the stars of the movie to which the method is applied, then the output parameter, whose type is a set of movies, is given as its value the set of all the Example 4.7: In Fig. 4.4 we see an evolution of the definition for class Movie, the actual definition of the method 1engthInHours a special term such as self would last seen in Fig. 4.3. The methods included with the class declaration are as be used to refer to the object to which the method is appUed. This matter is of no concern follows. as far as declarations of method signatures is concerned. 148 CHAPTER 4. OTHER DATA MODELS . ADDITIONAL ODL CONCEPTS

3. Keys, which are optional in ODL. m each of these to Contract. For instance, the inverse of theMovie might named contractsfor. Itre would then replace line (3) of Fig. 4.6 by 4. Extents, the set of objects of a given class that exist in a database. These are the ODL equivalent of entity sets or relations, and must not be con- 3) relationship Movie theMovie fused with the class itself, which is a schema. inverse Movie::contractsFor; 148 CHAPTER 4. OTHER DATA MODELS . ADDITIONAL ODL CONCEPTS 4.3.1 Multiway Relationships in ODL nd add to the declaration of Movie the statement: relationship Set contractsFor ODL3. supports Keys, which only binaryare optional relationships. in ODL. There is a trick, which we introduced m each of these to Contract. ForCHAPTER instance, 4. the OTHER inverse of DATA theMovie MODELS might 3. ADDITIONAL ODL CONCEPTS in Section 2.1.7, to replace a multiway relationship by several binary, many-one 150 named contractsfor.inverse C0ntract::theMovie; Itre would then replace line (3) of Fig. 4.6 by . 151 relationships.4. Extents, Suppose the set of we objects have aof multiwaya given class relationship that exist Rin amonga database. classes These or are the ODL equivalent of entity sets or relations, and must not be con- tice that in Movie, the relationship contractsFor gives us a set of contracts, entity sets Cl, C2, . . . ,C,. We may replace R by a class C and n many-one 3) relationship Movie theMovie fused with the class itself, which is a schema. 4.3.3 ce thereMultiple may inversebe Inheritanceseveral Movie::contractsFor; contracts in associated ODL with one movie. Each contract binary relationships from C to each of the Ci5s. Each object of class C may be the set is essentially a triple consisting of that movie, a star, and a studio, thought of as a tuple t in the relationship set for R. Object t is related, by the sometimes,ndus addthe assalaryto in the the thatdeclaration case is paidof a ofmovieto Movie the likestar the "Rogerby statement: the studio Rabbit," for weacting need in a that class movie. that n 4.3.1many-one Multiway relationships, Relationships to the objects of in the ODL classes Ci that participate in is a subclass of two or more other classes at the same time. In the E/R model, theODL relationship-set supports only tuple binary t. relationships. There is a trick, which we introduced relationship Set contractsFor in Section 2.1.7, to replace a multiway relationship by several binary, many-one n,e were able to imagineinverse that C0ntract::theMovie; "Roger Rabbit" was represented by components in Example 4.9: Let us consider how we would represent in ODL the 3-way relationships. Suppose we have a multiway relationship R among classes or all three3.2 of theSubclasses Movies, Cartoons, in ODL and fdurder-Mysren'es entity sets, which were relationship Contracts, whose E/R diag~amwas given in Fig. 2.7. We may tice that in Movie, the relationship contractsFor gives us a set of contracts, entity sets Cl, C2, . . . ,C,. We may replace R by a class C and n many-one connectedLet us recallin an theisa-hierarchy. discussion of However, subclasses a inprinciple the E/R of model object-oriented from Section systems 2.1.11. start wid1 the class defiriliions for Novie, Star, and Studio, the three classes ce there may be several contracts associated with one movie. Each contract e ODL standard does not dictate how such conflicts are to be resolved. binary relationships from C to each of the Ci5s. Each object of class C may be There is a similar capability in ODL to declare one class C to be a subclass that are related by Contracts, that we saw in Fig. 4.3. is that theobjects set is belongessentially to onea triple and consisting only one ofclass. that movie,Thus, toa star, represent and a moviesstudio, ome possible approaches to handling conflicts that arise from multiple inheri- thought of as a tuple t in the relationship set for R. Object t is related, by the of another class D. We follow the name C in its declaration with the keyword We must create a class Contract that corresponds to the 3-way relationship us the salary that is paid to the star by the studio for acting in that movie. n many-one relationships, to the objects of the classes Ci that participate in thatextends are both and cartoons the name and D. murder mysteries, we need a fourth class for these Contracts.the relationship-set The three tuplemany-one t. relationships from Contract to the other three movies. classes we shall call thenovie, thestar, and thestudio. Figure 4.6 shows the TheExample class CartoonMurderMystery4.10: Recall Example 2.10, must where inherit we propertiesdeclared cartoonsfrom both to Car-be a . Disallow multiple inheritance altogether. This approach is generally re- definitionExample of 4.9:the classLet Saritract.us consider how we would represent in ODL the 3-way toonsubclass and3.2 MurderMystery, ofSubclasses movies, with asthein suggested additionalODL by property Fig. 4.7. of aThat relationship is, a ~artoonMurder- from a cartoon relationship Contracts, whose E/R diag~amwas given in Fig. 2.7. We may ODL: INHERITANCE garded as too limiting. t: t: Leta usset recall of stars the discussionthat are its of subclasses"voices." Irein the can E/R create model a subclass from Section Cartoon 2.1.11. for start wid1 the class defiriliions for Novie, Star, and Studio, the three classes 1) class Contract i MysteryhlovieThere object withis a similarthe has ODL all capability the declaration: properties in ODL of to a declareMovie object,one class plus C tothe be relationship a subclass that are related by Contracts, that we saw in Fig. 4.3. . Indicate which of the candidate definitions of the property applies to the 2) attribute integer salary; voicesof another and the class attribute D. We weapon.follow the name C in its declaration with the keyword We must create a class Contract that corresponds to the 3-way relationship class Cartoon extends Movie i 3) relationship Movie theMovie extends and the name D. subclass. For instance, in Example 4.11 we may decide that in a courtroom Contracts. The three many-one relationships from Contract to the other three relationship Set voices; inverse ... ; • Same Idea as in OOMovie programming (C++ or Java) romance we are more interested in whether the movie has a happy or sad classes we shall call thenovie, thestar, and thestudio. Figure 4.6 shows the 4) relationship Star thestar Example• Subclass 4.10: Recall inherits Example all 2.10,attributes, where we declaredrelationships, cartoons to and be a methods ending than we are in the verdict of the courtroom trial. In this case, we definition of the class Saritract. subclass of movies, with the additional property of a relationship from a cartoon inverse ... ; ITe have not• indicatedPlus adding the name additional of the inverse of fields relationship voices, although would specify that class Courtroom-Romance inherits attribute ending 5) relationship Studio thestudio technically t: a set of westars must that do are so. its "voices." Ire can create a subclass Cartoon for 1) class Contract i hlovie with the ODL declaration: Keyword extends from superclass Romance, and not from superclass Courtroom. inverse . . . ; A subclass inherits all the properties of its superclass. Thus, each cartoon 2) attribute integer salary; Cartoon MurderMystery 1; objectclass has attributes Cartoon title,extends year, Movie length, i and f ilmType inherited from ~ovie 3) relationship Movie theMovie 3. Give a new name in the subclass for one of the identically named proper- (recall Fig.relationship 4.3), and it inheritsSet relationships voices; stars and ownedBy fromCartoon Movie, movie is a movie inverse ; ... in addition to its own relationship voices. ties in the superclasses. For instance, in Example 4.11, if C~urt~o~~-~~~- Figure4) 4.6: A classrelationship Contract toStar represent thestar the 3-way relationship Contracts with voices of characters Also in that esample. we defined a class of murder mysteries with additional inverse ... ; ance inherits attrihute ending from superclass Romance, then we may attributeITe have notweapon. indicated theCartoonMurderMyster~ name of the inverse of relationship voices, although There5) is one attributerelationship of the class Studio Contract, thestudio the salary, since that quantity is technically we must do so. specify that class Courtroom-Romance has an additional attribute called inverse . . . ; associated with the contract itself, not with any of the three part,icipants. Recall Aclass subclass FigureMurderMystery inherits 4.7: allDiagram the extends properties showing Movie of multipleits superclass. inheritance Thus, eachMurder cartoon movie is a movie verdict, which is a renaming of the attribute ending inherited from class that in Fig. 2.71; we made an analogous decision to place the attribute salary on object hasattribute attributes string title, year,weapon; length, and f ilmType inherited from ~ovie Courtroom. the relationship Contracts, rather than on one of the participating entity sets. (recall Fig. 4.3), and it inherits relationships stars and ownedBy fromwith Movie, the weapons used The other properties of Contract objects are the three relationships mentioned. Figure 4.6: A class Contract to represent the 3-way relationship Contracts inIn additionODL, we to may its own follow relationship the keyword voices. extends by several classes, separated Note that we have not named the inverses of these relationships. need by iscolons.3 a suitableAlso inThus, that declaration esample.we may ofdeclare we this defined subclass. the a fourthclass Again, of class murder all by: t,he mysteries properties with of additionalmovies are 4.3.4 Extents to modify the declarations of Movie, Star, and Studio to include relationships inherited by MurderMystery. There is one attribute of the class Contract, the salary, since that quantity is attribute weapon. When an ODL class is part of the database being defined, we need to distinguish \ associated with the contract itself, not with any of the three part,icipants. Recall classclass CartoonMurderMystery MurderMystery extends Movie Inherits from two other that in Fig. 2.7 we made an analogous decision to place the attribute salary on extendsattribute MurderMystery string weapon; : Cartoon; the class definition itself from the set of objects of that class that exist at a the relationship Contracts, rather than on one of the participating entity sets. classes \ given time. The distinction is the same as that between a relation scllema The other properties of Contract objects are the three relationships mentioned. isWhen a suitable a class declaration C inherits of thisfrom subclass. several classes, Again, all there t,he propertiesis t,he potential of movies for arecon- and a relation instance, even though both can be referred to by the name Note that we have not named the inverses of these relationships. need 24 to modify the declarations of Movie, Star, and Studio to include relationships fiietsinherited among byproperty MurderMystery. names. Two or more of the superclasses of C may have a \ property of the same name, and the types of these properties may differ. Class CmoonMurderMystery did not present such a problem, since the only prop-

\ erties in common between Cartoon and ~urder~ystery'are the ropert ties of In ODL, the distinction is made explicit by giving the class and its eztent, Movie, which are the same property in both superclasses of CartoonMurder- or set of existing objects, different names. Thus, the class name is a schema Mystery. Here is an example where we are not so lucky. for t,he class, while the extent is the name of the currellt set of objects of that class. We provide a name for the extent of a class by follo-~ingthe class name Example 4.11: Suppose we have subclasses of Movie called Romance and by a parenthesized expression consisting of the keyword extent and the name Courtroom. Further suppose that each of these subclasses has an attribute chosen for the extent. called ending. h class Romance, attribute ending draws its'values from the Example 4.12 : In general, we find it a useful convention to name classes by a 3Technically, the second and subsequent names must be "interfaces," rather than classes. Roughly, an interface in ODL is a class definition without an associated set of objects, or singular noun and name the corresponding extent by the same noun in plural. ''e~tent.~We discuss the distinction further in Section 4.3.4. Following this convention, we could call the extent for class Movie by the name CHAPTER 4. OTHER DATA MODELS DDITIONAL ODL. CONCEPTS 153

tributes forming keys. If there is more than one attribute in a key, the Interfaces of attributes must be surrounded by parentheses. The key declaration itself ears, along with the extent declaration, inside parentheses that may follow ODL provides for the definition of interfaces, which are essentially class name of the class itself in the first line of its declaration. definitions with no associated extent (and therefore, with no associated objects). We first mentioned interfaces in Section 4.3.3, where we pointed mple 4.13 : To declare that the set of two attributes title and year form y for class Movie, we could begin its declaration: out that they could support inheritanceCHAPTER by 4.one OTHER class from DATA several MODELS classes. DDITIONAL ODL. CONCEPTS 153 Interfaces also are useful if we have several classes that have different extents, but the same properties; the situation is analogous to several class Movie relations that have the same schema but different sets of . tributes(extent forming Movies keys. key If there (title, is more year)) than one attribute in a key, the If we define an interfaceInterfaces I, we can then define several classes that of attributes must be surrounded by parentheses. The key declaration itself attribute string title; inherit their properties from I. Each of those classes has a distinct extent, ears, along with. . . the extent declaration, inside parentheses that may follow ODLso provides we can formaintain the definition in our database of interfaces, several whichsets of areobjects essentially that have class the name of the class itself in the first line of its declaration. definitionssame type, with yetno belongassociated to distinct extent classes. (and therefore, with no associated could have used keys in place of key, even though only one key is declared. objects). We first mentioned interfaces in Section 4.3.3, where we pointed Similarly,mple 4.13 if name : To isdeclare a key forthat class the Star, set of then two weattributes could begin title its anddeclaration: year form out that they could support inheritance by one class from several classes. y for class Movie, we could begin its declaration: class Star InterfacesMovies. To also declare are useful this name if we for have the extent, several we classes would thatbegin have the declaration different of class(extent Movie Stars key name) extents,class Movie but theby: same properties; the situation is analogous to several relations that have the same schema but different sets of tuples. attribute(extent Movies string key name; (title, year)) If weclass define Movie an interface(extent I,Movies) we can 1 then define several classes that ... inherit their attributeproperties fromstring I. Eachtitle; of those classes has a distinct extent, attribute string title; ...... so we can maintain in our database several sets of objects that have the sameAs wetype, sliall yet see belong when to we distinct study theclasses. query language OQL that is designed for Itcould is possible have used that keys several inODL: placesets of of attributeskey, even INSTANCES arethough keys. only If so, one then key followingis declared. & KEYS querying ODL data, we refer to the extent Movies, not to the class Movie, when the Similarly,word key(s) if name we may is a placekey for several class Star,keys separated then we couldby commas. begin its As declaration: usual, a we want to examine the movies currently stored in our database. Remember key that consists of more than one attribute must have parentheses around the that the choice of a name for the extent of a class is entirely arbitrary, although list of classits attributes, Star so we can disambiguate a key of several attributes from Movies.we shallTo declare follow thethis "makename forit plural" the extent, convention we would in this begin book. the declaration0 of several• keysInstance(extent of one attribute Stars of a keyeach. class name) are all objects currently exist of that class class Movie by: CHAPTER 4. OTHER DATA MODELS ExampleDDITIONAL• 4.14In :ODL As ODL. an that example CONCEPTS is calledof a situation extent where (and it is appropriate is given toa havename)153 more• than Keys oneattribute key, are consider notstring a as class name; important Employee, whose for complete referencing set of attributes objects 4.3.5 Declaring Keys in ODL andtributes relationships forming we keys.shall not If theredescribe is morehere. than However, one attributesuppose that in a two key, of the its class Movie (extent Movies)Interfaces 1 of attributes• Because must... be surrounded each object by parentheses. already The haskey declaration a unique itself OID attribute string title; attributes are empID, the employee ID, and ssNo, the Social Security number. ODL differs from the other models studied so far in that the declaration and Thenears,• we along Definingcan declarewith the each keysextent of these declaration,in ODLattributes isinside optionalto be parentheses a key by itself that with may follow ODL provides. . for . the definition of interfaces, which are essentially class name of the class itself in the first line of its declaration. definitionsuse of keys with is optional.no associated That extentis, in the(and E/R therefore, model, withentity no sets associated need keys to objects).distinguish We membersfirst mentioned of the entity interfaces set from in Section one another. 4.3.3, whereIn the relationalwe pointed model, mple• classODL 4.13 Employee : allowsTo declare definingthat the set of multipletwo attributes keys title and(Comma year form separated) As outwewhere sliallthat relations theysee whencould are wesupport sets, study all inheritance attributesthe query together bylanguage one classform OQL from a keythat several unless is designed classes.some proper for yIt for is classpossible(extent Movie, that Employees we several could beginsetskey ofempID, its attributes declaration: ssNo) are keys. If so, then following Keywords extent & key queryingInterfacessubset ODL of the also data, attributes are we useful refer for toif a the wegiven extenthave relat.ion several Movies, can classes serve not to as that the a key. classhave Either Movie, different way, when there the wordclass key(s) Movie. . .we may place several keys separated by commas. As usual, a extents, but the same properties; the situation is analogous to several key that consists of more than one attribute must have parentheses around the we wantrelationsmust to be examine thatat least have onethe the keymovies same for schema acurrently relation. but storeddifferent in sets our ofdatabase. tuples. Remember Because there(extent are noMovies parentheses key (title,around theyear)) list of attributes, ODL interprets that theIf However,choice we define of aobjects name an interface forhave the a extentI,unique we canof object a thenclass identity, isdefine entirely severalas arbitrary,we discussedclasses although that in Sec- listthe ofabove its attributes,as saying that so eachwe can of thedisambiguate two attributes a key is aof key several by itself. attributes If we put from The key is the pair of (title, year) inherittion 4.1.3. their Consequently,properties from in I. ODL, Each the of thosedeclaration classes of has a key a distinct or keys extent, is optional. several keysattribute of one attribute string each.title; we shall follow the "make it plural" convention in this book. 0 parentheses around. . . the list (empID, ssNo) , then ODL would interpret the two soIt we is entirelycan maintain appropriate in our fordatabase there to several be several sets ofobjects objects of thata class have that the are in- attributes together as forming one key. That is, the implication of writing samedistinguishable type, yet belong by any to properties distinct classes. iecan observe; the system still keeps them Examplecould have 4.14 used : As keys an inexample place of of key, a situation even though where only it isone appropriate key is declared. to have distinct by their internal object identity. moreSimilarly, thanclass one ifEmployee name key, isconsider a key for a class Star,Employee, then wewhose could complete begin its set declaration: of attributes 4.3.5 InDeclaring ODL we may Keysdeclare onein orODL more attributes to be a key for a class by using and relationshipsclass(extent Star weEmployees shall not keydescribe (empID, here. ssNo)) However, suppose that two of its Movies.the keywordTo declare key this or namekeys for(it thedoesn't extent, matter we would which) begin followed the declarationby the attribute of attributes(extent are .empID, . . Stars the keyemployee name) ID, and ssNo, the Social Security number.The key is the pair of (empID, SSN) ODLclass differsMovie by:from the other models studied so far in that the declaration and Then we canattribute declare stringeach of thesename; attributes to be a key by itself with use of classkeys is Movie optional. (extent That Movies)is, in the 1 E/R model, entity sets need keys to ... distinguish attributemembers of stringthe entity title; set from one another. In the relational model, class Employee Two keys empID and SSN where relations are. . . sets, all attributes together form a key unless some proper (extent Employees key empID, ssNo) subsetAs we ofsliall the seeattributes when we for study a given the relat.ion query canlanguage serve OQLas a key. that Either is designed way, there for It is possible. that . . several sets of attributes are keys. If so, then following mustquerying be at ODL least data, one wekey refer for ato relation. the extent Movies, not to the class Movie, when the word key(s) we may place several keys separated by commas. As usual, a 25 we want to examine the movies currently stored in our database. Remember keyBecause that consists there are of moreno parentheses than one attributearound the must list have of attributes, parentheses ODL around interprets the thatHowever, the choice objects of a name have for a theunique extent object of a class identity, is entirely as we arbitrary, discussed although in Sec- list of its attributes, so we can disambiguate a key of several attributes from severalthe above keys as of sayingone attribute that each each. of the two attributes is a key by itself. If we put tionwe shall4.1.3. follow Consequently, the "make init ODL,plural" the convention declaration in thisof a book. key or keys0 is optional. parentheses around the list (empID, ssNo) , then ODL would interpret the two Example 4.14 : As an example of a situation where it is appropriate to have It is entirely appropriate for there to be several objects of a class that are in- attributes together as forming one key. That is, the implication of writing distinguishable by any properties iecan observe; the system still keeps them more than one key, consider a class Employee, whose complete set of attributes 4.3.5 Declaring Keys in ODL and relationships we shall not describe here. However, suppose that two of its distinct by their internal object identity. attributesclass are empID,Employee the employee ID, and ssNo, the Social Security number. ODLIn ODLdiffers we from may the declare other one models or more studied attributes so far to in be that a key the for declaration a class by usingand Then we can declare each of these attributes to be a key by itself with use of keys is optional. That is, in the E/R model, entity sets need keys to (extent Employees key (empID, ssNo)) thedistinguish keyword members key or keysof the (it entity doesn't set frommatter one which)another. followed In the relational by the attribute model, class Employee. . . where relations are sets, all attributes together form a key unless some proper (extent Employees key empID, ssNo) of the attributes for a given relat.ion can serve as a key. Either way, there . . . must be at least one key for a relation. Because there are no parentheses around the list of attributes, ODL interprets However, objects have a unique object identity, as we discussed in Sec- the above as saying that each of the two attributes is a key by itself. If we put tion 4.1.3. Consequently, in ODL, the declaration of a key or keys is optional. parentheses around the list (empID, ssNo) , then ODL would interpret the two It is entirely appropriate for there to be several objects of a class that are in- attributes together as forming one key. That is, the implication of writing distinguishable by any properties iecan observe; the system still keeps them distinct by their internal object identity. class Employee In ODL we may declare one or more attributes to be a key for a class by using (extent Employees key (empID, ssNo)) the keyword key or keys (it doesn't matter which) followed by the attribute . . . 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 428 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGUAGES 9.1. INTRODUCTION TO OQL 429

3. The keyword WHERE and a boolean-valued expression. This expression, like Arrows and Dots the expression following the SELECT, may only use as operands constants and those variables declared in the FROM clause. The comparison operators OQL allows the arrow -> as a for the dot. This convention is are like SQL's, except that ! =, rather than <>, is used for "not equal to." partly in the spirit of C, where the dot and arrow both obtain compo- The logical operators are AND, OR, and NOT, like SQL's. nents of a structure. However, in C, the arrow and dot operators have slightly different meanings; in OQL they are the same. 111 C, expression The query produces a bag of objects. We compute this bag by considering a.f expects a to be a structure, while p->f expects p to be a pointer to a all possible values of the variables in the FROM clause, in nested loops. If any structure. Both produce the value of the field f of that structure. combination of values for these variables satisfies the condition of the WHERE clause, then the object described by the SELECT clause is added to the bag that is the result of the select-from-where statement.

Example 9.2 : Here is a more complex OQL query:

If it makes sense, we can form expressions with several dots. For example, SELECT s.name if myMovie denotes a movie object, then myMovie. ownedBy denotes the Studio FROM Movies m, m.stars s object that owns the movie, and mynovie. ownedBy .name denotes the string WHERE m.title = "Casablanca" that is the name of that studio. This query asks for the names of the stars of Casablanca. Notice the sequence 426 CHAPTER 9. OBJECT-ORIENTflTIONIN QUERY LANGUAGES INTRODUCTION TO OQL OQL: EXAMPLE9.1.3 Select-From-Where QUERIES Expressions inI OQL of terms in the FROM clause. First we define m to be an arbitrary object in the class Movie, by saying m is in the extent of that class, which is Movies. Then, object-oriented host language, such as C++, Smalltalk, or Java. Objects will be manipulated both by OQL queries and by the conventional statements of the OQL permits us to write expressions using a select-from-where syntas similar for each value of m we let s be a Star object in the set m.stars of stars of host language. The ability to mix host-language statements and OQL queries . to SQL's familiar query form. Here is an example asking for the year of the movie m. That is, n-e consider in two nested loops all pairs (m, s) such that m is without explicitly transferring values428 betweenCHAPTER the two languages 9. is OBJECT-ORIENTATIONan advance IN QUERYclass Movie LANGUAGES 9.1.movie INTRODUCTION Gone IVzth the Wind. TO ReferenceOQL the extent (instance of class) 429 a movie and s a star of that movie. The evaluation can be sketched as: over the way SQL is embedded into a host language, as was discussed in Sec- (extent Movies key (title, year)) tion 8.1. C SELECT m. year attribute string title; 3. The keyword WHERE and a boolean-valued expression. This expression, like FOR each m in Movies DO Arrows and Dots theFROM expressionMovies m following the SELECT, may only use as operands constants 9.1.1 An Object-Oriented Movie Example attribute integer year; FOR each s in m.stars DO attribute integer length; andWHERE those m.title variables = "Gone declared With inthe the Wind" FROM clause. The comparison operators IF m.title = "Casablanca" THEN OQL allows the arrow -> as a synonym for the dot. This convention is In order to illustrate the dictions of OQL, we need a running example. It attribute enum Film (color,blackAndWhite> filmType; are like SQL's, except that ! =, rather than <>, is used for "not equal to." add s.name to the output bag will involve the familiar classes Movie,partly Star, in and the Studio. spirit We ofshall C, use where the the dot and arrow bothrelationship obtain Setcompo- stars XoticeSelectThe that, logical esceptthe year operatorsfor theof moviedouble-quotes are ‘Gone AND, aroundOR, with and thethe NOT, stringwind’ like constant, SQL's. this query definitions of Movie, Star, and Studionents from of Fig. a 4.3, structure. augmenting themHowever, with in C, the arrow and dot operatorsinverse have Star::starredIn; key and extent declarations. Only Movie has methods, gathered from Fig. 4.4. could be SQL rather than OQL. The WHERE clause restricts our consideration to those pairs that have m equal slightly different meanings; in OQL they are the same.relationship 111 C, expression Studio ownedBy The query produces a bag of objects. We compute this bag by considering The complete example schema is in Fig. 9.1. inverse Studio::owns; In general, the OQL select-from-where expression consists of: a.f expects a to be a structure, while p->f expects p to be a pointer to a all possible values of the variables in the FROM clause, in nested loops. If any to the Movie object whose title is Casablanca. Then, the SELECT clause produces 428 CHAPTER 9. OBJECT-ORIENTATION IN QUERYfloat lengthInHours() LANGUAGES raises(no~engthF0und); 9.1. INTRODUCTION TO OQL 429 the bag (~hichshould be a set in this case) of all the name attributes of star structure. Both produce the value of the field f of thatvoid structure. starNames(out Set); combination1. The keylvord of values SELECT for follolved these by variables a list of expressions. satisfies the condition of the WHERE 9.1.2 Path Expressions objects s in the (my s) pairs that satisfy the WHERE clause. These names are void otherMovies(in Star, out Set) - clause, then the object described by the SELECT clause is added to the bag that For each movie m, s is the set of stars in IVe access components of objects and structures using a dot notation that is raises(noSuchStar); is the3.2. The result keyrvord keyword of the FROM WHEREselect-from-where followed and aby boolean-valued a list ofstatement. one or more expression. variable declarations.This expression, like the names of the stars in the set m,. stars, where m, is the Casablanca movie similar to the dot used in C and also related to the dot used in SQL.Arrows The and Dots I; the expressionthat following movie (follow the SELECT, a relationship) may only use as operands constants object. 0 general rule is as follows. If a denotes an object belonging to class C. and p d variable is declared by giving Exampleand those 9.2 : variables Here is a declared more complex in the FROM OQL clause. query: The comparison operators is some property of the class - eitherOQL an attribute, allows relationship, the arrow or method -> as of a synonym for the dot. This convention is the class - then a.p denotes the result of "applying" p to a. That is: class Star 430 CH..IPTER 9.are(a) OBJECT-ORIENTATION like.An expressionSQL's, except whose thatvalue I,V ! has =,QUERY rathera collection LANGUAGES than type, <>, ise.g. used a set for or "notbag. equal to."9.1. IAiTRODUCTION TO OQL 43 1 partlyIf it makes in the sense, spirit we of canC, formwhere expressions the dot and with arrow several both dots. obtain For compo-example, SELECT s.name (extent Stars key name) The logical operators are AND, OR, and NOT, like SQL's. 9.1.4 Modifying the Type of the Result 1. If p is an attribute, then a.pif ismyMovienents the value of of denotes athat structure. attribute a movie in objectHowever, object, a. then in C, myMovie. the arrow ownedBy and dot denotes operators the Studiohave FROM(b) The Movies optional m, keyn-ord m.stars AS, ands object that owns the movie, and mynovie. ownedBy .name< denotes the string In the first three lines, we consider each Movie object m. If the name of the slightly different meanings; in OQL they are the same. attribute111 C, expression string name; TheWHERE(c) query The m.title nameproduces of the = a variable. "Casablanca"bag of objects. We compute this bag by considering 2. If p is a relationship, then a.p is the object or collection of objects related FROM studio that oxns this.A query movie like is "Disney," Example then 9.2 producesthe complete a hag object of strings m becomes as a result. That is, OQL thata.f is expectsthe name a toof thatbe a studio.structure, while p->f expects p toattribute be a pointer Struct to Addr a all possibleAlternative values Formof the ofvariables Lists in the FROM clause, in nested loops. If any to a by relationship p. a member of the followsoutput thebag. SQLThe default fourth ofline not specifies eliminating that theduplicates object,s inm its answer unless &- structure. Both produce the value of the field f of that structure.{string street, string city) address; combinationThisSelect queryTypically. starasks of thenames valuesfor expression the from for names these ofmovie (a)of variables theis ‘Casablanca’the stars extent satisfiesof ofCasablanca. some the class, condition Noticesuch as ofthethe the sequence WHERE relationship Set starredIn In addition to the SQL-style elements of FROM clauses, where the collection rected to do so. However, we can force the result to be a set or a list if we 3. If p is a method (perhaps 9.1.3with parameters), Select-From-Where then a.p( . .) is the result of Expressions in OQL clause,of termsextent then in Movies thethe FROMobject for clause.class described Movie First inby we thethe define example SELECT m toabove. clause be anAn is arbitrary addedextent tois objectthethe bag in that theproduced by the select-from-wherequery are to be ordered first by the value of applying p to a. inverse Movie::stars; is follo~vedclassby a nameMovie, for by a typicalsaying element,m is in theOQL extent allo~vs ofa completelythat class, which is Movies. Then,m. length (i.e., thewish. length of the movie) and then, if there are ties, by the value 1; is theanalog result ofof athe relation select-from-where in an SQL FROM statement.clause. However, it is possible to OQL permits us to write expressions using a select-from-where syntas similar equivalent, formore each logical, value yet ofless m SQL-is11 we let form.Anothers be We a Starcan notation give object the typical in the set m.stars of stars ofof m. title (i.e., the title of the movie). The value produced by this query is Example 9.1 : Let myMovie. denoteto SQL's an object familiar of type Movie. query Then: form. Here is an example asking for the year of the element name, thenuse the in keyworda variable IN, declaration and finally anythe namecollection-producing of the collection. expression, such as To make the result a set, use the keyword DISTINCT after SELECT, as in Examplemovieanother m. That 9.2 select-from-where :is, Here n-e consideris a more expression. in complex two nested OQL loops query: all pairs (m, s) such that mthus is a list of Movie objects. The value of myMovie .length movie is the Gonelength of IVzththe movie, the that Wind. is, the value class Studio For instance,a movie and s a star of that movie. The evaluation can be sketched as: SQL. of the length attribute for the IfMovie it makesobject denoted sense, by myMovie.we can form expressions with several (extentdots. StudiosFor example, key name) SELECT s.name if myMovieSELECT denotes m. year a movie object, then myMovie. ownedByC denotes the Studio FROMFOR eachmMovies IN Movies,m inm, Movies m.starss IN m.stars DO s 9.1.5 Complex Output Types The value of myMovie. lengthInHours0 is a real number, the length of attribute string name; objectFROM that Moviesowns the m movie, and mynovie. ownedBy .name denotes the string FOR each s= in m.stars DO the movie in hours, computed by applying the method 1engthInHours to attribute string address; WHERE m.title "Casablanca" The elements in the SELECT clause need not be simple variables. They can that isWHERE the name m.title of that = studio."Gone With the Wind" is an equivalent FROM clause forIF the m.title query in Example= "Casablanca" 9.2. THEN , object mynovie. relationship Set owns be any expression, including expressions built using type constructors. For inverse Movie::ownedBy; This query asks for theadd names s.name of theto thestars output of Casablanca. bag Notice the sequence The value of myMovie.starsXotice is the that, set of esceptStar objects for relatedthe double-quotes to the around the string constant, this query 28 example, we can apply the Struct type constructor to several expressions and I ; of terms in the FROM clause. First we define m to be an arbitrary object in the movie myMovie by the relationshipcould9.1.3 bestars. SQLSelect-From-Where rather than OQL. Expressions in OQL get a select-from-where query that produces a set or bag of structures. classThe Movie, WHERE by clause saying restricts m is in ourthe considerationextent of that to class, those which pairs isthat Movies. have m Then, equal Expression myMovie .starNames(myStars) OQLIn permitsgeneral, returns us the tono OQL valuewrite (LC., select-from-where expressions in C++ using expression a select-from-where consists of: syntas similar To make tothe the result Movie a list, object add an whose ORDER titleBY clause is Casablanca. at the end of Then,the query, the SELECT clause produces Figure 9.1: Part of an object-oriented inovie database for each value of m we let s be a Star object in the set m.stars of stars Exampleof 9.5: Suppose we want the set of pairs of stars living at the same the type of this expression. to is void).SQL's As familiara side effect, queryhowever, form. it sets the Here is an example asking for the year of the again as moviethein SQL. bag m. (~hichThat is,should n-e consider be a set in intwo this nested case) loops of all all the pairs name (m, attributess) such that of starm is value of the output variable mystars1. The of keylvordthe method starNamesSELECT follolvedto be a by a list of expressions. address. \ire can get this set with the query: movie Gone IVzth the Wind. aobjects movie sand in sthe a star(my s)of pairsthat movie.that satisfy The evaluation the WHERE canclause. be sketched These namesas: are set of strings; those strings are the names of the stars of the mol-ic. The following examples will illustrate the correct syntax. 2. The keyrvord FROM followed by a list of one or more variable declarations. the names of the stars in the set m,. stars, where m, is the Casablanca movie SELECT m. year SELECT DISTINCT Struct (starl : sl, star2: s2) d variable is declared by giving Example 9.3:object. Let usFOR ask 0 each for the m namesin Movies of the stars DO of Disney movies. The FROM Movies m FOR each s in m.stars DO FROM Stars sl, Stars s2 following query does the job, eliminating duplicate names in the situation where WHERE sl.address = s2.address AND s1.name < s2.name WHERE(a) .An m.title expression = "Gonewhose valueWith hasthe a Wind" collection type, e.g. a set or bag. IF m.title = "Casablanca" THEN a star appeared in several Disney movies. add s.name to the output bag Xotice (b)that, The escept optional for the keyn-ord double-quotes AS, and around the string constant, this query 9.1.4 Modifying the Type of the Result That is, 1%-econsider all pairs of stars, sl and s2. The WHERE clause checks SELECT DISTINCT s.name could be(c) SQL The rather name thanof the OQL. variable. .A query like Example 9.2 produces a hag of strings as a result. That is, OQLthat they have the same address. It also checks that the name of the first star FROM MoviesThe m, WHEREm.stars clause s restricts our consideration to those pairs that have m equal In general, the OQL select-from-where expression consists of: followsto the Movie the SQL object default whose of title not is eliminating Casablanca. duplicates Then, the inSELECT its answer clause unless produces &-p~ecedes the name of the second in alphabetic order, so ~3-edon't produce pairs Typically. the expression of (a) is the extent of some class, such as the WHERE m. ownedBy. name = "Disney" therected bag to (~hich do so.should However, be a weset canin this force case) the ofresult all theto namebe a setattributes or a list of if star weconsisting of the same star t~viceand we don't produce the same pair of stars 1. The keylvord SELECT follolved by a list of expressions. extent Movies for class Movie in the example above. An extent is the objectswish. s in the (my s) pairs that satisfy the WHERE clause. These names arein two different orders. analog of a relation in an SQL FROM clause. However, it is possible to The strategy of this query is similar to that of Example 9.2. We again 2. The keyrvord FROM followed by a list of one or more variable declarations. consider all pairsthe of names a movie of and the a starsstar of inthat the movie set m,.in two stars, nested whereloops as m, in is the Casablanca movie For every pair that passes the t~otests, we produce a record structure. The use in a variable declaration any collection-producing expression, such as To make the result a set, use the keyword DISTINCT after SELECT, as in d variable is declared by giving object. 0 type of this structure is a record with two fields, named starl and star2. The another select-from-where expression. Example 9.2. But now;SQL. the condition on that pair (m, s) is that "Disney" is the name of the studio whose Studio object is m. ownedBy. type of each field is the class Star. since that is the type of the variables sl (a) .An expression whose value has a collection type, e.g. a set or bag. and s2 that provide values for the two fields. That is. formally, the type of the (b) The optional keyn-ord AS, and The ORDER 9.1.4BY clause inModifying OQL is quite similarthe Type to the same of theclause Resultin SQL. structure is Keywords are followed by a list of expressions. The first of these (c) The name of the variable. .A query like Example 9.2 produces a hag of strings as a result. That is, OQL expressions is evaluated for each object in the result of the query, and objects Struct(star1: Star, star2: star) follows the SQL default of not eliminating duplicates in its answer unless &- Typically. the expression of (a) is the extent of some class, such as the are ordered by this value. Ties, if any, are broken by the value of the second expression. thenrected the third, to do and so. so on.However, By default, we thecan order force is ascending.the result but to be a set or a list if weThe type of the result of the query is a set of these structures, that is: extent Movies for class Movie in the example above. An extent is the wish. analog of a relation in an SQL FROM clause. However, it is possible to a choice of ascending or descending order can be indicated by the keyword ASC Set use in a variable declaration any collection-producing expression, such as or DESC, respectively. Tofollowing make an the attribute. result aas set, in SQL. use the keyword DISTINCT after SELECT, as in another select-from-where expression. SQL. Example 9.4 : Let us find the set of Disney movies, but let the result be a list of movies. ordered by length. If there are ties, let the movies of equal length be ordered alphabetically. The query is: 9.1.6 Subqueries SELECT m FROM Movies m Ure can use a select-from-whereexpression anywhere a collection is appropriate. WHERE m.ownedBy.name = "Disney" \Ye shall give one example: in the FROM clause. Sereral other examples of ORDER BY m.length, m.title subquery use appear in Section 9.2. -

430 CH..IPTER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES 9.1. IAiTRODUCTION TO OQL 43 1

In the first three lines, we consider each Movie object m. If the name of the Alternative Form of FROM Lists studio that oxns this movie is "Disney," then the complete object m becomes - 9.1. INTRODUCTION TO OQL 433 432 CHAPTER 9. OBJECT- ORIENTATION IN QUERY LANGUAGES a member of the output bag. The fourth line specifies that the object,s m In addition to the SQL-style elements of FROM clauses, where the collection produced by the select-from-wherequery are to be ordered first by the value of 9.1.7 Exercises for Section 9.1 is follo~vedby a name for a typical element, OQL allo~vsa completely m. length (i.e., the length of the movie) and then, if there are ties, by the value SELECT Lists of Length One Are Special equivalent, more logical, yet less SQL-is11 form. We can give the typical of m. titleExercise (i.e., the 9.1.1: title In of Fig. the 9.2 movie).is an ODL Thedescription value of producedour running productsby this query is 9.1. IAiTRODUCTION TO OQLexercise. \Ire have made each of the three types of products43 1 subclasses of the 430 elementCH..IPTER name, 9. thenOBJECT-ORIENTATION the keyword IN, andNotice I,V finally QUERY that thewhen LANGUAGES name a SELECT of thelist has collection. only a single expression, the type of thus a list of Movie objects. main Product class. The reader should observe that a type of a product can For instance, the result is a collection of values of the type of that expression. However: be obtained either from the attribute type or from the subclass to ~hichit if we have more than one expression in the SELECT list, there is an implicit In the first three lines, we considerbelongs. each This Movie arrangement object ism. not Ifan the excellent name design, of the since it allows for the FROM m IN Movies, stuctures IN formed m.stars with components for each expression. Thus, even had we 9.1.5 Complex Output Types possibility that, say, a PC object will haye its type attribute equal to "laptop" Alternative Form of FROMstarted Lists the query of Example 9.5 with studio that oxns this movie is "Disney," then the complete object m becomes The elementsor "printer". in the SELECT However, clause the arrangement need not gives beyou simplesome interesting variables. options They can is an equivalent FROM clause for the query in Example 9.2. a member of the output bag. The fourth line specifies that the object,s m For In addition to the SQL-style elements of FROM clauses, whereSELECT the collection DISTINCT starl: sl, star2: s2 be any expression,regarding how including one expresses expressions queries. built using type constructors. produced by the select-from-whereexample, we canBecausequery apply typeare the tois inheritedbe Struct ordered by Printertype first constructorby from the the value superclass ofto several Product, expressionswe have and is follo~vedby a name for a typical element, OQL allo~vsa completely the type of the result would be m. length (i.e., theget length a select-from-where of thehad movie) to rename and thethen, query type if attributetherethat producesare of ties,Printer by a theto set be value printerType.or bag of structures. The latter equivalent, more logical, yet less SQL-is11 form. We can give the typical attribute gives the process used by the printer (e.g., laser or inkjet), while type To make the result a list, add an ORDER BY clause at the end of the query, of m. title (i.e., the title of the movie). The value produced by this query is Set of Product will have values such as PC, laptop, or printer. elementagain name, as then in SQL.the keyword IN, and finally the name of the collection. thus a list of MovieExample objects. 9.5: Suppose we want the set of pairs of stars living at the same address. \ire canAdd getto the this ODL set code with of Fig.the 9.2query: method signatures (see Section 1.2.7) For instance, Honrever, in Example 9.3, the type of the result is Set, not appropriate for functions that do the following: The following examples will illustrate the Set. FROM m IN Movies, s IN m.stars 9.1.5 Complex OutputSELECT* a) TypesDISTINCT Subtract x from Struct the price (starl of a product. : sl, Assume star2: x is provided s2) as an input Example 9.3: Let us ask for the names of the stars of Disney movies. The FROM Starsparameter sl, ofStars the function. s2 following query does the job, eliminating duplicate names in the situation where The elements in the SELECT clause need not be simple variables. They can is an equivalent FROM clause for the query in Example 9.2. WHERE sl.address = s2.address AND s1.name < s2.name a star appeared in several Disney movies. In the FROM clause, we may use a subquery to form a collection.be We any then expression, including expressions* b) Return thebuilt speed using of a producttype constructors. if the product is Fora PC or laptop and raise allow a variable representing a typical element of that collection to range over the exception notcomputer if not. example, we can applyThat the is, Struct1%-econsider type constructor all pairs toof severalstars, expressionssl and s2. and The WHERE clause checks SELECT DISTINCT s.name each member of the collection. that they havec) Setthe the same screen address. size of a laptop It also to a checksspecified inputthat valuethe x.name of the first star FROM Movies m, m.stars s get a select-from-where query that produces a set or bag of structures. Example 9.6 : Let us redo the query of Example 9.3, which asked for the stars p~ecedesthe name of the second in alphabetic order, so ~3-edon't produce pairs To makeWHERE the m. result ownedBy. a list, add name an =ORDER "Disney" BY clause at the end of the query, ! d) Given an input product p, determine whether the product q to which the of the movies made by Disney. First, the set of Disney movies could beExample obtained 9.5: Supposeconsisting we wantof the themethod same set isof starapplied pairs t~vice hasof starsa higherand living wespeed don't atand the a lower produce same price thanthe p.same Raise pairthe of stars again as in SQL. by the query, as was used in Example 9.4. The strategy of this query is similar to that of Example 9.2. We again address. \ire can getin twothis setdifferent with theexception orders. query: badInput if p is not a product with a speed (i.e., neither a PC SELECT m For every pairnor thatlaptop) passes and the the exception t~o tests,nospeed we if q produceis not a product a record with a structure.speed. The 426 CHAPTER 9. OBJECT-ORIENTflTIONIN QUERY LANGUAGES INTRODUCTION TO OQL Theconsider following all examples pairs of will a movieillustrate and the a correctstar of syntax. that movie in two nested loops as in OQL: EXAMPLEExample 9.2. But now; QUERIES the condition on thatFROM pair Movies (m, s)II m is that "Disney" is the SELECT DISTINCTtype of Struct thisExercise structure (starl 9.1.2 : sl, is: a Using star2:record the ODLwiths2) schema two fields,of Exercise named 9.1.1 andstarl Fig. 9.2, and write star2. The Example 9.3: Let us ask for the names of the starsWHERE of Disney m.ownedBy.name movies. =The "Disney" type of each field is the class Star. since that is the type of the variables sl object-oriented host language, such as C++, Smalltalk, or Java. Objects will name of the studio whose Studio object is m. ownedBy. FROM Stars sl, Stars thes2 follo~ving queries in OQL: be manipulated both by OQL queries and by the conventional statements of the following query does the job, eliminating duplicateWe names can now in usethe this situation query as wherea subquery to define the set over which a variableWHERE sl.addressand s2 =that s2.address provide valuesAND s1.name for the 430 CH..IPTER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES 9.1.orThe DESC,IAiTRODUCTION strategy respectively. of this query followingTO is OQL similar an toattribute. that of Exampleas in SQL. 9.2. We again 43 1 in two different orders. In order to illustrate the dictions of OQL, we need a running example. It attribute enum Film (color,blackAndWhite> filmType; Select distinct star names in moviesThis expression owned of the queryby ‘Disney’ "Find the stars of Disney movies" is no Inore d) Find tlle set of pairs (r.h) such that some PC or laptop has r megabytes will involve the familiar classes Movie, Star, and Studio. We shall use the relationship Set stars considerExample all pairs 9.4 of :a Letmovie us andfind a thestar set of thatof Disney moviesuccinct inmovies, thantwo nestedthat but of Exampleloopslet the as 9.3.resultin and beperhaps a list less so. However, itFor does every pair that passes the t~oof tests,RAM andwe hproduce gigabytes a ofrecord hard disk. structure. The definitions of Movie, Star, and Studio from Fig. 4.3, augmenting them with inverse Star::starredIn; ExampleInof the movies. first9.2. But threeordered now; lines, theby weconditionlength. consider If on there eachthat pairareMovieillustrate ties,(m, s)object let isa newthat the m.form "Disney"movies Ifof buildingthe of isname equalthe queries of length availablethe be in OQL. In the querytype above. of this structure is a record with two fields, named starl and star2. The key and extent declarations. Only Movie has methods, gathered from Fig. 4.4. e) Create a list of the PC's (objects, not model numbers) in ascending order of FROMrelationship Studio ownedBy namestudioordered of thethat alphabetically.studio oxns whose this movie Studio The is object "Disney,"query is is: m. thenownedBy.the theFROM completeclause has two object nested m loops. becomes In the first, the variable d rangestype overof each field is the class Star. since that is the type of the variables sl The complete example schema is in Fig. 9.1. Alternative Form Lists inverse Studio::owns; subquery of processor speed. a member of the output bag. The fourth allline Disney specifies movies, the that result the of theobject,s subquery m in the FROM clause. In theand second s2 that provide9.1.6 values forSubqueries the two fields. That is. formally, the type of the float lengthInHours() raises(no~engthF0und); SELECT m loop, nested within the first, the variable s ranges over all stars of the Disney ! f) Create a list of the model numbers of tlle laptops n-ith at least 64 xnega- In addition to the SQL-style elements of FROM clauses,void starNames(outwhere the collection Set); producedThe ORDER by BYthe clause select-from-where in OQL is quitequery similar are to to bethe ordered same clause first inby SQL.the value of structure is 9.1.2 Path Expressions FROM Movies m ' lnovie d. Sotice that no WHERE clause is needed in the outer query. bytes of R.411: in descending order of screen size. is follo~vedby a name for a typical element, OQL allo~vsa completely Keywords ORDER BY are followed by a list of expressions. The first of these Ure can use a select-from-whereexpression anywhere a collection is appropriate. void otherMovies(in Star, out Set) m. lengthWHERE (i.e., m.ownedBy.namethe length of the movie) = "Disney" and then, if there are ties, by the value \Ye shall give one example: in the FROM clause. Sereral other examples of IVe access components of objects and structures using aequivalent, dot notation more that islogical, yet less SQL-is11 form. We can giveraises(noSuchStar); the typical expressionsof m. title is evaluated (i.e., the fortitle each of theobject movie). in the The result value of the produced query, and by objects this query is Struct(star1: Star, star2: star) ORDER BY m.length, m.title subquery use appear in Section 9.2. similar to the dot used in C and also related to the dotelement used in name, SQL. thenThe the keyword IN, and finallyI; the name of the collection. arethus ordered a list by of thisMovie value. objects. Ties, if any, are broken by the value of the second general rule is as follows. If a denotes an object belongingFor toinstance, class C. and p The type of the result of the query is a set of these structures, that is: is some property of the class - either an attribute, relationship, or method of expression.order then themovies third, andowned so on. by By ‘Disney’default, the based order is on ascending. length but and title the class - then a.p denotes the result of "applying" p to a. That is: class Star a choice of ascending or descending order can be indicated by the keyword ASC FROM m IN Movies, s IN m.stars 9.1.5 Complex Output Types (extent Stars key name) or DESC, respectively. following an attribute. as in SQL. Set 1. If p is an attribute, then a.p is the value of that attribute in object a. < The elements in the SELECT clause need not be simple variables. They can is an equivalent FROM clause for the query in Exampleattribute 9.2. string name; : 2. If p is a relationship, then a.p is the object or collection of objects related Examplebe any expression,9.4 Let us find including the set expressions of Disney movies, built but using let thetype result constructors. be a list For attribute Struct Addr to a by relationship p. ofexample, movies. ordered we Reportcan by apply length. set the ofIf Struct therestructures are type ties, constructor let the movies to of several equal lengthexpressions be and {string street, string city) address; orderedget a select-from-wherealphabetically. The queryquery thatis: produces a set or bag of structures. 3. If p is a method (perhaps with parameters), then a.p( . .) is the result of relationship Set starredIn To make the result a list, add an ORDER BY clause at the end inverseof the query, Movie::stars; 9.1.6 Subqueries applying p to a. SELECT m again as in SQL. 1; Example 9.5: Suppose we want the set of pairs of stars living at the same Example 9.1 : Let myMovie denote an object of type Movie. Then: address.FROM \ireMovies can mget this set with the query: Join two classes Ure can use a select-from-whereexpression anywhere a collection is appropriate. The following examples will illustrate the correct syntax. WHERE m.ownedBy.name = "Disney" \Ye shall give one example: in the FROM clause. Sereral other examples of The value of myMovie .length is the length of the movie, that is, the value class Studio ORDERSELECT BY m.length,DISTINCT m.titleStruct (starl : sl, star2: s2) subquery use appear in Section 9.2. of the length attribute for the Movie object denotedExample by myMovie. 9.3: Let us ask for the names of the stars(extent of Disney Studios movies. key name) The FROM Stars sl, Stars s2 following query does the job, eliminating duplicateC names in the situation where The value of myMovie. lengthInHours0 is a real number, the length of WHERE sl.address = s2.address AND s1.name < s2.name a star appeared in several Disney movies. attribute string name; the movie in hours, computed by applying the method 1engthInHours to attribute string address; , object mynovie. That is, 1%-econsider all pairs of stars, sl and s2. The WHERE clause checks SELECT DISTINCT s.name relationship Set owns Report pairs of stats who have the same address inverse Movie::ownedBy; that they have the same address. It also checks that the name of the first star The value of myMovie.stars is the set of Star objectsFROM related Movies to the m, m.stars s 29 I ; p~ecedesthe name of the second in alphabetic order, so ~3-edon't produce pairs movie myMovie by the relationship stars. WHERE m. ownedBy. name = "Disney" consisting of the same star t~viceand we don't produce the same pair of stars Expression myMovie .starNames(myStars) returns no value (LC., in C++ The strategy of this query is similar to that of ExampleFigure 9.1: 9.2.Part ofWe an againobject-oriented inovie database in two different orders. the type of this expression is void). As a side effect, however, it sets the For every pair that passes the t~otests, we produce a record structure. The value of the output variable mystars of the methodconsider starNames all pairs to ofbe aa movie and a star of that movie in two nested loops as in set of strings; those strings are the names of theExample stars of the 9.2. mol-ic. But now; the condition on that pair (m, s) is that "Disney" is the type of this structure is a record with two fields, named starl and star2. The name of the studio whose Studio object is m. ownedBy. type of each field is the class Star. since that is the type of the variables sl and s2 that provide values for the two fields. That is. formally, the type of the The ORDER BY clause in OQL is quite similar to the same clause in SQL. structure is Keywords ORDER BY are followed by a list of expressions. The first of these expressions is evaluated for each object in the result of the query, and objects Struct(star1: Star, star2: star) are ordered by this value. Ties, if any, are broken by the value of the second expression. then 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: a choice of ascending or descending order can be indicated by the keyword ASC or DESC, respectively. following an attribute. as in SQL. Set

Example 9.4 : Let us find the set of Disney movies, but let the result be a list of movies. ordered by length. If there are ties, let the movies of equal length be ordered alphabetically. The query is: 9.1.6 Subqueries SELECT m FROM Movies m Ure can use a select-from-whereexpression anywhere a collection is appropriate. WHERE m.ownedBy.name = "Disney" \Ye shall give one example: in the FROM clause. Sereral other examples of ORDER BY m.length, m.title subquery use appear in Section 9.2. -

430 CH..IPTER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES 9.1. IAiTRODUCTION TO OQL 43 1

In the first three lines, we consider each Movie object m. If the name of the Alternative Form of FROM Lists studio that oxns this movie is "Disney," then the complete object m becomes

- a member of the output bag. The fourth line specifies that the object,s m In addition to the SQL-style elements of FROM clauses, where the collection produced by the select-from-wherequery are to be ordered first by the value of is follo~vedby a name for a typical element, OQL allo~vsa completely m. length (i.e., the length of the movie) and then, if there are ties, by the value equivalent, more logical, yet less SQL-is11 form. We can give the typical of m. title (i.e., the title of the movie). The value produced by this query is 430element CH..IPTER name, then 9. the OBJECT-ORIENTATION keyword IN, and finally the I,V name QUERY of the LANGUAGES collection. thus9.1. aIAiTRODUCTION list of Movie objects. TO OQL 43 1 For instance,

FROM m IN Movies, s IN m.stars In9.1.5 the firstComplex three lines, Output we consider Types each Movie object m. If the name of the Alternative Form of FROM Lists studioThe elements that oxns in thisthe SELECTmovie is clause"Disney," need then not the be complete simple variables. object m Theybecomes can is an equivalent FROM clause for the query in Example 9.2. abe member any expression, of the output including bag. expressionsThe fourth built line using specifies type that constructors. the object,s Form - In addition to the SQL-style elements of FROM clauses, where the collection producedexample, weby thecan select-from-whereapply the Structquery type constructorare to be ordered to several first expressionsby the value and of is follo~vedby a name for a typical element, OQL allo~vsa completely m.get length a select-from-where (i.e., the length query of the that movie) produces and then, a set if or there bag areof structures. ties, by the value equivalent,To make the more result logical, a list, yet add less an SQL-is11 ORDER BY form. clause We at can the giveend ofthe the typical query, of m. title (i.e., the title of the movie). The value produced by this query is Example 9.5: Suppose we want the set of pairs of stars living at the same 430 CH..IPTER 9. OBJECT-ORIENTATIONelementagain as name, in SQL. then the I,Vkeyword QUERY IN, LANGUAGES and finally the name of the collection.9.1. IAiTRODUCTION TO OQLthus a list of Movie objects. 43 1 For instance, address. \ire can get this set with the query: The following examples will illustrate the correct syntax. In the first three lines, we consider eachSELECT Movie objectDISTINCT m. IfStruct the name (starl of the : sl, star2: s2) FROM m IN Movies, s IN m.stars 9.1.5 Complex Output Types AlternativeExample 9.3: Form Let ofus FROMask for Lists the names of OQLthe stars of Disney OUTPUT movies. Thestudio that oxns this movie is "Disney,"FROM then Starsthe complete sl, Stars object s2m becomes following query does the job, eliminating duplicate names in the situation wherea member of the output bag. The fourthelementsWHERE line sl.address in specifies the SELECT that = the s2.addressclause object,s need m notAND bes1.name simple < variables. s2.name They can In addition to the SQL-stylea staris appearedan elements equivalent in of several FROM FROM clauses, clauseDisney where for movies. the the query collection in Example 9.2. produced by the select-from-wherebequery any areexpression, to be ordered including first by expressions the value of built using type constructors. For is follo~vedby a name for a typical element, OQL allo~vsa completely m. length (i.e., the length of the movie)That is,and 1%-e then,consider if there all are pairs ties, byof thestars, value sl and s2. The WHERE clause checks SELECT DISTINCT s.name example, we can apply the Struct type constructor to several expressions and equivalent, more logical, yet less SQL-is11 form. We can give the typical of m. title (i.e., the title of the thatmovie). they The have value the produced same address. by this Itquery also ischecks that the name of the first star FROM Movies m, m.stars s get a select-from-where query that produces a set or bag of structures. element name, then the keyword IN, and finally the name of the collection. thus a list of Movie objects. p~ecedesthe name of the second in alphabetic order, so ~3-edon't produce pairs For instance, WHERETo make m. ownedBy. the result name a list, = add "Disney" an ORDER BY clause at the end of the query, • Unlike SQL which produces relations, OQLconsistingExample produces of9.5: the Supposesame star we t~vice want and the weset don'tof pairs produce of stars the living same at pair the of same stars Theagain strategy as in of SQL. this query is similar to that of Example 9.2. We again9.1.5 in two different orders. - FROM m IN Movies, s IN m.stars Complex Output address.Types \ire can get this set with the query: consider all pairs of a movie and a star of that movie in two nested loops as in For every pair that passes the t~otests, we produce a record structure. The The following examples will illustrate the correct syntax. The elements in the SELECT clause need not be simple variables. They can Example 9.2.collection But now; the condition (set, on that pairbag, (m, s) is thatlist) "Disney" of isobjects the type of this structure is a record with two fields, named starl and star2. The is an equivalent FROM clause for the query in Example 9.2. be any expression, including expressionsSELECT built usingDISTINCT type Structconstructors. (starl For : sl, star2: s2) name of the studio whose Studio object is m. ownedBy. type of each field is the class Star. since that is the type of the variables sl Example 9.3: Let us ask for the names of the stars of Disney movies. Theexample, we can apply the Struct typeFROM constructor Stars to sl, several Stars expressions s2 and 430 CH..IPTER 9. OBJECT-ORIENTATION I,V QUERY LANGUAGES 9.1.following IAiTRODUCTION •query The does theobject TO job, OQL eliminating can duplicate be namesof any in the situation type43 where 1 and s2 that provide values for the two fields. That is. formally, the type of the The ORDER BY clause in OQL is quite similar to the same clause in SQL.get a select-from-where query thatstructure producesWHERE is a setsl.address or bag of structures.= s2.address AND s1.name < s2.name To make the resultKeywordsa astar list, appeared add ORDER an ORDER inBY several areBY clausefollowed Disney at the by movies. end a listof the of query,expressions. The first of these again as in SQL.Inexpressions the first threeis evaluated lines, we for consider each object each Movie in the object result m.of theIf the query, name and of objectsthe Example 9.5: Suppose we wantThat the is,setStruct(star1: 1%-eof pairsconsider of stars allStar, pairsliving star2: ofat stars,the samestar) sl and s2. The WHERE clause checks Alternative Form of FROM Lists studioare ordered thatSELECT oxns by thisDISTINCT this value. movie s.nameis Ties, "Disney," if any, then are thebroken complete by the object value m of becomes the second address. \ire can get this set with the query: The following examples will illustrate the correct syntax. that they have the same address. It also checks that the name of the first star aexpression. memberFROM of then Moviesthe theoutput third,m, bag.m.stars and The so son.fourth By linedefault, specifies the orderthat Set theis ascending. ofobject,s strings m but The type of the result of the query is a set of these structures, that is: SELECT DISTINCT Struct p~ecedes(starl : sl,the star2:name of s2) the second in alphabetic order, so ~3-edon't produce pairs In addition to the SQL-style elements of FROM clauses, where the collection Example 9.3: Let usproduceda choiceask forWHERE of theby ascending the namesm. select-from-where ownedBy. of orthe descending stars name of =query Disney "Disney" order are movies. can to bebe Theordered indicated first by by the the keyword value of ASC is follo~vedby a name for a typical element, OQL allo~vsa completely FROM Stars sl, Stars s2consisting Set produce the same pair of stars following query does them.or lengthjob,DESC, eliminating respectively. (i.e., the duplicate length following of names the movie) an in theattribute. andsituation then, as where ifin there SQL. are ties, by the value WHERE sl.address = s2.addressin two different AND s1.name orders. < s2.name equivalent, more logical, yet less SQL-is11 form. We can give the typical a star appeared in severalof m. Disney titleThe strategy movies.(i.e., the of title this of querythe movie). is similar The tovalue that produced of Example by this 9.2. query We isagain Example 9.4 : Let us find the set of Disney movies, but let the result be a list For every pair that passes the t~otests, we produce a record structure. The element name, then the keyword IN, and finally the name of the collection. thusconsider a list allof Moviepairs ofobjects. a movie and a star of that movie in two nested loops asThat in is, 1%-econsider all pairs of stars, sl and s2. The WHERE clause checks SELECT DISTINCTof movies.s.name ordered by length. If there are ties, let the movies of equal length be type of this structure is a record with two fields, named starl and star2. The For instance, Example 9.2. But now; the condition on that pair (m, s) is that "Disney" is thethat they have the same address. It also checks that the name of the first star FROM Movies m,ordered m.stars alphabetically. s The query is: name of the studio whose Studio object is m. ownedBy. p~ecedesthe name of the second typein alphabetic of each order,field isso the~3-e don'tclass produceStar. since pairs that is the type of the variables sl WHERE m. ownedBy.9.1.5 name =Complex "Disney" Output Types 9.1.6 Subqueries FROM m IN Movies, s IN m.stars SELECT m consisting of the same star t~viceandand s2we thatdon't provide produce values the same for thepair two of stars fields. That is. formally, the type of the The ORDER BY clause in OQL is quite similar to the same clause in SQL. The strategy of thisThe query elementsFROM is Moviessimilar in the to mSELECT that of clauseExample need 9.2. not We be again simple variables. They can in two different orders. Urestructure can use is a select-from-whereexpression anywhere a collection is appropriate. is an equivalent FROM clause for the query in Example 9.2. consider all pairs of a bemovieKeywords anyWHERE and expression, a ORDERstarm.ownedBy.name of thatBY including are movie followed expressions in = two "Disney" bynested a builtlist loops of using asexpressions. in type constructors. SetThe of first objects ofFor these of For type every Movie pair that passes the\Ye t~o shalltests, wegive produce one example: a record structure.in the FROM The clause. Sereral other examples of Example 9.2. But now;example, expressionsthe conditionORDER we can BYis on evaluated m.length,apply that pairthe forStruct(m, m.title s)each is typethat object "Disney"constructor in the is result the to several of the expressions query, and andobjects type of this structure is a record subquerywith twoStruct(star1: fields, use appearnamed starlinStar, Section and star2: star2. 9.2. star)The name of the studio whosegetare aStudio orderedselect-from-where object by this is m. value. ownedBy. query Ties,that producesif any, are a setbroken or bag by of the structures. value of the secondtype of each field is the class Star. since that is the type of the variables sl expression. then the third, and so on. By default, the order is ascending. butand s2 that provide values for theThe two type fields. of Thatthe result is. formally, of the thequery type is ofa theset of these structures, that is: To make the result a list, add an ORDER BY clause at the end of the query, The ORDER BY clause in OQL is quite similar to the same clause in SQL. Examplea choice of 9.5: ascending Suppose or wedescending want the orderset of canpairs be of indicated stars living by theat thekeyword same ASCstructure is again as in SQL. Keywords ORDER BY are followed by a list of expressions. The first of these address.or DESC, \ire respectively. can get this following set with thean attribute.query: as in SQL. Set The following examples will illustrate the correct syntax. expressions is evaluated for each object in the result of the query, and objects Struct(star1: Star, star2: star) are ordered by this value. Ties, if any, are broken by the value of the second ExampleSELECT 9.4 DISTINCT : Let us Structfind the (starl set of :Disney sl, star2: movies, s2) but let the result be a list expression. then 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: Example 9.3: Let us ask for the names of the stars of Disney movies. The FROM Stars sl, Stars s2 Set of structures a choice of ascending orof descending movies. ordered order can by belength. indicated If there by the are keyword ties, let ASC the movies of equal length be following query does the job, eliminating duplicate names in the situation where orderedWHERE alphabetically. sl.address The= s2.address query is: AND s1.name < s2.name Set a star appeared in several Disney movies. or DESC, respectively. following an attribute. as in SQL. 9.1.6 Subqueries 30 Example 9.4 : Let usThat find theis,SELECT 1%-eset ofconsider Disneym allmovies, pairs butof stars,let the slresult and be s2. a list The WHERE clause checks SELECT DISTINCT s.name of movies. ordered by length.that they FROMIf therehave Movies arethe ties,same m let address. the movies It also of equal checks length that be the name of the first star FROM Movies m, m.stars s Ure can use a select-from-whereexpression anywhere a collection is appropriate. ordered alphabetically.p~ecedes The queryWHEREthe is: name m.ownedBy.name of the second in= alphabetic"Disney" order, so ~3-edon't produce pairs \Ye shall give one example: in the FROM clause. Sereral other examples of WHERE m. ownedBy. name = "Disney" consisting of the same star t~viceand we don't produce the same pair of stars 9.1.6 Subqueries SELECT m ORDER BY m.length, m.title subquery use appear in Section 9.2. in two different orders. The strategy of this query is similar to that of Example 9.2. We again FROM Movies m Ure can use a select-from-whereexpression anywhere a collection is appropriate. consider all pairs of a movie and a star of that movie in two nested loops as in WHERE m.ownedBy.nameFor every = "Disney" pair that passes the t~otests, we produce a record structure. The \Ye shall give one example: in the FROM clause. Sereral other examples of Example 9.2. But now; the condition on that pair (m, s) is that "Disney" is the ORDER BY m.length,type ofm.title this structure is a record with two fields, named starl and star2. The subquery use appear in Section 9.2. name of the studio whose Studio object is m. ownedBy. type of each field is the class Star. since that is the type of the variables sl and s2 that provide values for the two fields. That is. formally, the type of the The ORDER BY clause in OQL is quite similar to the same clause in SQL. structure is Keywords ORDER BY are followed by a list of expressions. The first of these expressions is evaluated for each object in the result of the query, and objects Struct(star1: Star, star2: star) are ordered by this value. Ties, if any, are broken by the value of the second expression. then 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: a choice of ascending or descending order can be indicated by the keyword ASC or DESC, respectively. following an attribute. as in SQL. Set

Example 9.4 : Let us find the set of Disney movies, but let the result be a list of movies. ordered by length. If there are ties, let the movies of equal length be ordered alphabetically. The query is: 9.1.6 Subqueries SELECT m FROM Movies m Ure can use a select-from-whereexpression anywhere a collection is appropriate. WHERE m.ownedBy.name = "Disney" \Ye shall give one example: in the FROM clause. Sereral other examples of ORDER BY m.length, m.title subquery use appear in Section 9.2. 440 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXG UAGES 9.2. ADDITIONAL FORMS OF OQL EXPRESSIONS in our general discussion. In the GROUP BY clause are two fields stdo and yr. 1. All variables xl, xz,.. . ,xk may be used in the expressions el, e2, . . . ,en corresponding to the expressions m. ownedBy .name and m. year, respectively. of the GROUP BY clause. For instance, Pretty Woman is a movie made by Disney in 1990. [Vhen nl is the object for this movie, the value of m. ownedBy. name is "Disney" and the 2. Structures in the bag that is the value of the field have fields value of m. year is 1990. As a result, the intermediate collection has, as one named xl, 22,. . . , xk. member, the structure: 3. Suppose il, iz, . . . :ik are values for variables xi, x2,. . . ,xk, respectively, Struct (stdo: "Disney", yr: 1990, partition:P) that niake the WHERE clause true. Then there is a structure in the inter- mediate collection of the form Here, P is a set of structures. It contains, for example,

Struct (m: mpw) and in bag P is the structure: where mPWis the Movie object for Pretty Woman. Also in P are one-component structures with field name m for every other Disney movie of 1990. Struct(xl : il x2 :iZ, xk :ik) Now, let us examine the SELECT clause. For each structure in the intermedi- , . . . , ate collection, we build one structure that is in the output collection. The first component of each output structure is stdo. That is, the field name is stdo 9.2.4 HAVING Clauses and its value is the value of the stdo field of the corresponding structure in the A GROUP BY clause of OQL may be followed by a HAVING clause, with a meaning intermediate collection. Similarly, the second component of the result has ficltl like that of SQL's HAVING clause. That is, a clause of the form name yr and a value equal to the yr con~ponentof the intermediate collection. The third component of each structure in the output is HAVING

SUM(SELECT p.m.length FROM partition p) serves to eliminate some of the groups created by the GROUP BY. The condition applies to the value of the partition field of each structure in the intermedi- To understand this select-from expression we first realize that variable p rangcs ate collection. If true, then this structure is processed as in Section 9.2.3, to over the members of the partition field of the structure in the GROUP BY form a structure of the output collection. If false, then this structure does not result. Each dueof p, recall, is a structure of the form Struct (m: o),t+-here o contribute to the output collection. 426 CHAPTER 9. OBJECT-ORIENTflTIONis IN a movieQUERY object. LANGUAGES The expression p.m therefore refersINTRODUCTION to this object TO OQLo. Thus. p.m. length refers to the length component of this Movie object OQL: AGGREGATIONExample 9.11 : Let us repeat Example 9.10, but ask for the sum of the lengths object-oriented host language, such as C++, Smalltalk,.is ora result,Java. Objects the select-from will query produces the bag of lengths of the movies of movies for only those studios and years such that the studio produced at lewt be manipulated both by OQL queries and by the conventionalin a particular statements group. of theFor instance, if stdo has the value "Disney" and yr has one movie of over 120 minutes. The query of Fig. 9.7 does the job. Notice that host language. The ability to mix host-language thestatements value 1990,and OQL then queries the result of the select-from is the bag of the lengths of the in the HAVING clause we used the same query as in the SELECT clause to obtain without explicitly transferring values between themovies two languages made isby an Disney advance in 1990. When we apply theclass SUM Movie operator to this bag the bag of le~lgtlisof movies for a given studio and year. In the HAVING clause, over the way SQL is embedded into a host language,we get as wasthe discussed sum of inthe Sec- lengths of the movies in the group.(extent Thus, Movies one key member (title, year)) tve take the maximum of those lengthsAggregate and compare over it tothe 120. partition tion 8.1. of the output collection might be C attribute string title; 9.1.1 An Object-Oriented Movie Example attribute integer year; attribute integer length; SELECT stdo, yr, sumlength: SUM(SELECT p.m.length In order to illustrate the dictions of OQL, we ifneed 123-1 a running is the correctexample. totalIt length of all the Disney moviesattribute of 1990. enum Film (color,blackAndWhite> filmType; FROM partition p) will involve the familiar classes Movie, Star, and Studio. We shall use the relationship Set stars FROM Movies m definitions of Movie, Star, and Studio from Fig. 4.3, augmenting them with inverse Star::starredIn; key and extent declarations. Only Movie has methods,Grouping gathered When from Fig. the 4.4. FROM Clause has Multiple relationshipCollections Studio ownedBy GROUP BY stdo: m.ownedBy.name, yr: m.year HAVING MAX(SELECT p.m.length FROM partition p) > 120 The complete example schema is in Fig. 9.1. In the event that there is more than one variable in the FROM clause.inverse a Studio::owns; fe~ changes to the interpretation of the query are necessary,float lengthInHours()but the principles raises(no~engthF0und); 9.1.2 Path Expressions void starNames(out Set); remain the same as in the one-variable case above. Supposevoid otherMovies(in that the variables Star, out Set) Figure 9.7: Restricting the groups considered IVe access components of objects and structuresappearing using a dot innotation the FROM that clauseis are XI,22, . . . :xk. Then: raises(noSuchStar); similar to the dot used in C and also related to the dot used in SQL. The I; general rule is as follows. If a denotes an object belonging to class C. and p is some property of the class - either an attribute, relationship, or method of the class - then a.p denotes the result of "applying" p to a. That is: class Star Intermediate result (extent Stars key name) 1. If p is an attribute, then a.p is the value of that attribute in object a. < Grouping fields attribute string name; 2. If p is a relationship, then a.p is the object or collection of objects related attribute Struct Addr Struct{ to a by relationship p. {string street, string city) address; stdo: …, 3. If p is a method (perhaps with parameters), then a.p( . .) is the result of relationship Set starredIn yr: …, applying p to a. inverse Movie::stars; 1; partition: bag(struct {m: …}) Example 9.1 : Let myMovie denote an object of type Movie. Then: }; The value of myMovie .length is the length of the movie, that is, the value class Studio of the length attribute for the Movie object denoted by myMovie. (extent Studios key name) C The value of myMovie. lengthInHours0 is a real number, the length of attribute string name; the movie in hours, computed by applying the method 1engthInHours to attribute string address; Bag of structures with members , object mynovie. relationship Set owns inverse Movie::ownedBy; follow what’s in the FROM clause The value of myMovie.stars is the set of Star objects related to the 31 movie myMovie by the relationship stars. I ; Expression myMovie starNames(myStars) returns no value (LC., in C++ . Figure 9.1: Part of an object-oriented inovie database the type of this expression is void). As a side effect, however, it sets the value of the output variable mystars of the method starNames to be a set of strings; those strings are the names of the stars of the mol-ic. 436 CHAPTER 9. OBJECT-ORIENT.4TION IN QUERY LA-WGUAGES 9.2. ADDITIONAL FORMS OF OQL EXPRESSIONS 437

Exercise 9.1.3 : In Fig. 9.3 is an ODL description of our running "battleships" 9.2.1 Quantifier Expressions database. Add the following method signatures: lie can test whether all members of a collection satisfy some condition, and we can test whether at least one member of a collection satisfies a condition. To a) Compute the firepower of a ship, that is, the number of guns times the test whether all members x of a collection S satisfy condition C(x), we use the cube of the bore. OQL expression: b) Find the sister ships of a ship. Raise the exception nosisters if the ship FOR ALL x IN S : C(x) is the only one of its class. The result of this expression is TRUE if every x in S satisfies C(x) and is FALSE c) Given a battle b as a parameter, and applying the method to a ship s, otherwise. Similarly, the expression find the ships sunk in the battle b, provided s participated in that battle. 426 CHAPTER 9. OBJECT-ORIENTflTIONIN QUERY LANGUAGESRaise the exception didNotParticipateINTRODUCTION if ship s did TO notOQL fight in battle EXISTS x IN S : C(x) b. OQL: COLLECTION OPERATORS object-oriented host language, such as C++, Smalltalk, or Java. Objects will has value TRUE if there is at least one x in S such that C(X)is TRUE and it has be manipulated both by OQL queries and by the conventional statementsd) Given of a thename and a year launched as parameters, add a ship of this name value FALSE otherwise. host language. The ability to mix host-language statements and andOQL yearqueries to the class to which the method is applied. without explicitly transferring values between the two languages is an advance class Movie Example 9.7 : Another way to express the query "find all the stars of Disney over the way SQL is embedded into a host language, as was discussed in Sec- (extent Movies key (title, year)) tion 8.1. ! Exercise 9.1.4: Repeat each part of ExerciseC 9.1.2 using at least one subquery • movies"Like is inshown SQL, in Fig. 9.4.we Here, have we focus onANY, a star s andALL, ask if they are in each of your queries. attribute string title; the star of some movie rn that is a Disney movie. Line (3) tells us to consider 9.1.1 An Object-Oriented Movie Example attribute integer year; allEXISTS movies m in the set of movies s. starredIn, which is the set of movies in attribute integer length; which star s appeared. Line (1) then asks whether movie m is a Disney movie. In order to illustrate the dictions of OQL, we need a runningExercise example. 9.1.5: It Using the ODL schema of Exerciseattribute 9.1.3 enum andFilm Fig.(color,blackAndWhite> 9.3, xvritc filmType; we will involve the familiar classes Movie, Star, and Studio.. the We follolving shall use thequeries in OQL: relationship Set stars If find even one such movie m, the value of the EXISTS expression in lines definitions of Movie, Star, and Studio from Fig. 4.3, augmenting them with inverse Star::starredIn; (3) and (4) is TRUE; otherwise it is FALSE. key and extent declarations. Only Movie has methods, gathered from Fig. 4.4. relationship Studio ownedBy • OQL has similar operators The complete example schema is in Fig. 9.1. a) Find the names of the classes of ships with at least nineinverse guns. Studio::owns; float lengthInHours() raises(no~engthF0und); 9.1.2 Path Expressions b) Find the ships (objects, not ship names)void with starNames(out at least nine Set); guns. 1) SELECT s void otherMovies(in Star, out Set) 2) FROM Stars s IVe access components of objects and structures using a dot c)notation Find thatthe namesis of the ships with a displacement underraises(noSuchStar); 30,000 tons. Nake similar to the dot used in C and also related to the dot used in SQL. The I; 3) WHERE EXISTS m IN s.starredIn : general rule is as follows. If a denotes an object belonging to classthe C. result and pa list, ordered by earliest launch year first, and if there are ties. 4) m. ownedBy .name = "Disney" is some property of the class - either an attribute, relationship, alphabeticallyor method of by ship name. the class - then a.p denotes the result of "applying" p to a. That is: class Star Select stars who participated in a d) Find the pairs of objects that are sister ships(extent (i.e., Stars ships key of thename) same class). Figure 9.4: Using an existential subquery 1. If p is an attribute, then a.p is the value of that attribute in object a. movie made by ‘Disney’ 3ote that the objects themselves are starredIn stars that have appeared only in Disney movies. Technically, that set includes case where there is only one variable x in the FROM clause. The value of x ranges applying p to a. inverse Movie::stars; .'stars" whoSELECT appear s in no movies at all (as far as we can tell from our database). over some collection, C. For each member of C, say i, that satisfies the condition !! f) Find the names of the batt~lesin which1; no ship was listed as damaged. It is possibleFROM Starsto add s another condition to our query, requiring that the star Example 9.1 : Let myMovie denote an object of type Movie. Then: of the WHERE clause, we evaluate all the expressions that follow the GROUP BY, appear inWHERE at least FOR oneALL rnovie.m IN buts.starredIn TW lealr that : improvement as ail exercise. to obtain values el (i), ea(i),. , . , en(i). This list of values is the group to which m. ownedBy name = "Disney" The value of myMovie .length is the length of the movie, that is, the value class Studio Figure 9.5 shows the query.. value i belongs. of the length attribute for the Movie object denoted9.2 by myMovie. Additional Forms of QQL(extent Expressions Studios key name) C Select stars who participated only The value of myMovie. lengthInHours0 is a real number, the length of attribute string name; Figure 9.5: Using a subquery with universal quantification The Intermediate Collection the movie in hours, computed by applying the methodIn 1engthInHours this section to we shall see some of the otherattribute operators, string besides address; select-from- 9.2.2 in Aggregationmovies made by Expressions ‘Disney’ , object mynovie. where, that OQL provides to help us build expressions. These operators in- relationship Set owns The actual value returned by the GROUP BY is a set of structures, which we shall clude logical quantifiers - for-all and there-exists - aggregationinverse Movie::ownedBy; operators, OQL uses the same five aggregation operators that SQL does: AVG, COUNT.32 SUM. The value of myMovie.stars is the set of Star objects related to the applying to a designated of a table, the same operators in OQL apply call the intermediate collection. The members of the intermediate collection movie myMovie by the relationship stars. 'the goup-by operator, and set operators -I ; union, intersection, and difference. MIN. and MAX. However, while these operators in SQL may be thought of as to all collections whose members are of a suitable type. That is, COUNT can have the form Expression myMovie starNames(myStars) returns no value (LC., in C++ . Figure 9.1: Part of an object-oriented inovie database apply to any collection; SUM and AVG can be applied to collections of arithmetic the type of this expression is void). As a side effect, however, it sets the value of the output variable mystars of the method starNames to be a types such as integers, and MIN and MAX can be applied to collections of any set of strings; those strings are the names of the stars of the mol-ic. type that can be compared, e.g., arithmetic values or strings. The first n fields indicate the group. That is, (vl, vz, . . . , v,) must be the list of values (el(i), ez(i), . . . ,en(i)) for at least one value of i in the collection C Example 9.9: To compute the average length of all movies, we need to create that meets the condition of the WHERE clause. a bag of all movie lengths. Note that we don't want the set of movie lengths, The last field has the special name partition. Its value is, intuitively, because then two movies t,hat had the same length would count as one. The the values i that belong in this group. ,\Iore precisely. P is a bag consisting of query is: structures of the form Struct (x: i),m-here x is the variable of the FROM clause. AVG(SELECT m.length FROM Movies m) The Output Collection That is, we use a subquery to extract the length components from movies. Its The SELECT clause of a select-from- here expression that has a GROUP BY clause result is the bag of lengths of movies, and we apply the AVG operator to this may refer only to the fields in the structures of the intermediate collection. bag. giving the desired answer. 0 namely fl.f2. . . . , fn and partition. Through partition, we may refer to the field x that is present in the structures that are members of the bag P that forms 9.2.3 Group-By Expressions the value of partition. Thus, we may refer to the variable x that appears in The GROUP BY clause of SQL carries over to OQL, but with an interesting twist the FROM clause, but we may only do so within an aggregation operator that in perspective. The form of a GROUP BY clause in OQL is: aggregates over all the menibers of a bag P. The result of the SELECT clause will be referred to as the output collection. 1. The keywords GROUP BY. Example 9.10: Let us build a table of the total length of movies for each 2. .I comma-separated list of one or more partition attributes. Each of these studio and for each pear. In OQL. what we actually construct is a bag of consists of structures. each xvith three componellts - a studio, a year: and the total length of movies for that studio and year. The query is shown in Fig. 9.6. (a) A field name, (b) A colon, and SELECT stdo, yr, sumlength: SUM(SELECT p.m.length (c) An expression. FROM partition p) FROM Movies m That is. the form of a GROUP BY clalisc is: GROUP BY stdo: m.ownedBy.name, yr: m.year

GROUP BY fl:el, f2:e2,.. . . f,:e,, Figure 9.6: Grouping movies by studio and year Each GROUP BY clause follows a select-from-where query. The expressions el. e?. .. .,en may refer to variables mentioned in the FROM clause. To facilitate To understand this query, let us start at the FROM clause. There, we find ' the explanation of how GROUP BY works, let us restrict ourselves to the common that variable m ranges over all Movie objects. Thus. m here plays the role of x 44.1 CHAPTER 9. OBJECT-0RIENT;LTION IN QUERY LANGUAGES 9.3. OBJECT ASSIGAr1IENT -4ND CREATION IX OQL 445 44.1 CHAPTER 9. OBJECT-0RIENT;LTION IN QUERY LANGUAGES 9.3. OBJECT ASSIGAr1IENT -4ND CREATION IX OQL 445 9.3.1 Assigning Values to Host-Language Variables then the type of the variable and the expression match, and the assignment is legal. Unlike SQL, which needs to move data between components of tuples9.3.1 Assigningand host- Values to Host-Language Variables then the type of the variable and the expression match, and the assignment is language variables, OQL fits naturally into its host language. That is: the legal. expressions of OQL that we have learned, such as select-from-where,Unlike SQL, produce which needs to move data between components of9.3.3 tuples and host-Obtaining Each Member of a Collection objects as values. It is possible to assign to any host-languagelanguage variable variables, of the OQL fits naturally into its host language. That is: the Obtaining each member of a set9.3.3 or bagObtaining is more Eachcomplex, Member but stillof a Collectionsimpler than proper type a value that is the result of one of these OQL expressions.expressions of OQL that we have learned, such as select-from-where,the -based produce algorithms we needed in SQL. First, we need to turn our set objects as values. It is possible to assign to any host-languageor variablebag into of the a list. \Ye do soObtaining with a eachselect-from-where member of a set or bag expression is more complex, that but stilluses simpler than Example 9.13 : The OQL expression proper type a value that is the result of one of these OQL expressions.ORDER BY. Recall from Sectionthe 9.1.4 cursor-based that the algorithms result we of needed such in SQL.an expression First, we need isto turna our set SELECT DISTINCT m list of the selected objects or values.or bag into a list. \Ye do so with a select-from-where expression that uses Example 9.13 : The OQL expression FROM Movies m ORDER BY. Recall from Section 9.1.4 that the result of such an expression is a Example 9.15: Suppose we want a list of all the movie objects in the class WHERE m.year < 1920 SELECT DISTINCT m list of the selected objects or values. Movie. We can use the title and (to break ties) the year of the movie, since 44.1 CHAPTER 9. OBJECT-FROM Movies0RIENT;LTION m IN QUERY LANGUAGES 9.3. OBJECT ASSIGAr1IENT -4ND CREATION IX OQL 445 produces the set of all those movies made before 1920. Its type is Set. (title, year) is a key for Movie. The statement WHERE m.year < 1920 Example 9.15: Suppose we want a list of all the movie objects in the class If oldMovies is a host-language variable of the same type, then we may write Movie. We can use the title and (to break ties) the year of the movie, since Assigning Values to Host-Language VariablesmovieList = SELECT m then the type of the variable and the expression match, and the assignment is (in C++ extended with OQL): 9.3.1 produces the set of all those movies made before 1920. Its type is Set. (title, year) is a key for Movie. The statement FROM Movies m legal. Unlike SQL, which needs toIf oldMoviesmove data is a host-language between variablecomponents of the same of type, tuples then we and may writehost- oldMovies = SELECT DISTINCT m INTEGRATING OQL &ORDER EXTERNAL BY m.title, m.year; language variables, OQL fits(in C++ naturally extended with into OQL): its host language. That is: the movieList = SELECT m FROM Movies m 9.3.3 Obtaining Each Member of a Collection WHERE m.year expressions< 1920; of OQL that we have learned, such as select-from-where, produce FROM Movies m oldMovies = SELECT DISTINCT m assigns to host-language variable movieList a list of all the Movie objects, objects as values. It is possible to assign to any host-language variable of the ObtainingORDER BY m.title, each m.year;member of a set or bag is more complex, but still simpler than FROM Movies m LANGUAGESsorted by title and year. and the value of oldMovies will becomeproper the type set a of value these that Movie is objects.the result of one of these OQL expressions. the cursor-based algorithms we needed in SQL. First, we need to turn our set WHERE m.year < 1920; Once x-e haye a list, sortedassigns or not. to host-languagewe canor bagaccess variable into each movieList a element list. a list\Ye by of allnumber;do the so Movie with objects, a select-from-where expression that uses Example 9.13 : The OQL expression sorted by title and year. 9.3.2 Extracting Elements of Collections and the value of oldMovies will become the set of these Moviethe objects. ith element of the list L is obtained by ORDERL[i - 11. BY. Note Recall that fromlists and Section arrays 9.1.4 that the result of such an expression is a are assunled numbered starting at 0, as in C or C++. Since the select-from-where and group-bySELECT expressions• OQL DISTINCT each produce fitsm collectionsnaturally in OO host languagesOnce x-e haye lista list, of sorted the or selectednot. we can accessobjects each elementor values. by number; - either sets, bags, or lists - we must doFROM something Movies extra m if we want a single 11. 9.3.2 Extracting Elements of Collections Example 9.16 : Suppose we thewant ith elementto write ofExample the a list C++ L is obtained function 9.15: by L[i Supposethat - Noteprints that we liststhe want and arrays a list of all the movie objects in the class element of that collection. This statementWHERE is true m.year even if . 9.9. (title, year) is a key for Movie. The statement to turn a singleton collection into its lone member. This operator- can either be sets, applied. bags, or lists - we must do something extra if we want a single Example 9.16 : Suppose we want to write a C++ function that prints the If oldMovies is a host-language variable of the same type, then we may write for instance, to the result of a query that is knownhost to return program a elementsingleton. of that collection. This statement is true even if we have a collection title. year, and length of each movie. -1 sketch of the function is shown in (in C++ extended with OQL): movieList = SELECT m that n-e are sure contains only one element. OQL provides the operator1) ELEMENT movieList = SELECTFig. m9.9. Example 9.14 : Suppose we would like to assign to the variableto turn gwtw. a singleton of type collection into its lone member. This operator can be applied. FROM Movies m FROM Movies m oldMovies = SELECT DISTINCT m Movie (i.e., the Movie class is its type) the object representing forthe instance, movie to theGone result of a query that is known to return a singleton. ORDER BY m.title, m.year; ORDER BY m.title, m.year; FROM Movies m lllth the Wind. The result of the query 2) number0fMovies = ~0UNT(Movies);1) movieList = SELECT m WHERE m.year < 1920; assigns to host-language variable movieList a list of all the Movie objects, Example 9.14 : Suppose we would like to assign to the variable gwtw.3) of typefor(i=O; i. Line (2) computesFigure 9.9: theExanlining number and printingof movies. each movie using 1; for instance, to the result of a query that is known to return a singleton.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 toFROM assign Movies tom the variable gwtw. of type Line (1) sorts the Movie class, placing the result intoFROM variable Moviesmovielist, m Movie (i.e., the Movie class is its type) theWHERE object m.title representing = "Gone With the the Wind" movie Gone ~vhosetype is List. Line (2) computes the numberORDER of movies. BY usingm.title, m.year; lllth the Wind. The result of the query1; the OQL operator COUNT. Lines2) (3)number0fMovies through (6)are a for-loop in= which~0UNT(Movies); integer 3) for(i=O; i. Line (2) computes the number of movies. using 1; the OQL operator COUNT. Lines (3) through (6)are a for-loop in which integer 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

• Second Approach: Object-Relational Model

34 SECOND APPROACH: OBJECT- RELATIONAL MODEL

• Object-oriented model tries to bring the main concepts from relational model to the OO domain • The heart is OO concepts with some extensions

• Object-relational model tries to bring the main concepts from the OO domain to the relational model • The heart is the relational model with some extensions • Extensions through user-defined types

35 CONCEPTUAL VIEW OF OBJECT- RELATIONAL MODEL

• Relation is still the fundamental structure

• Relational model extended with the following features • Type system with primitive and structure types (UDT) • Including set, bag, array, list collection types • Including structures like records • Methods • Special operations can be defined over the user-defined types (UDT) • Specialized operators for complex types, e.g., images, multimedia, etc. • Identifiers for tuples • Unique identifiers even for identical tuples • References • Several ways for references and de-references

36 168 CHAPTER 4. OTHER DAT.4 MODELS . THE OBJECT-RELATIONAL MODEL 169 integers, reals, strings, and SO on had little to do with the issues discussed, attributes, street and city, and there are two tuples, corresponding to her such as functional dependencies and normalization. We shall continue to avoid two houses. Next comes the birthdate, another atomic value. Finally, there is a this distinction, but when describing the schema of a nested relation, we must component for the movies attribute; this attribute has a relation schema as its indicate which attributes have relation schemas as types. To do so, we shall type, with components for the title, year, and length of a movie. The relation treat these attributes as if they were the names of relations and follow them for the movies component of the Carrie Fisher tuple has tuples for her three by a parenthesized list of their attributes. Those attributes, in turn, may haye best-known movies. associated lists of attributes, down for as many levels as we wish. The second tuple, for Mark Hamill, has the same components. His relation for address has only one tuple, because in our imaginary data, he has only Example 4.23: Let us design a nested relation schema for stars that incor- one house. His relation for movies looks just like Carrie Fisher's because their porates within the relation an attribute movies, which will be a relation rep- best-known movies happen, by coincidence, to be the same. Note that these resenting all the movies in which the star has appeared. The relation schema two relations are two different tuple-components. These components happen to for attribute movies will include the title, year, and length of the movie. The be identical, just like two components that happened to have the same integer +r Stars re1atio:i schem? the relation mill include the name, address, and birth- value, e.g., 124. 0 date, as well a:, :e found in movies. Additionally, the address attribute will have a relation type with attributes street and city. We can record in this relation several addresses for the star. The schema for Stars can 4.5.3 References be written: The fact that movies like Star Wars will appear in several relations that are Stars(name, address(street, city), birthdate, values of the movies attribute in the nested relation Stars is a cause of redun- movies(title, y .>r , length)) dancy. In effect, the schema of Example 4.23 has the nested-relation analog of not being in BCNF. However, decomposing this Stars relation will not elimi- An exampl(s F a possibleCONCEPTUAL relation for nested relation Stars is VIEWshown in OF OBJECT-nate the redundancy. Rather, we need to arrange that among all the tuples of Fig. 4.17. We srv in this relation two tuples, one for Carrie Fisher and one all the movies relations, a movie appears only once. for Mark Warnill. The valucs of components are abbreviated to conserve space, To cure the problem, object-relations need the ability for one tuple t to refer and the dashed lines separating tuplesRELATIONAL are only for convenience and have no MODELto another tuple s: rather than incorporating s directly in t. lye thus add to notational significance. our model an additional inductive rule: the type of an attribute can also be a reference to a tuple with a given schema. riame address birthdate rnovies If an attribute .I has a type that is a reference to a single tuple with a I I I relation schema named R, we show the attribute d in a schema as ,-l(*R). Fisher 1 street city 9 / 9 /9 9 1 rifle 1 year 1 ~~r~~~j1 Xotice that this situation is analogous to an ODL relationship .4 whose type is 1 .4 R; i.e., it connects to a single object of type R. Similarly, if an attribute has r:-% Star Wars 1977 124 a type that is a set of references to tuples of schema R. then .-Iwill be shown in a schema as A({*R)).This situation resembles an ODL relationship .A that • Allow of nestedhas typerelations Set. .------Example 4.24: An appropriate way to fix the redundancy- in Fig. 4.17 is • Repeating moviesto use t~voinsiderelations. the one stars for stars and one For movies. The relation Movies miStar------Wars 1977 ---124 will be an ordinary relation ~viththe same schema as the attribute movies in records is redundancyExample 4.23. The relation Stars xvill have a schema similar to the nested Empire------1980 ---127 Stars Return 1983 133 relation of that example. but the movies attribute will have a type that is a set of references to Movies tuples. The schemas of the tn-o relations are Star(name, address(street, city), birthdate, • To avoid redundancy,thus: use pointers Figure 4.17: A nested relation for stars and their movies 4. 4.5. 171 170 movies(title, year, length))CH-dPTER OTHER DATA MODELS(references) Movies (title,THE year,OBJECT-RELATIONAL length) MODEL \ In the Carrie Fisher tuple, we see her name. an atomic value, follo~ved Stars (name, address (street, city), birthdate, 3p a relation for the value of the address component. That relation has two movies(i*Movies3>interfaces, which are 1 essentially . class declarations without an extent (see the box on "Interfaces" in Section 4.3.4). Then, ODL allows you to define any number \ of classes that inherit this interface, while each class has a distinct extent. In that manner, ODL offers the same opportunity the object-relational approach when it comes to sharing the same declaration among several collections.

ire did not discuss the use of methods as part of an object-relational schema. Movie However, in practice, the SQL-99 standard and all irnplementations of object- relational ideas allow the same ability as ODL to declare and define methods Star associated with any37 class. Stars Movies Type Systems Figure 4.18: Sets of references as the wlue of a,n attribute The type systems of the object-oriented and object-relational models are quite similar. Each is based on atomic types and construction of new types by struct- ~h~ data of Fig. 4.17, converted to this new schema, is shown in Fig. 4.18. and collection-type-constructors. The selection of collection types may vary, but Sotice that, because each movie has only one tuple, although it can have man!. all variants include at least sets and bags. AIoreover, the set (or bag) of structs references, \ye have eliminated the redundancy inherent in the schema of Ex- type plays a special role in both models. It is the type of classes in ODL, and ample 4.23. the type of relations in the object-relational model.

4.5.4 object-Oriented Versus Object-Relational References and Object-ID'S ~1,~object-oriented data model, as typified by ODL, and the object-relational .A pure object-oriented model uses object-ID'S that are completely hidden from model discussed here, are remarkably similar. Some of the salient points of the user, and thus cannot be seen or queried. The object-relational model allows references to be part of a type, and thus it is possible under some circumstances comparison follow. for the user to see their values and even remember them for future use. You may regard this situation as anything from a serious bug to a stroke of genius, Objects and Tuples depending on your point of , but in practice it appears to make little An object's value is really a struct with components for its attributes alld re- lationships. ~t is not specified in the ODL standard how relationships are to be represented, but we may assume that an object is connected to related ob- Backwards Compatibility jects by some collection of pointers. -1 tuple is likewise a struct, but in the conventional relational model, it has colnponents for only the attributes. Re- With little difference in essential features of the two models, it is interesting to lationsllips would be represented by tuples in another relation, as suggested in consider ~rhyobject-relational systems have dominated the pure ~bject-~ri~~t~d Sectioll 3.2.2. Ho~veverthe object-relational model, by allo\ving sets of refer- systems in the marketplace. The reason, we believe, is that there -? by the cncfs to be a compollent of tuples, also allo\x-s relationships to be incorporated time object-oriented systems were seriously proposed, an enormous number directly into the tuples that represent an "object" or entity. of installations running a relational database system. -4s relational DBlIS's evolved into object-relational DBMS's, the vendors were careful to maint.ain back~vardscompatibility. That is. nen-er versions of the system would still run Extents and Relations the old code and accept the same schemas, should the user not care to adopt ODL treats all objects in a class as living in an "extent" for that class. The any of the object-oriented features. On the other hand, miflation to a pure object-relational model allorvs several different relations with identical schemas. object-oriented DBMS would require the installations to rewrite and reorganize so it might appear that there is more opportunity in the object-relational model , extensively. Thus, whatever competitive advantage existed was not enough to to distinguish members of the same class. However, ODL allows the definition of , convert many databases to a pure object-oriented DBXIS. SUPPORT FROM VENDORS

• Several major software companies including IBM, Informix, Microsoft, Oracle, and Sybase have all released object-relational versions of their products

• Extended SQL standards called SQL-99 or SQL3

38 SQL-99: QUERY LANGUAGE FOR OBJECT- RELATIONAL MODEL

• User-defied types (UDT) replace the concept of classes

• Create relations on top of the UDTs • Multiple relations can be created on top of the same UDT

Create Type AS (attributes and method declarations)

39 450 CHAPTER 9. OBJECT-ORI%NTATION M QUERY LANGUAGES 9.4. USER-DEFZXED TYPES IN SQL 451

1. The keywords CREATE TYPE, 9.4.2 Methods in User-Defined Types 450 CHAPTER 9. OBJECT-ORI%NTATION M QUERY LANGUAGES 9.4. USER-DEFZXED TYPES IN SQL 451 The declaration of a method resembles the way a function in PSM is introdnced; 2. A name for the type, see Section 8.2.1. There is no analog of PSI1 procedures as methods. That is, 450 CHAPTER 9. OBJECT-ORI%NTATION1. TheM QUERYkeywords LANGUAGES CREATE TYPE, 9.4. USER-DEFZXED TYPES IN SQL 9.4.2 Methods in451 User-Defined Types every method returns a value of some type. While function declarations and 3. The keyword AS, definitionsThe declaration in PShf of are a method combined, resembles a method the needs way a both function a declaration, in PSM is within introdnced; the 1. The keywords CREATE TYPE, 2. A name for the type, 9.4.2 Methods in User-Defined Typesdefinitionsee Section of its8.2.1. type, There and a is separate no analog definition, of PSI1 in procedures a CREATE asMETHOD methods. statement. That is, 4. A parenthesized, comma-separated list of attributesThe and declaration their types. of a method resembles the way a functioneveryX method methodin PSM declaration isreturns introdnced; a looksvalue likeof somea PSI1 type. function While declaration, function declarations with the key- and The keyword AS, 2. A name for the type, 3. see Section 8.2.1. There is no analog of PSI1 proceduresworddefinitions METHOD as methods. in replacing PShf areThat combined,CREATE is, FUNCTION. a method However, needs both SQL a declaration, methods typicallywithin the 5. A comma-separated list of methods, including theirevery argument method ty returns pe(s) , a value of some type. Whilehavedefinition function no arguments; of declarations its type, they and and are a separate applied definition,to rows, just in aas CREATE ODL methodsMETHOD statement. are ap- 3. The keyword AS, 4. andA parenthesized, return type. comma-separated list of attributesdefinitions and their in types. PShf are combined, a method needs pliedboth Xato declaration,method objects. declaration In within the definition the looks like of thea PSI1 method, function SELF declaration, refers to this with tuple, the key-if definition of its type, and a separate definition, innecessary. aword CREATE METHOD METHOD replacing statement. CREATE FUNCTION. However, SQL methods typically 4. A parenthesized, comma-separated listThat of 5.attributes is,A thecomma-separated definition and their oftypes. a typelist ofT hasmethods, the form including their X argument method declaration ty pe(s) , looks like a PSI1 functionhave declaration, no arguments; with the they key- are applied to rows, just as ODL methods are ap- and return type. word METHOD replacing CREATE FUNCTION. However,Exampleplied SQL to objects.9.21:methods LetIn typically theus extenddefinition the of definitionthe method, of theSELF type refers AddressType to this tuple, of if 5. A comma-separated list of methods, including their argument ty pe(s) , have no arguments; they are applied to rows, justFig.necessary. as9.10 ODL with methods a method are ap-houseNumber that extracts from the street com- CREATE TYPE T AS ; and return type. That is, the definition of a type T has the form plied to objects. In the definition of the method,ponent SELF refersthe portion to this devoted tuple, if to the house address. For instance, if the street necessary. componentExample \-ere9.21: '123 Let Maple us extend St. ', the then definition houseNumber of the should type AddressTypereturn '123'. of That is, the definition of a type T has the formExample 9.20: ?Ve can create a type representing movie stars, analogous to TheFig. revised 9.10 withtype adefinition method ishouseNumber thus: that extracts from the street com- the class StarCREATE found TYPE in T the AS OQL ExampleHowever, we9.21:; cannot Let us extend the definition ofponent the type the AddressTypeportion devoted of to the house address. For instance, if the street represent directly a set of movies as a field within Star tuples.Fig. 9.10 Thus, with we ashall method houseNumber that extractscomponent CREATEfrom the \-ereTYPE street '123AddressType com- Maple St. AS ', (then houseNumber should return '123'. CREATE TYPE T AS ; startExample with only 9.20: the ?Ve name can and create address a type components representing of Starmovieponent tuples. stars, the analogous portion devotedto to the house address.The For revisedinstance,street type if the definitionCHAR(501, street is thus: component \-ere '123 Maple St. ', then houseNumber should return '123'. theTo class begin, Star note found that in thethe typeOQL of example CREATINGan address of Fig. in Fig.9.1. 9.1However, is itself wea tuple,cannot UDT city CHAR(20) Example 9.20: ?Ve can create a type representing movie stars, analogous to The revised type definition is thus: withrepresent components directly streeta set of andmovies city. as aThus, field wewithin need Star two tuples.type definitions, Thus, we oneshall CREATE1 TYPE AddressType AS ( 450 CHAPTER 9. OBJECT-ORI%NTATION M QUERYthe class LANGUAGES Star found in the OQL example9.4. for ofstartUSER-DEFZXED Fig.addresses with 9.1. only However,and the TYPESthe name otherwe IN andcannot SQL for address stars. Thecomponents necessary of definitionsStar tuples.451 are shown in METHODstreet houseNumber CHAR(501, () RETURNS CHAR(^^) ; represent directly a set of movies as a field within Star tuples. Thus, we shall CREATE TYPE AddressType AS ( city CHAR(20) Fig. To9.10. begin, note that the type of an address in Fig. 9.1 is itselfstreet a tuple, CHAR(501, start with only the name and address components of Star tuples. We see the keyword1 METHOD, follon-ed by the name of the method and a parnithe- 1. The keywords CREATE TYPE, 9.4.2with Methodscomponents in street User-Defined and city. Types Thus, we need two type definitions,city oneCHAR(20) To begin, note that the type of an address in Fig. 9.1 is itself a tuple, sized list of itsMETHOD arguments houseNumber and their () types. RETURNS In this CHAR(^^) case, there ; are no arguments, for addresses and the other for stars. The necessary definitions are1 shown in with components street and city. Thus,The we declaration needCREATE two of type aTYPE method definitions, AddressType resembles one the way AS a function( in PSM is introdnced; but the parentheses are still needed. Had there bee11 arguments, they would 2. A name for the type, see Fig.Section 9.10. 8.2.1. There is no analog of PSI1 procedures as methods. That is, METHOD houseNumber () RETURNS CHAR(^^) ; 0 for addresses and the other for stars. The necessary definitionsstreet CHAR(~O),are shown in Creating a type for the address of haveWe seeappeared, the keyword follo~ved METHOD,by their follon-ed types. by such the asname (a ofINT, the methodb CHAR(^)). and a parnithe- Fig. 9.10. every method returnscity a valueCHAR(20) of some type. While function declarations and sized list of its arguments and their types. In this case, there are no arguments, 3. The keyword AS, definitions in PShf are combined, a method needs both a declaration, withinstarsWe seethe the keyword METHOD, follon-ed by the name of theSeparately, method and we aneed parnithe- to define the metliod. -1 simple form of method defini- );CREATE TYPE AddressType AS ( sized list of its arguments and their types. In this case,but thethere parentheses are no arguments, are still needed. Had there bee11 arguments, they would definition of its type, and a separate definition, in a CREATE METHOD statement. tion consists of: 0 street CHAR(~O), have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). 4. A parenthesized, comma-separated list of attributes and theirCREATE types. TYPE AddressType AS ( X method declaration looks like a PSI1 function declaration, with thebut key- the parentheses are still needed. Had there bee11 arguments, they would CREATEcity TYPE StarTypeCHAR(20) AS ( have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). 0 street CHAR(~O), word METHOD replacing CREATE FUNCTION. However, SQL methods typically 1. The keywords CREATE METHOD. name CHAR(30) , Separately, we need to define the metliod. -1 simple form of method defini- 5. A comma-separated list of methods, including their argumentcity ty pe(s) , CHAR(20) have no arguments;); they are applied to rows, just as ODL methods are ap- address AddressType Separately, we need to define the metliod. -1 simpletion consists form of of:method defini- and return type. ); plied to objects. In the definition of the method, SELF refers to this tuple, if 2. The method name. arguments and their types, and the RETURNS clause, CREATE TYPE StarType AS ( tion consists of: necessary.); 1.as The in the keywords declaration CREATE of theMETHOD. method. CREATE TYPE StarType AS ( name CHAR(30) , A hierarchy of types That is, the definition of a type T has the form 1. The keywords CREATE METHOD. 3. The keyword FOR and tlic name of the UDT in which the method is name CHAR(30) , Example 9.21:address Let us extendAddressType the definition of the type AddressType of 2. The method name. arguments and their types, and the RETURNS clause, Figure 9.10: Two type definitions (inheritance) declarcd. address AddressType Fig. 9.10 );with a method houseNumber that extracts from the street com-2. The method name. arguments and their types, andas thein theRETURNS declaration clause, of the method. CREATE TYPE AS ; T ); ponent the portion devoted to the house address. For instance, if the streetas in the declaration of the method. 4. The body of the method. \vhich is ~vrittcnin the same language as the componenth tuple \-ere of'123 type Maple AddressType St. ', then houseNumberhas two components, should return whose '123'. attributes are 3. The keyword FOR and tlic name of the UDT in which the method is Figure 9.10: Two type definitions bodies of PSJI functions. Example 9.20: ?Ve can create a type representing movie stars, analogous to Thestreet revised and type city. definition The is types thus: of these components are character3. strings The keyword of length FOR and tlic name of the UDT in declarcd.which the method is Figure 9.10: Two type50 definitions and 20, respectively. A tuple of type StarType also has tn-odeclarcd. components. the class Star found in the OQL example of Fig. 9.1. However, we cannot For instance,4. The body we could of the define method. the method\vhich is houseNumber ~vrittcnin the from same Example language 9.21 as as: the The hfirst tuple is attribute of type name,AddressType whose( type has is twoa 30-character components, string, whose and attributesthe second areis represent directly a set of movies as a field within Star tuples. Thus, we shall CREATE TYPE AddressType AS 4.Adding The body a of method the method. declaration \vhich is ~vrittcn in the same language as the h tuple of type AddressType has two components,address,street and whose city.whose type Theattributes is itselftypes aof areUDT these AddressType. components are that character is, a tuple strings with ofstreet length bodies of PSJI functions. start with only the name and address components of Star tuples. street CHAR(501, forbodies a type of PSJI (not functions. definition) CREATE METHOD houseNmber RETURNS CHAR (10) street and city. The types of these componentsand cityare character components. strings ofC] length To begin, note that the type of an address in Fig. 9.1 is itself a tuple, 50 and city20, respectively.CHAR(20) A tuple of type StarType also has tn-o components. FOR AddressType 50 and 20, respectively. A tuple of type StarType also has tn-o components. (Encapsulation) For instance, we could define the method houseNumber from Example 9.21 as: with components street and city. Thus, we need two type definitions, one The first1 is attribute name, whose type is a 30-character string,For instance,and the second we could is define the method houseNumber from Example 9.21 as: The first is attribute name, whose type is a 30-character string, and the second is for addresses and the other for stars. The necessary definitions are shown in address,METHOD whose houseNumber type is itself () RETURNSa UDT AddressType.CHAR(^^) ; that is, a tuple with street CREATE METHOD houseNmber RETURNS CHAR (10) address, whose type is itself a UDT AddressType. that is, a tuple with street RETURNS CHAR (10) Fig. 9.10. and city components. C] 452 CREATECHAPTER METHOD 9. houseNmber OBJECT-ORIENTATION INFOR QUERY AddressType LANGU.4GEs 9.1. USER-DEFINED TYPES IAr SQL 453 and city components. C] We see the keyword METHOD, follon-ed by the name of the method and a parnithe-FOR AddressType sized list of its arguments and their types. In this case, there are no arguments,BEGIN A REF(T) SCOPE R . . . CREATE TYPE AddressType AS ( but the parentheses are still needed. Had there bee11 arguments, they would If no scope is specified, the reference can go to any relation of type T 0 END ; street CHAR(~O), have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). 40 ExampIe 9.23 : Reference attributes are not sufficient to record in MovieStar city CHAR(20) \Ve have omitted the body of the method because accomplishing the intended Separately, we need to define the metliod. -1 simple form of methodseparation defini- of the string string as intended is nontrivial, even in PSM. the set of all movies they starred in, but they let us record the best movie for ); each star. Assume that we have declared a relation Movie, and that the type of tion consists of: this relation is the UDT MovieType; we shall define both MovieType and Movie 9.4.3 Declaring Relations with a UDT CREATE TYPE StarType AS ( later, in Fig. 9.11. The following is a new definition of StarType that includes 1. The keywords CREATE METHOD. Having declared a type, we may declare one or more relations whose tuples are a11 attribute bestMovie that is a reference to a movie. name CHAR(30) , of that type. The form of relation declarations is like that of Section 6.6.2, but address AddressType 2. The method name. arguments and their types, and the RETURNSwe clause, use CREATE TYPE StarType AS ( name CHAR(30) , ); as in the declaration of the method. address AddressType, bestMovie REF(MovieType) SCOPE Movie 3. The keyword FOR and tlic name of the UDT in which the methodin place is of the list of attribute declarations in a normal SQL table declaration. > ; Figure 9.10: Two type definitions declarcd. Other elements of a table declaration, such as keys, foreign keys, and tuple- based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star 4. The body of the method. \vhich is ~vrittcnin the same languageonly as tothe this table, not to the UDT itself. tuple will have a component that refers to a Movie tuple - the star's best h tuple of type AddressType has two components, whose attributes are movie. street and city. The types of these components are character strings of length bodies of PSJI functions. Example 9.22 : We could declare MovieStar to be a relation whose tuples were of type StarType by 50 and 20, respectively. A tuple of type StarType also has tn-o components. Sest, n-e must arrange that a table such as Movie in Example 9.23 will have houseNumber as: a reference column. Such a table is said to be referenceable. In a CREATE TABLE For instance, we could define the method from Example 9.21 CREATE TABLE MovieStar OF StarType; The first is attribute name, whose type is a 30-character string, and the second is statement n-here the type of the table is a UDT (as in Section 9.4.3), we may address, whose type is itself a UDT AddressType. that is, a tuple with street CREATE METHOD houseNmber RETURNS CHAR (10) As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: and city components. C] FOR AddressType attribute, name, is an ordinary character string, but the second, address. has a type that is itself a UDT, namely the type AddressType. REF IS tattribute name>

• Book Type contains collections • Arrays of authors à capture the order of authors • Set of keywords create type Book as (title varchar(20), author-array varchar(20) array [10], pub-date date, publisher Publisher, keyword-set setof(varchar(20)))

• Large object types • CLOB: Character large objects Usually provide methods inside book-review CLOB(10KB) the UDT to manipulate CLOB & • BLOB: binary large objects BLOB image BLOB(10MB) movie BLOB(2GB)

41 450 CHAPTER 9. OBJECT-ORI%NTATION M QUERY LANGUAGES 9.4. USER-DEFZXED TYPES IN SQL 451

1. The keywords CREATE TYPE, 9.4.2 Methods in User-Defined Types The declaration of a method resembles the way a function in PSM is introdnced; 2. A name for the type, see Section 8.2.1. There is no analog of PSI1 procedures as methods. That is, every method returns a value of some type. While function declarations and 3. The keyword AS, definitions in PShf are combined, a method needs both a declaration, within the definition of its type, and a separate definition, in a CREATE METHOD statement. 4. A parenthesized, comma-separated list of attributes and their types. X method declaration looks like a PSI1 function declaration, with the key- word METHOD replacing CREATE FUNCTION. However, SQL methods typically 5. A comma-separated list of methods, including their argument ty pe(s) , have no arguments; they are applied to rows, just as ODL methods are ap- and return type. plied to objects. In the definition of the method, SELF refers to this tuple, if necessary. That is, the definition of a type T has the form Example 9.21: Let us extend the definition of the type AddressType of Fig. 9.10 with a method houseNumber that extracts from the street com- CREATE TYPE T AS ; ponent the portion devoted to the house address. For instance, if the street component \-ere '123 Maple St. ', then houseNumber should return '123'. Example 9.20: ?Ve can createCREATING a type representing movie stars, RELATIONSanalogous to The revised type definition is thus: the class Star found in the OQL example of Fig. 9.1. However, we cannot represent directly a set of movies as a field within Star tuples. Thus, we shall CREATE TYPE AddressType AS ( start with only the name and address components of Star tuples. street CHAR(501, To begin, note that the type of an address in Fig. 9.1 is itself a tuple, city CHAR(20) with •components Once street types and city. areThus, we created, need two type definitions, we one can create relations1 for addresses and the other for stars. The necessary definitions are shown in METHOD houseNumber () RETURNS CHAR(^^) ; Fig. 9.10. We see the keyword METHOD, follon-ed by the name of the method and a parnithe- sized list of its arguments and their types. In this case, there are no arguments, CREATE TYPE AddressType AS ( but the parentheses are still needed. Had there bee11 arguments, they would • In general, we can create tables without types 0 street CHAR(~O), have appeared, follo~vedby their types. such as (a INT, b CHAR(^)). city CHAR(20) • But types provide encapsulation, inheritance, etc.Separately, we need to define the metliod. -1 simple form of method defini- ); tion consists of: CREATE TYPE StarType AS ( 1. The keywords CREATE METHOD. name CHAR(30) , address AddressType Create Table MovieStar OF StarType2. The; method name. arguments and their types, and the RETURNS clause, ); as in the declaration of the method. 3. The keyword FOR and tlic name of the UDT in which the method is Figure 9.10: Two type definitions declarcd.

h tuple of type AddressType has two components, whoseHow attributes to define are keys and 4. The body of the method. \vhich is ~vrittcnin the same language as the street and city. The types of these components are character strings of length bodies of PSJI functions. 50 and 20, respectively. A tuple of type StarType also has tn-orelationships??? components. For instance, we could define the method houseNumber from Example 9.21 as: The first is attribute name, whose type is a 30-character string, and the second is address, whose type is itself a UDT AddressType. that is, a tuple with street CREATE METHOD houseNmber RETURNS CHAR (10) and city components. C] FOR AddressType

42 450 CHAPTER 9. OBJECT-ORI%NTATION M QUERY LANGUAGES 9.4. USER-DEFZXED TYPES IN SQL 451

1. The keywords CREATE TYPE, 9.4.2 Methods in User-Defined Types The declaration of a method resembles the way a function in PSM is introdnced; 2. A name for the type, see Section 8.2.1. There is no analog of PSI1 procedures as methods. That is, every method returns a value of some type. While function declarations and 3. The keyword AS, definitions in PShf are combined, a method needs both a declaration, within the CREATING RELATIONSdefinition of its type, and a separate definition, in a CREATE METHOD statement. 4. A parenthesized, comma-separated list of attributes and their types. 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERYX methodLAXGU-AGES declaration looks like a PSI1 9.5.function OPERATIONS declaration, ON with OBJECT-RELATIONAL the key- DATA 455 word METHOD replacing CREATE FUNCTION. However, SQL methods typically 5. A comma-separated list of methods, including their argument ty pe(s) , have no arguments; they are applied to rows, just as ODL methods are ap- and return type. * b) PersonType, with a name of the person and references to the persons that 1) CREATE TYPE MovieType AS ( plied to objects. In the definition of the method,are SELF their refersmother to and this father. tuple, You if must use the type from part (a) in your • A single primary key can2 be titledefined CHAR(30) using , Primarynecessary. Key declaration. That is, the definition of a type T has the form year INTEGER, keyword 3,4) incolor BOOLEAN Example 9.21: Let us extend the definitionc) MarriageType,of the type AddressType with the date ofof the marriage and references to the hus- 1 ; Fig. 9.10 with a method houseNumber that extractsband and from wife. the street com- CREATE TYPE T AS CHAPTER ; 9. OBJECT-ORIENTATION IN QUERYponent LAXGU-AGES the portion devoted to the house address.9.5. OPERATIONS For instance, ON if the OBJECT-RELATIONAL street DATA 455 Exercise 9.4.2: Redesign our running products database schema of Exer- 5) CREATE TABLE Movie OF MovieType ( component \-ere '123 Maple St. ', then houseNumber should return '123'. 6) REF IS movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes where appropriate. Example• 9.20:To reference?Ve can create a type another representing movierelation stars, analogous R, R tohas to be referenceableThe revised type definition is thus: * b) PersonType, with a name of the person and references to the persons that 7) PRIMARY KEY (title, year) In particular, in the relations PC: Laptop, and Printer make the model at- the class Star found in the OQL example of Fig. 9.1. 1)However, CREATE weTYPE cannot MovieType AS ( are their mother and father. You must use the type from part (a) in your using REF keyword 1; tribute be a reference to the Product tuple for that model. represent directly a set of movies as a field within Star 2tuples. Thus,title we shallCHAR(30) , CREATE TYPE AddressType AS ( declaration. year INTEGER, start with only the name and address components of Star tuples. Tuples can be referenced using attributestreet CHAR(501, ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY3,4) LAXGU-AGES incolor BOOLEAN 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA c) MarriageType,455 with the date of the marriage and references to the hus- Fig. 9.1 FiguremovieID 9.11: (system Creating agenerated) referenceable table city CHAR(20) tables PC, Laptop, and Printer could be references to tuples of the Product To begin, note that the type of an address in 1 ;is itself a tuple, band and wife. with components street and city. Thus, we need two type definitions, one 1 table. Is it also possible to make the model attribute in Product a reference to * b) PersonType, with a name of the person and referencesthe tupleto the in persons the relation that for that type of product? Why or why not? ( METHOD houseNumber () RETURNSExercise CHAR(^^) 9.4.2: ; Redesign our running products database schema of Exer- for 1)addresses CREATE and TYPE the MovieType other for stars.AS The necessaryGENERATED" definitions5) CREATE by are "DERIVED," TABLE shown Movie in then OF new MovieType tuples would ( getare their their value mother of movieIDand father. You must use the type from part (a) in your Fig.2 9.10. title CHAR(30) , REF IS movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes where appropriate. by some6) calculation, performed by the system, on the declaration.valuesWe of see the the primary-key keyword METHOD, follon-ed by the* Exercisename of the 9.4.4: method Redesign and a ourparnithe- running battleships database schema of Exer- year INTEGER, attributes7) titlePRIMARY and year KEY from(title, the same year) tuple. In particular, in the relations PC: Laptop, and Printer make the model at- sized list of its arguments and their types. Incise this 5.2.4 case, to usethere type are declarations no arguments, and reference attributes where appropriate. 3,4) incolor BOOLEAN 1; c) MarriageType, with the date of the marriage andThe tributereferences schema be toa from reference the Exercisehus- to the 9.1.3 Product should tuplesuggest for where that model.reference attributes are butDefine the parentheses primary keyare still needed. Had there bee11 arguments, they would CREATE1 ; TYPE AddressType AS ( Example 9.25 : Now, let us see how to represent theband many-many and wife. relationship useful. Look for many-one relationships and try to represent them using an have appeared, follo~vedby their types. such! Exercise as (a INT, 9.4.3: b CHAR(^)).In Exercise 09.4.2 we suggested that model numbers in the street CHAR(~O), between moviesCreate and stars Movie using tablereferences. Previously, we represented this attribute with a reference type. 5) CreateCREATEcity TABLEtypeCHAR(20) Moviefor movies OF MovieType ( relationship by aFigure relation 9.11: like Creating StarsIn a thatreferenceable containsExercise tuplestable 9.4.2: with Redesignthe keys ourof running products databasetables schema PC, Laptop, of Exer- and Printer could be references to tuples of the Product cise 5.2.1 to useSeparately, type declarations we need andto define reference the attributesmetliod.table. -1where simple Is itappropriate. also form possible of method to make defini- the model attribute in Product a reference to 6) ); REF IS movieID SYSTEM GENERATED, Movie and MovieStar. As an alternative, we may define StarsIn to have references to tuples from these-two relations. In particular,tion inconsists the relations of: PC: Laptop, and Printerthe make tuple the in modelthe relation at- for that type of product? Why or why not? 7) PRIMARY KEY (title, year) GENERATED" by "DERIVED," then new tuples would get their value of movieID 9.5 Operations on Object-Relational Data First, we need to redefine MovieStar so it is tributea referenceable be a reference table, thusly:to the Product tuple for that model. CREATE1; TYPE StarType AS ( by some calculation, performed by the system, on the values of1. the The primary-key keywords CREATE METHOD. * -111Exercise appropriate 9.4.4: SQL Redesign operations our from running previous battleships chapters databaseapply to tablesschema that of areExer- name CHAR(30) , attributesCREATE title TABLE and yearMovieStar from the OF sameStarType tuple.! Exercise ( 9.4.3:Referenceable, In Exercise 9.4.2 but nowe suggested that declaredmodelcise 5.2.4 numbers with to usea UDTin type the or declarations that have attributes and reference whose attributes type is a whereCDT. Thereappropriate. are addressFigure AddressType 9.11: Creating a referenceable table REF IS starID SYSTEM GENERATED tables PC, Laptop,primary2. The and method key Printer name. could arguments be references and totheir alsotuplesThe sometypes, schema of entirelythe and fromProduct the new Exercise RETURNS operations 9.1.3 clause, we should can use, suggest such aswhere reference-follo~ving. reference attributesHow- are Example 9.25 : Now, let us see how to represent the many-many relationship ); 1; table. Is it also possibleas in the to declaration make the model of the attribute method. in ever,Productuseful. some Looka familiarreference for many-oneoperations. to relationships especially those and that try accessto represent or modify them columns using an between movies and stars using references. Previously, we represented this the tuple in the relation for that type of product? Why \\-hoseorattribute why type not? with is a UDT,a reference involve type. new syntax. GENERATED"Create by "DERIVED," type for then stars new tuples would get theirrelationship valueThen,Create ofwe by movieID maya relation declareMovieStar like the StarsInrelation table StarsInthat contains to have tuples two 3.attributes, with The the keyword keys ~vhich of FOR and43 tlic name of the UDT in which the method is by some calculation, performedFigure by 9.10: the system, Two type on the definitions valuesMovieare of references, theand primary-key MovieStar. one to a Asmovie an tuplealternative, and one we* to Exercise maya star define tuple. 9.4.4: StarsIn Heredeclarcd. Redesign is toa direct have our running battleships database schema of Exer- attributes title and year from the same tuple. referencesdefinition to of tuples this relation: from these-two relations. cise 5.2.4 to use type declarations and reference attributes9.5.19.5 where FollowingOperations appropriate. References on Object-Relational Data First, we need to redefine MovieStar so it is aThe referenceable schema from4. table,The Exercise body thusly: 9.1.3of the should method. suggest \vhich where is ~vrittcnreferenceSupposein xattributes theis a samevalue are oflanguage type REF(T). as the Then x refers to some tuple t of type T. Exampleh tuple 9.25 of : Now,type letAddressType us see how to has represent two components, the many-many whoseCREATE relationship attributes TABLE StarsIn are ( useful. Look forbodies many-one of PSJI relationships functions. and try to representWe-111 can appropriate obtain them usingtuple SQL ant operationsitself, or components from previous of t: chaptersby two means: apply to tables that are betweenstreet movies and city. and Thestars types using of references. these components Previously, are characterwe CREATErepresented starstrings TABLE this ofMovieStarREF(StarType1 length OF StarTypeSCOPE MovieStar, ( declared with a UDT or that have attributes whose type is a CDT. There are 50 and 20, respectively. A tuple of type StarType also has tn-o components. attribute with a reference type. relationship by a relation like StarsIn that contains tuples with REFthemovie keysIS starID ofREF(MovieType1 SYSTEM GENERATED SCOPE Movie For instance, we could define the method houseNumberalso1. someOperator entirely from -> has newExample essentially operations 9.21 the weas: same can use,meaning such as as this reference-follo~ving. operator does in C.How- MovieThe firstand isMovieStar. attribute name,As an whose alternative, type is awe 30-character may define string, StarsIn1;1; and to the have second is ever,That some is, familiar if x is operations.a reference to especially a tuple thoset. and that a is accessan attribute or modify of t, columns then referencesaddress, to whose tuples type from is these-two itself a UDTrelations. AddressType. that is, a tuple with street 9.5 OperationsCREATE METHOD on Object-Relational houseNmber RETURNS\\-hose x->a CHARData type is (10) isthe a UDT,value ofinvolve the attribute new syntax. n in tuple t. Optionally, we could have defined a UDT as above, and then declared StarsIn andFirst, city we components.need to redefine C] MovieStar so it is a referenceableThen, table, we maythusly: declare the relation StarsIn to have two attributes,FOR AddressType ~vhich areto references, be a table ofone that to atype. movie tuple and one to a star tuple. Here is a direct 2. The DEREF operator applies to a reference and produces the tuple refer- -111 appropriate SQL operations from previous chapters apply9.5.1 to tablesFollowing that are References CREATE TABLE MovieStar OF StarType ( definition of this relation: declared with a UDT or that have attributes whose type is aenced. CDT. There are REF IS starID SYSTEM GENERATED 9.4.5 Exercises for Section 9.4 also some entirely new operations we can use, such as reference-follo~ving.Suppose x is a valueHow- of type REF(T). Then x refers to some tuple t of type T. CREATE TABLE StarsIn ( Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 1; ever, some familiar operations. especially those that accessWe orcan modify obtain columns tuple t itself, or components of t: by two means: Exercise 9.4.1 : Write type declarations for the following types: star REF(StarType1 SCOPE MovieStar,\\-hose type is a UDT, involve new syntax. the movies in which JIel Gibson starred. Recall that the schema is Then, we may declare the relation StarsIn to have two attributes,movie ~vhich REF(MovieType1 SCOPE Movie 1. Operator -> has essentially the same meaning as this operator does in C. are references, one to a movie tuple and one to a star tuple.a) 1; HereNameType, is a direct with components for first, middle, and last names and a title. StarsIn(star, movie) 9.5.1 Following References That is, if x is a reference to a tuple t. and a is an attribute of t, then definition of this relation: x->a is the value of the attribute n in tuple t. Optionally, we could have defined a UDT as above, and then declared StarsIn Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. CREATE TABLE StarsIn ( to be a table of that type. We can obtain tuple t itself, or components of t: by two means:2. The DEREF operator applies to a reference and produces the tuple refer- star REF(StarType1 SCOPE MovieStar, enced. movie REF(MovieType1 SCOPE Movie 9.4.5 Exercises for Section 9.4 1. Operator -> has essentially the same meaning as this operator does in C. Example 9.26: StarsIn 1; That is, if x is a reference to a tuple t. and a is an attribute of t, thenLet us use the relation from Example 9.25 to find Exercise 9.4.1 : Write type declarations for the following types: x->a is the value of the attribute n in tuple t. the movies in which JIel Gibson starred. Recall that the schema is Optionally, we could have defined a UDT as above, and then declared StarsIn to be a table of that type. a) NameType, with components for first, middle,2. and The last DEREF names operator and a title.applies to a reference and produces StarsIn(star,the tuple refer- movie) enced. 9.4.5 Exercises for Section 9.4 Example 9.26: Let us use the relation StarsIn from Example 9.25 to find Exercise 9.4.1 : Write type declarations for the following types: the movies in which JIel Gibson starred. Recall that the schema is

a) NameType, with components for first, middle, and last names and a title. StarsIn(star, movie) 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 1) CREATE TYPE MovieType AS ( are their mother and father. You must use the type from part (a) in your 2 title CHAR(30) , declaration. year INTEGER, 3,4) incolor BOOLEAN c) MarriageType, with the date of the marriage and references to the hus- 1 ; band and wife.

5) CREATE TABLE Movie OF MovieType ( Exercise 9.4.2: Redesign our running products database schema of Exer- 6) REF IS movieID SYSTEM GENERATED, cise 5.2.1 to use type declarations and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular, in the relations PC: Laptop, and Printer make the model at- 1; tribute be a reference to the Product tuple for that model. ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the Figure 9.11: Creating a referenceable table tables PC, Laptop, and Printer could be references to tuples of the Product table. Is it also possible to make the model attribute in Product a reference to the tuple in the relation for that type of product? Why or why not? GENERATED" by "DERIVED," then new tuples would get their value of movieID by some calculation, performed by the system, on the values of the primary-key * Exercise 9.4.4: Redesign our running battleships database schema of Exer- attributes title and year from the same tuple. cise 5.2.4 to use type declarations and reference attributes where appropriate. The schema from Exercise 9.1.3 should suggest where reference attributes are DEFINING RELATIONSHIPSExample 9.25 : Now, let us see how to represent the many-many relationship useful. Look for many-one relationships and try to represent them using an between movies and stars using references. Previously, we represented this attribute with a reference type. relationship by a relation like StarsIn that contains tuples with the keys of Movie and MovieStar. As an alternative, we may define StarsIn to have 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED TYPES IAr SQL references453 to tuples from these-two relations. 9.5 Operations on Object-Relational Data • One-to-many Or one-to-oneFirst, we need to redefine MovieStar so it is a referenceable table, thusly: BEGIN • Plug it Ainside REF(T) SCOPEthe Rexisting types -111 appropriate SQL operations from previous chapters apply to tables that are . . . CREATE TABLE MovieStar OF StarType ( If no scope is specified, the reference can go to any relation of type T declared with a UDT or that have attributes whose type is a CDT. There are END ; REF IS starID SYSTEM GENERATED also some entirely new operations we can use, such as reference-follo~ving.How- \Ve have omitted the body of the method because accomplishing the intended ExampIe• 9.23 Many-to-many : Reference attributes are not sufficient to record in MovieStar1; ever, some familiar operations. especially those that access or modify columns separation of the string string as intended is nontrivial, even in PSM. the set of all movies they starred in, but they let us record the best movie for \\-hose type is a UDT, involve new syntax. each star. Assume• Createthat we have adeclared new a relationtype Movie, or new and that table theThen, type ofreferencingwe may declare the existing relation StarsIn types to have two attributes, ~vhich this relation is the UDT MovieType; we shall define both MovieType and Movie 9.4.3 Declaring Relations with a UDT are references, one to a movie tuple and one to a star tuple. Here is a direct later, in Fig. 9.11. The following is a new definition of StarType that includes 9.5.1 Following References Having declared a type, we may declare one or more relations whose tuples are a11 attribute bestMovie that is a reference to a movie. definition of this relation: of that type. The form of relation declarations is like that of Section 6.6.2, but Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. ( CREATE TABLE StarsIn ( we use CREATE TYPE StarType AS We can obtain tuple t itself, or components of t: by two means: name CHAR(30) , star REF(StarType1 SCOPE MovieStar, address AddressType, movie REF(MovieType1 SCOPE Movie bestMovie REF(MovieType) SCOPE Movie 1. Operator -> has essentially the same meaning as this operator does in C. in place of the list of attribute declarations in a normal SQL table declaration. 1; ; That is, if x is a reference to a tuple t. and a is an attribute of t, then Other elements of a table declaration, such as keys, foreign keys, and tuple- > Table for each star participated in x->a is the value of the attribute n in tuple t. based constraints, may be added to the table declaration if desired, and apply Sow, if Forrelation each MovieStar star, keepis defined the to have the UDT above, thenOptionally, each star we could have defined a UDT as above, and then declared StarsIn which movies (many-many) only to this table, not to the UDT itself. tuple willbest have movie a component (one-many) that refers to a Movie tuple - theto star's be a besttable of that type. 2. The DEREF operator applies to a reference and produces the tuple refer- movie. Example 9.22 : We could declare MovieStar to be a relation whose tuples enced. were of type StarType by Sest, n-e must arrange that a table such as Movie in Example 9.239.4.5 will haveExercises for Section 9.4 a reference column. Such a table is said to be referenceable. In a CREATE TABLE Example 9.26: Let us use the relation StarsIn from Example 9.25 to find CREATE TABLE MovieStar OF StarType; statement n-here the type of the table is a UDT (as in SectionSCOPE 9.4.3),Exercise wepoints may 9.4.1 to a : ‘referenceable’ Write type declarations table for the following types: the movies in which JIel Gibson starred. Recall that the schema is As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: attribute, name, is an ordinary character string, but the second, address. has a) NameType, with components for first, middle, and last names and a title. StarsIn(star, movie) a type that is itself a UDT, namely the type AddressType. REF IS tattribute name>

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

• Second Approach: Object-Relational Model • Conceptual view • Data Definition Language (Creating types, tables, and relationships) • Querying object-relational database (SQL-99)

45 QUERYING OBJECT-RELATIONAL DATABASE

• Most relational operators work on the object- relational tables • E.g., selection, projection, aggregation, set operations

• Some new operators and new syntax for some existing operators

• SQL-99 (SQL3): Extended SQL to operate on object- relational databases

46 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGES are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your 455 2 title CHAR(30) , declaration. year INTEGER, * b) PersonType, with a name of the person and references to the persons that 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS ( c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your 2 1 ; title CHAR(30) , band anddeclaration. wife. year INTEGER, EXAMPLES I 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 454 5) 3,4) CREATECHAPTER incolor TABLE 9. Movie OBJECT-ORIENTATIONBOOLEAN OF MovieType ( IN QUERY LAXGU-AGES Exercise9.5. c)9.4.2: MarriageType, OPERATIONS Redesign our with ON running the OBJECT-RELATIONAL date products of the databasemarriage schemaand DATA references of Exer- to the hus- 455 6) 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema of Exer- 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( 453 tribute be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your 2 1; title CHAR(30) , Q1: Find the year of moviecise ‘King5.2.1 to Kong’ use type declarations and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, declaration.declaration. 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the model at- A REF(T) SCOPE R BEGIN 3,4) 3,4) 1; incolorFigureincolor 9.11: BOOLEAN BOOLEAN Creating a referenceable table tables PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus- . . . 1 ;1 ; Select m.year table. Is it alsoband bandpossible andand to wife. wife.make the model attribute in Product a reference to END ; If no scope is specified, the reference can go to any relation of type T ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the the tuple in the relation for that type of product? Why or why not? Figure Creating a referenceable table From Movie m tablesExercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema of Exer- \Ve have omitted the body of the method because accomplishing the intended table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movieWhere for m.title *= Exercise ‘Kingcise 9.4.4:Kong’; 5.2.1 Redesign to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. separation of the string string as intended is nontrivial, even in PSM. theIn tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type of cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType and Movie tribute be a reference to the Product tuple for that model. 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-key The schema* Exercise from Exercise9.4.4: Redesign 9.1.3 should our suggestrunning where battleships reference database attributes schema are of Exer- Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship that includes attributes title and year from the same tuple. Variable m is importantuseful. !cise !to LookExercise Exercise reference5.2.4 for many-oneto 9.4.3: use9.4.3: typethe relationshipsIn In fieldsdeclarations Exercise Exercise 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. in the Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of useful.table.table. Is LookIs itit also alsofor possible many-onepossible toto relationships makemake thethe modelmodel and attributeattributetry to represent inin ProductProduct them a usingreferencereference an to we use Moviebetween andCREATE moviesMovieStar. TYPE and StarType starsAs an using alternative, AS references.( we may Previously, define StarsIn we represented to have this name CHAR(30) , attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieID of 9.5 Operations on Object-Relational Data address AddressType, Q2: Find the title of the best movie ’Jim Carry’ byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to have Exercise 9.4.4: Redesign our running battleships database schema of Exer- bestMovie REF(MovieType) SCOPE Movie ** Exercise 9.4.4: Redesign our running battleships database schema of Exer- in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. -111 appropriate9.5cisecise 5.2.45.2.4 SQLOperations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. CREATE> ; TABLE MovieStar OF StarType ( Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly:Select s.bestMoviedeclared->title ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationship relationship -111 appropriate SQL operations from previous chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There are only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented star'sFrom best this MovieStar ever,s someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys of also some entirely new operations we can use, such as reference-follo~ving.How- movie.relationship by a relation like StarsIn that contains tuples with theWhere keys of s.name =\\-hose ‘Jim type Carry’; is a UDT, involve new syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhich to to have have ever, some familiar operations. especially those that access or modify columns were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a direct \\-hose type is a UDT, involve new syntax. referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have 9.59.5 OperationsOperations onon Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly: 9.5.1 Following References a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, is athusly: TABLEdirect CREATE TABLE MovieStar OF StarType; -111-111 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( declared with a or that have attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We canFollow obtaindeclared atuple reference with t itself, a UDTUDT or (pointer)components or that have of t:attributes by two means: whose type is a CDT. There are starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( usingalsoalso some àsome operator entirely entirely new new operationsoperations wewe cancan use,use, suchsuch asas reference-follo~ving.reference-follo~ving.How- movie REF(MovieType1 SCOPE Movie We can obtain tuple t itself, or components of t: by two means: a type that is itself a UDT, namely the type AddressType. 1;1; starREF REF(StarType1IS tattribute name> SCOPE has familiar familiar essentially operations.operations. the same especiallymeaning especially as those thosethis operator thatthat accessaccess does orinor C.modifymodify columns 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. movie REF(MovieType1 SCOPE Movie That1. is, Operator if x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 47 1; x->a is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared StarsIn 2. The DEREF operator applies to a reference and produces the tuple refer- 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. enced.SupposeSuppose2. The xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype T. CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, 2. DERIVED. lneaning that the DBMS will use the primary key of the relation Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: the moviesExample in1.1. which OperatorOperator 9.26: JIel Gibson ->Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25 todoes find in C. through the notion of a reference. Tables whose type is a UDT may have Exercise1;1; 9.4.1 : Write type declarations for the following types: the moviesThatThat in is, is,which ifif xx JIelisis aa Gibsonreferencereference starred. toto aa tupletupleRecall t.t. that andand theaa isis schema anan attributeattribute is of t,t, then a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, enced. types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attribute of type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a title. anytitle. StarsIn(star,StarsIn(star, movie)movie) a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGES are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your 455 2 title CHAR(30) , declaration. year INTEGER, * b) PersonType, with a name of the person and references to the persons that 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS ( c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your 2 1 ; title CHAR(30) , band anddeclaration. wife. yearEXAMPLES INTEGER, II: DE-REFERENCING 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 454 5) 3,4) CREATECHAPTER incolor TABLE 9. Movie OBJECT-ORIENTATIONBOOLEAN OF MovieType ( IN QUERY LAXGU-AGES Exercise9.5. c)9.4.2: MarriageType, OPERATIONS Redesign our with ON running the OBJECT-RELATIONAL date products of the databasemarriage schemaand DATA references of Exer- to the hus- 455 6) 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema of Exer- 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( 453 tribute be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your 2 1; title CHAR(30) , Q3: Find movies starred bycise ‘Jim5.2.1 to Carry’ use type declarations and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, declaration.declaration. 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the model at- A REF(T) SCOPE R BEGIN 3,4) 3,4) 1; incolorFigureincolor 9.11: BOOLEAN BOOLEAN Creating a referenceable table tables PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus- . . . 1 ;1 ; Select DEREF(movie)table. Is it alsoband bandpossible andand to wife. wife.make the model attribute in Product a reference to END ; If no scope is specified, the reference can go to any relation of type T ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the the tuple in the relation for that type of product? Why or why not? Figure Creating a referenceable table From StarsIn tablesExercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema of Exer- \Ve have omitted the body of the method because accomplishing the intended table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movieWhere for star->name* Exercise =cise 9.4.4:‘Jim 5.2.1 RedesignCarry’; to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. separation of the string string as intended is nontrivial, even in PSM. theIn tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type of cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType and Movie tribute be a reference to the Product tuple for that model. 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-key The schema* Exercise from Exercise9.4.4: Redesign 9.1.3 should our suggestrunning where battleships reference database attributes schema are of Exer- Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship that includes attributes title and year from the same tuple. DEREF: Get the tupleuseful. pointed !cise! LookExercise Exercise 5.2.4 forto many-onetoby 9.4.3: use9.4.3: the type given relationshipsInIn declarations Exercise Exercise pointer 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. in the Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of useful.table.table. Is LookIs itit also alsofor possible many-onepossible toto relationships makemake thethe modelmodel and attributeattributetry to represent inin ProductProduct them a usingreferencereference an to we use Moviebetween andCREATE moviesMovieStar. TYPE and StarType starsAs an using alternative, AS references.( we may Previously, define StarsIn we represented to have this name CHAR(30) , attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieID of 9.5 Operations on Object-Relational Data address AddressType, Q4: Find movies starred by ‘Jim Carry’ (Another way) byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to have Exercise 9.4.4: Redesign our running battleships database schema of Exer- bestMovie REF(MovieType) SCOPE Movie ** Exercise 9.4.4: Redesign our running battleships database schema of Exer- in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. -111 appropriate9.5cisecise 5.2.45.2.4 SQLOperations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. CREATE> ; TABLE MovieStar OF StarType ( Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly: declared ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationshipSelect relationship s.movie ->title, s.movie-111 appropriate->year, SQL s.movie operations->inColor from previous, chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There are only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented Fromstar's best thisStarsIn s ever, someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys of also some entirely new operations we can use, such as reference-follo~ving.How- movie.relationship by a relation like StarsIn that contains tuples with the keys of \\-hose type is a UDT, involve new syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhichWhere to to have have s.star ->name = ever,‘Jim some Carry’; familiar operations. especially those that access or modify columns were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a direct \\-hose type is a UDT, involve new syntax. referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have 9.59.5 OperationsOperations onon Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly: 9.5.1 Following References a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, is athusly: TABLEdirect CREATE TABLE MovieStar OF StarType; -111-111 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( *** Using a variable fordeclared StartsIn with a (s inor Q4) that have is not attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We can obtaindeclared tuple with t itself, a UDTUDT or components or that have of t:attributes by two means: whose type is a CDT. There are starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( necessary because thealso alsotable some some entirely isentirely not new new based operationsoperations on wewe type. cancan use,use, suchsuch asas reference-follo~ving.reference-follo~ving.How- movie REF(MovieType1 SCOPE Movie We can obtain tuple t itself, or components of t: by two means: a type that is itself a UDT, namely the type AddressType. 1;1; starREF REF(StarType1IS tattribute name> SCOPE has familiar familiar essentially operations.operations. the same especiallymeaning especially as those thosethis operator thatthat accessaccess does orinor C.modifymodify columns 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. movie REF(MovieType1 SCOPE Movie That1. is, Operator if x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 48 1; x->a is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared StarsIn 2. The DEREF operator applies to a reference and produces the tuple refer- 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. enced.SupposeSuppose2. The xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype T. CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, 2. DERIVED. lneaning that the DBMS will use the primary key of the relation Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: the moviesExample in1.1. which OperatorOperator 9.26: JIel Gibson ->Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25 todoes find in C. through the notion of a reference. Tables whose type is a UDT may have Exercise1;1; 9.4.1 : Write type declarations for the following types: the moviesThatThat in is, is,which ifif xx JIelisis aa Gibsonreferencereference starred. toto aa tupletupleRecall t.t. that andand theaa isis schema anan attributeattribute is of t,t, then a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, enced. types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attribute of type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a title. anytitle. StarsIn(star,StarsIn(star, movie)movie) a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGES are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your 455 2 title CHAR(30) , declaration. year INTEGER, * b) PersonType, with a name of the person and references to the persons that 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS ( c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your 2 1 ; title CHAR(30) , band anddeclaration. wife. year EXAMPLESINTEGER, III: COMPARISON 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 454 5) 3,4) CREATECHAPTER incolor TABLE 9. Movie OBJECT-ORIENTATIONBOOLEAN OF MovieType ( IN QUERY LAXGU-AGES Exercise9.5. c)9.4.2: MarriageType, OPERATIONS Redesign our with ON running the OBJECT-RELATIONAL date products of the databasemarriage schemaand DATA references of Exer- to the hus- 455 6) 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema of Exer- 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( 453 tribute be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your 2 1; title CHAR(30) , Q5: Find distinct movies starredcise 5.2.1 toby use ‘Jim type declarationsCarry’ and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, declaration.declaration. 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) or ‘Mel Gibson’ ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the model at- A REF(T) SCOPE R BEGIN 3,4) 3,4) 1; incolorFigureincolor 9.11: BOOLEAN BOOLEAN Creating a referenceable table tables PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus- . . . 1 ;1 ; table. Is it alsoband bandpossible andand to wife. wife.make the model attribute in Product a reference to END ; If no scope is specified, the reference can go to any relation of type T ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the Select Distinct DEREF(movie)the tuple in the relation for that type of product? Why or why not? Figure Creating a referenceable table tablesExercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema of Exer- \Ve have omitted the body of the method because accomplishing the intended From StarsIn table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movie for * Exercisecise 9.4.4: 5.2.1 Redesign to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. separation of the string string as intended is nontrivial, even in PSM. theIn tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the typeWhere of star->namecise 5.2.4 = In to‘Jim useparticular, type Carry’ declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType and Movie tribute be a reference to the Product tuple for that model. 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-keyOr star->name The= ‘Mel schema* Exercise Gibson’;from Exercise9.4.4: Redesign 9.1.3 should our suggestrunning where battleships reference database attributes schema are of Exer- Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship that includes attributes title and year from the same tuple. useful. !cise! LookExercise Exercise 5.2.4 for many-oneto 9.4.3: use9.4.3: type relationshipsInIn declarations Exercise Exercise 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. in the Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of useful.table.table. Is LookIs itit also alsofor possible many-onepossible toto relationships makemake thethe modelmodel and attributeattributetry to represent inin ProductProduct them a usingreferencereference an to we use Moviebetween andCREATE moviesMovieStar. TYPE and StarType starsAs an using alternative, AS references.( we may Previously, define StarsIn we represented to have this name CHAR(30) , attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieID of 9.5 Operations on Object-Relational Data address AddressType, byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to have Exercise 9.4.4: Redesign our running battleships database schema of Exer- bestMovie REF(MovieType) SCOPE Movie • That is wrong because** Exercise all objects9.4.4: Redesign of typeour running battleships database schema of Exer- in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. -111 appropriate9.5cisecise 5.2.45.2.4 SQLOperations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. CREATE> ; TABLE MovieStar OF StarType ( MovieType are unique even if they have the Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly: declared ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationship relationship -111 appropriate SQL operations from previous chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then eachsame star content also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There are only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented star's best this ever, someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys of also some entirely new operations we can use, such as reference-follo~ving.How- movie.relationship by a relation like StarsIn that contains tuples with the keys of \\-hose type is a UDT, involve new syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhich• to toNeed have have a mechanismever, to some define familiar howoperations. objects especially those that access or modify columns were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a direct \\-hose type is a UDT, involve new syntax. referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have 9.59.5 OperationsOperations onon Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly:compare to each9.5.1 otherFollowing References a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, is athusly: TABLEdirect CREATE TABLE MovieStar OF StarType; -111-111 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we (needed may for anySuppose comparison,9.5.1 x is a valueFollowing of type e.g., REF(T). References ordering, Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( declared with a or that have attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We can obtaindeclared tuple with t itself, a UDTUDT or components or that have of t:attributes by two means: whose type is a CDT. There are starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, duplicate elimination,Suppose grouping, x is a value of typeetc.) REF(T). Then x refers to some tuple t of type T. attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( alsoalso some some entirely entirely new new operationsoperations wewe cancan use,use, suchsuch asas reference-follo~ving.reference-follo~ving.How- movie REF(MovieType1 SCOPE Movie We can obtain tuple t itself, or components of t: by two means: a type that is itself a UDT, namely the type AddressType. 1;1; starREF REF(StarType1IS tattribute name> SCOPE has familiar familiar essentially operations.operations. the same especiallymeaning especially as those thosethis operator thatthat accessaccess does orinor C.modifymodify columns 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. movie REF(MovieType1 SCOPE Movie That1. is, Operator if x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 49 1; x->a is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared StarsIn 2. The DEREF operator applies to a reference and produces the tuple refer- 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. enced.SupposeSuppose2. The xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype T. CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, 2. DERIVED. lneaning that the DBMS will use the primary key of the relation Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: the moviesExample in1.1. which OperatorOperator 9.26: JIel Gibson ->Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25 todoes find in C. through the notion of a reference. Tables whose type is a UDT may have Exercise1;1; 9.4.1 : Write type declarations for the following types: the moviesThatThat in is, is,which ifif xx JIelisis aa Gibsonreferencereference starred. toto aa tupletupleRecall t.t. that andand theaa isis schema anan attributeattribute is of t,t, then a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, enced. types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attribute of type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a title. anytitle. StarsIn(star,StarsIn(star, movie)movie) a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM ORDERING RELATIONSHIPS

• Need to define how to compare objects of a given type T

Equality or non-equality (=, ≠) Identical content EQUALS ONLY BY STATE; Create Ordering For T BY RELATIVE WITH F; ORDERING FULL User-defined function F(O1, O2) and Full comparison (=, <, >, ≤, ≥, ≠) returns 0, -ve, +ve

50 460 CHAPTER 9. OBJECT-ORIENT-4TION IN QUERY LANGUAGES 9.6. SUMMARY OF CHAPTER 9 461

CREATE ORDERING FOR AddressType EQUALS ONLY BY STATE; ! d) Find the movies (title and year) with at least five stars. 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES460 CHAPTER 9. OBJECT-ORIENT-4TION9.5. OPERATIONS ON OBJECT-RELATIONAL IN QUERY LANGUAGES DATA 455 9.6. SUMMARY OF CHAPTER 9 461 Alternatively, we could define a conlplete ordering of AddressType objects. Exercise 9.5.2: Using your schema from Exercise 9.4.2, write the following One reasonable ordering is to order* b) PersonType, addresses first with by a namecities, of alphabetically, the person and referencesand to the persons that queries. Don't forget to use references whenever appropriate. 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGESamong addressesCREATE inORDERING the same city, FOR byare 9.5.AddressTypestreet their OPERATIONS address,mother and alphabetically. EQUALS father. ON OBJECT-RELATIONALYou ONLY must To do BYuse so, theSTATE; I{-e type from DATA part (a) in your 455 ! d) Find the movies (title and year) with at least five stars. 2 title CHAR(30) , have to define a function, say AddrLEG,declaration. that takes two AddressType arguments a) Find the manufacturers of PC's with a hard disk larger than 60 gigabytes. year INTEGER, Alternatively, we could define a conlplete ordering of AddressType objects. Exercise 9.5.2: Using your schema from Exercise 9.4.2, write the following and returns a negative, zero, or positive* b) valuePersonType, to indicate with thata name the of first the isperson less and references to the persons that 4) 1) CREATE TYPE MovieType AS ( One reasonable ordering is to order addresses first by cities, alphabetically, and b) Find the manufacturers of laser printers. 3, incolor BOOLEAN than, equal to, or greater than thec) MarriageType, second.are We their declare: with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your queries. Don't forget to use references whenever appropriate. 2 1 ; title CHAR(30) , among addresses in the same city,band andby streetwife. address, alphabetically. To do so, I{-e ORDERING FUNCTIONdeclaration. ! c) Produce a table giving for each model of laptop, the model of the lap- year INTEGER, haveCREATE to define ORDERING a function, FOR AddressType say AddrLEG, that takes two AddressType arguments a) Find the manufacturers of PC's with a hard disk larger than 60 gigabytes. 454454 3,4)CHAPTER CHAPTERincolor 9. 9. OBJECT-ORIENTATION OBJECT-ORIENTATIONBOOLEAN IN IN QUERY QUERY LAXGU-AGES LAXGU-AGES Exercise9.5.9.5. c)9.4.2: MarriageType, OPERATIONSOPERATIONS Redesign our with ON ON running the OBJECT-RELATIONALOBJECT-RELATIONAL date products of the databasemarriage schemaand DATADATA references of Exer- to the hus-top455 having the highest processor speed of any laptop made by the same 5) CREATE TABLE Movie OF MovieType ( and ORDERreturns FULL a negative, BY RELATIVE zero, WITH or positiveAddrLEG; value to indicate that the first is less 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. manufacturer. b) Find the manufacturers of laser printers. 6) than, equal to, or greater than the second. We declare: 7) PRIMARY KEY (title, year) The function AddrLEG is shownIn particular, in Fig.** b)b) 9.13. inPersonType,PersonType, the Notice relations that with with PC: if a weaLaptop, namename reach of ofand line thethe Printer person(7),person and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema ofExercise Exer- 9.5.3: Using your schema from Exercise 9.4.4, write the following 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( it must 453be that the two citytribute components be a referenceare areare their their the to motherthemothersame, Product so andand we father.tuplefather. compare for YouYou that the mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your ! c) Produce a table giving for each model of laptop, the model of the lap- 2 1; title CHAR(30) , CREATE ORDERING ciseAddressType 5.2.1 to use type declarations and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, street components. Likewise,FOR if we reachdeclaration. declaration.line (9), the only remaining possi- queries. Don't forget to use references whenever appropriate and avoid joins year INTEGER, In particular, in the relations PC: Laptop, and Printer make the model at- top having the highest processor speed of any laptop made by the same 7) PRIMARYyear KEYINTEGER, (title, year) bility is ORDERthat the FULL cities BYare RELATIVE!the Exercise same and 9.4.3: WITH the InfirstAddrLEG; Exercise street 9.4.2precedes we suggested the second that model numbers in the (i.e., subqueries or more than one tuple variable in the FROM clause). BEGIN 3,4) 3,4) incolorincolor BOOLEAN BOOLEANA REF(T) SCOPE R tributec)c) MarriageType,beMarriageType, a reference to with with the theProductthe datedate tupleofof thethe for marriagemarriage that model. andand referencesreferences toto thethe hus- manufacturer. 1; Figure 9.11: Creating a referenceable table alphabetically. 13 tables PC, Laptop, and Printer could be references to tuples of the Product . . . 1 ;1 ; The function AddrLEGtable. is shown Is it also inband bandpossible Fig. andand 9.13. to wife. wife.make Notice the model that attribute if we reach in Product line (7),a reference to * a) Find the ships with a displacement of more than 35,000 tons. END ; If no scope is specified, the reference can go to any relation of type T ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the 9.5.3: thecity tuple in the relation for that type of product? Why or why not? Exercise Using your schema from Exercise 9.4.4, write the following Figure Creating a referenceable table it must be that the two tablesExercisecomponents PC, Laptop, 9.4.2: are andRedesign the Printer same, our could runningso webe references compare products to databasethe tuples of schema the Product ofb) Exer-Find the battles in which at least one ship was sunk. GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema of Exer- queries. Don't forget to use references whenever appropriate and avoid joins \Ve have omitted the body of the method because accomplishing the intended street components. Likewise,table.cise if we 5.2.1Is itreach alsoto use possible line type (9), declarationsto makethe onlythe modeland remaining reference attribute attributespossi- in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movie 1) forCREATE FUNCTION* ExerciseAddrLEGcise (9.4.4: 5.2.1 Redesign to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. FROM separation of the string string as intended is nontrivial, even in PSM. bility is that the cities are thetheIn same tupleparticular, inand the the inrelation the first relations for street that typePC: precedes Laptop, of product? theand secondWhyPrinter or why make not? the model! c) Find at- the classes(i.e., that subqueries had ships launched or more after than 1930. one tuple variable in the clause). attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type2) of x1 AddressType,cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType andalphabetically. Movie3) x2 AddressType13 tribute be a reference to the Product tuple for that model. !! d) Find the battles in n-hich at least one US ship was damaged. 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-key The schema* Exercise from Exercise9.4.4: Redesign 9.1.3 should our suggestrunning where battleships reference database attributes schema are of Exer- * a) Find the ships with a displacement of more than 35,000 tons. Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship that includes 4) ) RETURNS INTEGER attributes title and year from the same tuple. useful. !cise! LookExercise Exercise 5.2.4 for many-oneto 9.4.3: use9.4.3: type relationshipsInIn declarations Exercise Exercise 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. in the Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this Exercise 9.5.4 : Assuming the function AddrLEG of Fig. 9.13 is available, write FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are b) Find the battles in which at least one ship was sunk. of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of 5) IF xl.city() < x2.cityOuseful. THEN Look RETURN(-1) for many-one relationships and try to represent them usinga suitable an function to compare objects of type StarType, and declare your CREATE TYPE StarType AS ( 1) CREATE FUNCTION AddrLEGtable.table. IsIs it(it alsoalso possible possible toto makemake thethe modelmodel attributeattribute inin ProductProduct a referencereference to we use Moviebetween and moviesMovieStar. and starsAs an using alternative, references. we may Previously, define StarsIn we represented to have 6) this ELSEIF xl.city() > x2.cityO THEN RETURN(1) function to be the basis! c) of Findthe ordering the classes of StarType that had objects. ships launched after 1930. name CHAR(30) , 2) x1 AddressType,attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieID7) ofELSEIF xl. street9.5 () < x2.Operations street () THEN on RETURN(-1) Object-Relational Data address AddressType, *! Exercise 9.5.5 : Write a procedure to take a star name as argument and delete byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to 8) have 3) ELSEIF xl.street()x2 AddressType = *x2.streetO* ExerciseExercise 9.4.4:9.4.4: THEN RedesignRedesignRETURN(0) ourour runningrunning battleshipsbattleships databasedatabase schemaschema of Exer- !! d) Find the battles in n-hich at least one US ship was damaged. bestMovie REF(MovieType) SCOPE Movie StarsIn MovieStar in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. 9)4) ELSE) RETURNSRETURN(1) INTEGER-111 appropriate9.5cise cise 5.2.45.2.4 SQLOperations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. from and all tuples involving that star. First,CREATE> ; we TABLE need toMovieStar redefine MovieStarOF StarType so it( is a referenceable table, thusly: Other elements of a table declaration, such as keys, foreign keys, and tuple- END IF; declared ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are Exercise 9.5.4 : Assuming the function AddrLEG of Fig. 9.13 is available, write ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationship relationship -111 appropriate SQL operations from previous chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an a suitable function to compare objects of type StarType, and declare your betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented 5) this IF xl.city() < x2.cityOdeclared with THEN a UDT RETURN(-1) or that have attributes whose type is a CDT. There9.6 are Summary of Chapter 9 only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented star's best this ever, someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys6) of ELSEIF xl.city() also> x2.cityOsome entirely newTHEN operations RETURN(1) we can use, such as reference-follo~ving.How- function to be the basis of the ordering of StarType objects. movie.relationship by a relation like StarsIn that contains tuples with the keys ofFigure 9.13: A comparison\\-hose type function is a UDT, for involve address new objects syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhich to to have 7)have ELSEIF xl. streetever, () < some x2. familiar street operations. () THEN especiallyRETURN(-1) those that access or modify columns+ Select-From- Where Statements in OQL: OQL offers a select-from-where were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a direct \\-hose type is a UDT, involve new syntax. expression*! that Exercise resembles 9.5.5 SQL's. : WriteIn the a FROMprocedure clause, to we take can a declare star name as argument and delete referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have8) ELSEIF xl.street()9.59.5 = x2.streetOOperationsOperations THEN onon RETURN(0) Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly: 9.5.1 Following References variables thatfrom range StarsIn over any collection, and MovieStar including all both tuples extents involving of classes that star. a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, is athusly: TABLEdirect9) ELSE RETURN(1) CREATE TABLE MovieStar OF StarType; 9.5.5 Exercises for Section-111 -1119.5 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat(analogous are to relations) and collections that are the values of attributes statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( END IF; declared with a UDT or that have attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: Exercise 9.5.1: Using the StarsInWe can obtain relationdeclared tuple of with tExample itself, a UDT or 9.25,components or that and havethe of Moviet:attributes by two means: whose type is a CDT. Therein are objects. starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, Supposealso some x is entirely a value new of typeoperations REF(T). we Then can use, x refers such to as some reference-follo~ving. tuple t of type T.How- attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( and Moviestar relations accessihle throughalso some StarsIn, entirelywrite new theoperations following we quer- can use, such as reference-follo~ving.How- 9.6 Summary of Chapter 9 1; movie REFREF(MovieType1 IS tattribute SCOPE name> Movie has familiar essentially operations. the same meaning especially as thosethis operator that access does inor C.modify columns 1; Figure 9.13: A comparison\\-hose\\-hose type type function isis aa UDT,UDT, for involveinvolve address newnew objects syntax.syntax. tersection, difference, and aggregation operators that are similar in spirit movie REF(MovieType1 SCOPE Movie That1. is, Operator if x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. Select-From- Where Statements in OQL: OQL offers a select-from-where It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 51 to SQL's. Ho~ever,+ aggregation is al~vaysover a collection, not a colunln 1; * a) Find the names of the stars ofx->a Ishtar. is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then In the FROM clause, we can declare as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct of a relation. expression that resembles SQL's. 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared*! b) StarsIn Find the titles and years of2. allThe movies DEREF inoperator which appliesat least to one a reference star lives and in produces the tuple refer- variables that range over any collection, including both extents of classes 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. 9.5.5lialibu. Exercises for Sectionenced.SupposeSuppose2. The 9.5xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype+ OQL T. Group-By: OQL(analogous also offers ato GROUP relations) BY clause and in collections select-from-where that are the values of attributes CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: statements that is similar to SQL's. Howeyer, in OQL, the collection of 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, Exercise 9.5.1: Using the StarsIn relation of Example 9.25, and the Movie in objects. 2. DERIVED. lneaning that the DBMS will use the primary key of thec) relation Find all the movies (objectsExample of type9.26: MovieType) Let us use thethat relation starred StarsIn Melanie from Example 9.25 to find objects in each group is explicitly accessible through a field name called 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie and Moviestar relations accessihle1. throughOperator StarsIn,-> has essentiallywrite thethe same following meaning quer- as this operator does in C. The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: Griffith. the moviesExample in1. which Operator 9.26: JIel Gibson Let-> has us starred.essentiallyuse the Recall relation the that same StarsIn the meaning schema from isas Example this operator 9.25 todoes find inpartition. C. + Common OQL Operators: OQL offers for-all, there-exists, IN: union, in- 1;1; 9.4.1 : ThatThat is,is, ifif xx isis aa referencereference toto aa tupletuple t.t. andand aa isis anan attributeattribute of t,t, then through the notion of a reference. Tables whose type is a UDT may have Exercise Write type declarations for the following types: ies: the movies in which JIel Gibson starred. Recall that the schema is tersection, difference, and aggregation operators that are similar in spirit a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declareda) a title.Find the names of the stars ofStarsIn(star, Ishtar. movie) to SQL's. Ho~ever,aggregation is al~vaysover a collection, not a colunln toto be be a atable table of ofthat that type. type. * 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- of a relation. enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year,*! together,b) Find the titles and years of all enced.movies in which at least one star lives in types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 OQL Group-By: OQL also offers a GROUP BY clause in select-from-where to be the key for relation Movie in line (7). lialibu. ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find + To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis statements that is similar to SQL's. Howeyer, in OQL, the collection of have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attributec) Find of all the movies (objects of type MovieType) that starred Melanie objects in each group is explicitly accessible through a field name called type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a Griffith.title. anytitle. StarsIn(star,StarsIn(star, movie)movie) partition. a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGES are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your 455 2 title CHAR(30) , declaration. year INTEGER, * b) PersonType, with a name of the person and references to the persons that 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS ( c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your 2 1 ; title CHAR(30) , band anddeclaration. wife. year EXAMPLESINTEGER, IV: COMPARISON 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 454 5) 3,4) CREATECHAPTER incolor TABLE 9. Movie OBJECT-ORIENTATIONBOOLEAN OF MovieType ( IN QUERY LAXGU-AGES Exercise9.5. c)9.4.2: MarriageType, OPERATIONS Redesign our with ON running the OBJECT-RELATIONAL date products of the databasemarriage schemaand DATA references of Exer- to the hus- 455 6) 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema of Exer- 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( 453 tribute be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your 2 1; title CHAR(30) , cise 5.2.1 to use type declarations and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, declaration.declaration. 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the model at- A REF(T) SCOPE R Create Ordering For MovieType Equals Only By State; BEGIN 3,4) 3,4) 1; incolorFigureincolor 9.11: BOOLEAN BOOLEAN Creating a referenceable table tables PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus- . . . 1 ;1 ; table. Is it alsoband bandpossible andand to wife. wife.make the model attribute in Product a reference to END ; If no scope is specified, the reference can go to any relation of type T ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the the tuple in the relation for that type of product? Why or why not? Figure Creating a referenceable table tablesExercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema of Exer- \Ve have omitted the body of the method because accomplishing the intended table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movie for * Exercisecise 9.4.4: 5.2.1 Redesign to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. separation of the string string as intended is nontrivial, even in PSM. theIn tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type of cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType and Movie tribute be a reference to the Product tuple for that model. 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-keyQ5: Find distinct moviesThe schema* starredExercise from Exercise9.4.4:by ‘Jim Redesign 9.1.3 Carry’ should our suggest running where battleships reference database attributes schema are of Exer- Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship that includes attributes title and year from the same tuple. or ‘Mel Gibson’ useful. !cise! LookExercise Exercise 5.2.4 for many-oneto 9.4.3: use9.4.3: type relationshipsInIn declarations Exercise Exercise 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. in the Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of useful.table.table. Is LookIs itit also alsofor possible many-onepossible toto relationships makemake thethe modelmodel and attributeattributetry to represent inin ProductProduct them a usingreferencereference an to we use Moviebetween andCREATE moviesMovieStar. TYPE and StarType starsAs an using alternative, AS references.( we may Previously, define StarsIn we represented to have this name CHAR(30) , attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieIDSelect of Distinct DEREF(movie)9.5 Operations on Object-Relational Data address AddressType, byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to have Exercise 9.4.4: Redesign our running battleships database schema of Exer- bestMovie REF(MovieType) SCOPE Movie From StarsIn ** Exercise 9.4.4: Redesign our running battleships database schema of Exer- in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. -111 appropriate9.5cisecise 5.2.45.2.4 SQLOperations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. CREATE> ; TABLE MovieStar OF StarType ( Where star->name = ‘Jim Carry’ Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly: declared ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationship relationship -111 appropriate SQL operations from previous chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then eachOr star star->name also= ‘Mel someuseful.useful. entirely Gibson’; Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There are only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented star's best this ever, someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys of also some entirely new operations we can use, such as reference-follo~ving.How- movie.relationship by a relation like StarsIn that contains tuples with the keys of \\-hose type is a UDT, involve new syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhich to to have have ever, some familiar operations. especially those that access or modify columns were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a direct \\-hose type is a UDT, involve new syntax. referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have 9.59.5 OperationsOperations onon Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly: 9.5.1 Following References a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, is athusly: TABLEdirect CREATE TABLE MovieStar OF StarType; -111-111 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( declared with a or that have attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We can obtaindeclared tuple with t itself, a UDTUDT or components or that have of t:attributes by two means: whose type is a CDT. There are starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( alsoalso some some entirely entirely new new operationsoperations wewe cancan use,use, suchsuch asas reference-follo~ving.reference-follo~ving.How- movie REF(MovieType1 SCOPE Movie We can obtain tuple t itself, or components of t: by two means: a type that is itself a UDT, namely the type AddressType. 1;1; starREF REF(StarType1IS tattribute name> SCOPE has familiar familiar essentially operations.operations. the same especiallymeaning especially as those thosethis operator thatthat accessaccess does orinor C.modifymodify columns 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. movie REF(MovieType1 SCOPE Movie That1. is, Operator if x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 52 1; x->a is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared StarsIn 2. The DEREF operator applies to a reference and produces the tuple refer- 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. enced.SupposeSuppose2. The xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype T. CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, 2. DERIVED. lneaning that the DBMS will use the primary key of the relation Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: the moviesExample in1.1. which OperatorOperator 9.26: JIel Gibson ->Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25 todoes find in C. through the notion of a reference. Tables whose type is a UDT may have Exercise1;1; 9.4.1 : Write type declarations for the following types: the moviesThatThat in is, is,which ifif xx JIelisis aa Gibsonreferencereference starred. toto aa tupletupleRecall t.t. that andand theaa isis schema anan attributeattribute is of t,t, then a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, enced. types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attribute of type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a title. anytitle. StarsIn(star,StarsIn(star, movie)movie) a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455

* b) PersonType, with a name of the person and references to the persons that 454 1) CHAPTERCREATE TYPE 9. MovieType OBJECT-ORIENTATION AS ( IN QUERY LAXGU-AGES are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your 455 2 title CHAR(30) , declaration. year INTEGER, * b) PersonType, with a name of the person and references to the persons that 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS ( c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in your 2 1 ; title CHAR(30) , band anddeclaration. wife. EXAMPLESyear INTEGER, V: GROUPING & NESTING 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 454 5) 3,4) CREATECHAPTER incolor TABLE 9. Movie OBJECT-ORIENTATIONBOOLEAN OF MovieType ( IN QUERY LAXGU-AGES Exercise9.5. c)9.4.2: MarriageType, OPERATIONS Redesign our with ON running the OBJECT-RELATIONAL date products of the databasemarriage schemaand DATA references of Exer- to the hus- 455 6) 1 ;REF IS movieID SYSTEM GENERATED, cise 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 7) PRIMARY KEY (title, year) In particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe persons that 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( Exercise 9.4.2: Redesign our running products database schema of Exer- 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) CREATE TABLE TYPES Movie IAr OF SQL MovieType ( 453 tribute be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a) inin your 2 1; title CHAR(30) , cise 5.2.1 to use type declarations and reference attributes where appropriate. 6)2 REFtitle IS movieIDCHAR(30) SYSTEM , GENERATED, Q6: Find stars who participateddeclaration.declaration. in less than 10 movies 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the model at- A REF(T) SCOPE R BEGIN 3,4) 3,4) 1; incolorFigureincolor 9.11: BOOLEAN BOOLEAN Creating a referenceable table tables PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus- . . . 1 ;1 ; table. Is it alsoband bandpossible andand to wife. wife.make the model attribute in Product a reference to END ; If no scope is specified, the reference can go to any relation of type T Select DEREF(star) ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers in the the tuple in the relation for that type of product? Why or why not? Figure Creating a referenceable table tablesExercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE 9.11:thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStarFrom StarsIn Exercise 9.4.2: Redesign our running products database schema of Exer- \Ve have omitted the body of the method because accomplishing the intended table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movie for * Exercisecise 9.4.4: 5.2.1 Redesign to use typeour running declarations battleships and reference database attributesschema of Exer-where appropriate. separation of the string string as intended is nontrivial, even in PSM. Group by DEREF(star)the In tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type of cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the model at- GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. this relation1; 1; is the UDT MovieType; we shall define both MovieType andHaving Movie count(movie) ; TABLE MovieStar OF StarType ( Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly: declared ThewithThe schemaaschema UDT or fromfrom that ExerciseExercise have attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-many relationship relationship -111 appropriate SQL operations from previous chapters apply to tables that are based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There are only to this table, not to the UDT itself. tuplebetween1; will movieshave a andcomponent stars using that references.refers to a Movie Previously, tuple we- therepresented star'sSelect best this m ever, someattributeattribute familiar withoperations.with aa referencereference especially type.type. those that access or modify columns relationship REFby aIS relation starID like SYSTEM StarsIn GENERATED that contains tuples with the keys of also some entirely new operations we can use, such as reference-follo~ving.How- movie.relationship by a relation like StarsIn that contains tuples with Fromthe keys Movie of m \\-hose type is a UDT, involve new syntax. Example 9.22 : We could declare MovieStar to be a relation whose tuples MovieMovieThen, and1; andwe MovieStar.may MovieStar. declare the AsAs relationan an alternative, alternative, StarsIn towe we have maymay two define define attributes, StarsIn StarsIn ~vhich to to have have ever, some familiar operations. especially those that access or modify columns were of type StarType by arereferences references, to tuplesone to froma movie these-two tuple and relations. one to a star tuple. Here is a directWhere m.year = 2000 \\-hose type is a UDT, involve new syntax. referencesSest,Then, n-e weto must maytuples arrange declare from these-twothatthe relationa table relations. suchStarsIn as Movie to have in Example two attributes, 9.23 will ~vhich have 9.59.5 OperationsOperations onon Object-RelationalObject-Relational DataData definitionFirst, ofwe this need relation: to redefine MovieStar so it is a referenceable table, thusly: 9.5.1 Following References a arereference First,references, wecolumn. need one toto Such redefine a movie a table MovieStartuple is said and to soone be it referenceable. tois aa starreferenceable tuple. In a Here CREATE table, Andis athusly: TABLEdirect m.title Not In ( CREATE TABLE MovieStar OF StarType; -111-111 appropriate appropriate SQL SQL operations operations fromfrom previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Select movie->titleSuppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( declared with a or that have attributes whose type is a CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We can obtaindeclared tuple with t itself, a UDTUDT or components or that have of t:attributes by two means: whose type is a CDT. There are starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, From StarsIn Suppose x is a value of type REF(T). Then x refers to some tuple t of type T. attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( alsoalso some some entirely entirely new new operationsoperations wewe cancan use,use, suchsuch asas reference-follo~ving.reference-follo~ving.How- movie REF(MovieType1 SCOPE Movie We can obtain tuple t itself, or components of t: by two means: a type that is itself a UDT, namely the type AddressType. 1;1; starREF REF(StarType1IS tattribute name> SCOPE name1. Operatorever,ever, some =some-> ‘Jimhas familiar familiar essentially Carry’ operations.operations. the same especiallymeaning especially as those thosethis operator thatthat accessaccess does orinor C.modifymodify columns 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. movie REF(MovieType1 SCOPE Movie And movie->yearThat1. is, Operator= if 2000);x is a reference-> has essentially to a tuple the t. sameand a meaningis an attribute as this of operator t, then does in C. It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhich ~vhich 53 1; x->a is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is is a a direct direct 9.5.19.5.1x->a FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared StarsIn 2. The DEREF operator applies to a reference and produces the tuple refer- 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain- to be a table of that type. enced.SupposeSuppose2. The xDEREF x isis aa valueoperatorvalue ofof type typeapplies REF(T).REF(T). to a reference ThenThen xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype T. CREATEingCREATE a unique TABLE TABLE value StarsIn StarsIn in this ( column ( of each tuple, or WeWe canenced.can obtainobtain tupletuple tt itself,itself, oror componentscomponents ofof t:t: byby twotwo means:means: 9.4.4 References 9.4.5 Exercisesstarstar REF(StarType1forREF(StarType1 Section 9.4 SCOPE SCOPE MovieStar, MovieStar, 2. DERIVED. lneaning that the DBMS will use the primary key of the relation Example 9.26: Let us use the relation StarsIn from Example 9.25 to find 9.4.5 movieExercisesmovie REF(MovieType1REF(MovieType1 for Section SCOPE 9.4SCOPE Movie Movie The effect of object identity in object-oriented languages is obtained in SQL Exerciseto produce9.4.1 : Write unique type values declarations for this for column. the following types: the moviesExample in1.1. which OperatorOperator 9.26: JIel Gibson ->Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25 todoes find in C. through the notion of a reference. Tables whose type is a UDT may have Exercise1;1; 9.4.1 : Write type declarations for the following types: the moviesThatThat in is, is,which ifif xx JIelisis aa Gibsonreferencereference starred. toto aa tupletupleRecall t.t. that andand theaa isis schema anan attributeattribute is of t,t, then a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda title. relation StarsIn(star,x->ax->a is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declared declared StarsIn StarsIn primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. 2. The DEREF operator applies to a reference and produces the tuple refer- are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- enced. defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, enced. types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25 toto find To refer to the tuples of a table with a reference column, an attribute may (6) ExerciseExercise\\e see 9.4.1 9.4.1in line : :Write Write thattype type thedeclarations declarations name of for thefor the the"identity" following following coluln~l types: types: for Movie is thethe movies movies in in whichwhich JIelJIel GibsonGibson starred.starred. RecallRecall thatthat thethe schemaschema isis have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attribute of type of a reference to a tuple of type T. Further, the reference may be given Movie.a)a) NameType, NameType,along xith with with title, components components year, and for for incolor;first, first, middle, middle, may andbe and used last last innames names queries and and like a a title. anytitle. StarsIn(star,StarsIn(star, movie)movie) a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the value of a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced "SYSTEM QUERYING COLLECTIONS & ARRAYS

create type Book as To get a relation containing pairs of the form (title varchar(20), “title, author-name” for each book and each author-array varchar(20) array [10], author of the book pub-date date, publisher Publisher, select B.title, A keyword-set setof(varchar(20))) from books as B, unnest (B.author-array) as A

find all books that have the word “database” as one of their keywords select title from books ‘ ’ where database in (unnest(keyword-set)) Unnest returns a relation

Get 1st and 2nd authors of certain book

select author-array[1], author-array[2] from books where title = `Database System Conceptsʼ 54 GENERATORS AND MUTATORS

• How to insert new new data into tables

• Generators • Like the constructors in OO programming • Create new objects

• Mutators • Modify the value of an existing object

• For each attribute x in UDT T, the system automatically creates: • Generator T() that returns an empty object of T • Mutator x(v) that sets the value of attribute x to value v

55 458 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGUAGES 9.5. OPERATIONS ON OBJECT-RELATIONAL DAT.4 459

a relation that has a UDT unless we define a function that tells which of two 1) CREATE PROCEDURE Insertstar( objects of that UDT precedes the other. IN s CHAR(5O), Yet there are many SQL operations that require either an equality test or 3)2, IN c CHAR(10). both an equality and a "less than" test. For instance, we cannot eliminate 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES4) IN n CHAR(30) 9.5. OPERATIONS ON OBJECT-RELATIONAL DATA 455 duplicates if we can't tell whether two tuples are equal. We cannot group by an 458 1 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGUAGES 9.5. attributeOPERATIONS whose ON type OBJECT-RELATIONAL is a UDT unless there DAT.4 is an equality test for459 that UDT. 5) DECLARE newAddr AddressType;* b) PersonType, with a name of the person and references to the persons that We cannot use an ORDER BY clause or a comparison like < in a WHERE clause 1) CREATE TYPE MovieType AS ( 454 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LAXGU-AGES6) DECLARE newstar StarType;are9.5. their OPERATIONS mother and father. ON OBJECT-RELATIONALYou must use the type from DATA part (a) in your a relation455unless that we hascan acompare UDT unless any wetwo define elements. a function that tells which of two 2 title CHAR(30) , declaration. year INTEGER, 1) CREATE PROCEDURE Insertstar( objects ofTo that specify UDT anprecedes ordering the other.or comparison, SQL allows us to issue a CREATE * b) PersonType, with a name of the person and references to the persons that ( BEGIN IN s CHAR(5O), Yet there are many SQL operations that require either an equality test or 3,4) 1) CREATEincolor TYPE BOOLEAN MovieType AS c) MarriageType,are their with mother the dateand father.of the marriageYou must and use references the type tofrom the part hus- (a) in yourORDERING statement for any UDT. There are a number of forms this statement 3)2, IN c CHAR(10). 2 1 ; title CHAR(30) , EXAMPLE7) SET newAddr = AddressTypeO;band anddeclaration. wife. both may an equality take, and and we a shall"less onlythan" considertest. For the instance, two simplest we cannot options: eliminate year INTEGER, 8) 4) SET INnewstar n CHAR(30) = StarTypeO ; duplicates if we can't tell whether two tuples are equal. We cannot group by an 454454 3,4)CHAPTER CHAPTERincolor 9. 9. OBJECT-ORIENTATION OBJECT-ORIENTATIONBOOLEAN IN IN QUERY QUERY LAXGU-AGES LAXGU-AGES Exercise9.5.9.5. c)9.4.2: MarriageType, OPERATIONSOPERATIONS Redesign our with ON ON running the OBJECT-RELATIONALOBJECT-RELATIONAL date products of the databasemarriage schemaand DATADATA references of Exer- to the9.5. hus- OPERATIONS455 ON OBJECT-RELATIONAL DAT.4 459 5) CREATE TABLE Movie OF MovieType ( 9)458 1CHAPTERnewAddr.street(s); 9. OBJECT-ORIENTATION IN QUERY LANGUAGES attribute1. whose The statementtype is a UDT unless there is an equality test for that UDT. 1 ;REF IS movieID SYSTEM GENERATED, 5) DECLARE newAddr ciseAddressType; 5.2.1 to useband type and declarations wife. and reference attributes where appropriate. 6) 10) newAddr. city (c) ; We cannot use an ORDER BY clause or a comparison like < in a WHERE clause 7) PRIMARY KEY (title, year) 6) DECLARE newstar InStarType; particular,** b)b) inPersonType,PersonType, the relations with with PC: aaLaptop, namename of ofand thethe Printer personperson and andmake referencesreferences the model toto at- thethe personsa relation that that has aCREATE UDT unless ORDERING we define FOR a functionT EQUALS that ONLY tells whichBY STATE; of two 1)1) CREATECREATE TYPE TYPE MovieType MovieType AS AS ( ( ( ; Exercise 9.4.2: Redesign our running products database schema ofunless Exer- we can compare any two elements. 452 CHAPTER 9. OBJECT-ORIENTATION IN QUERY LANGU.4GEs 9.1. USER-DEFINED5) 1; CREATE TABLE TYPES Movie IAr OF SQL MovieType 11) 4531) newstarCREATE .name(n) PROCEDUREtribute Insertstar( be a referenceareare their their to motherthemother Product andand father.tuplefather. for YouYou that mustmust model. useuse thethe typetype fromfrom partpart (a)(a)objects inin your of that UDT precedes the other. 2 2 titleREFtitle IS movieIDCHAR(30)CHAR(30) SYSTEM , , GENERATED, cise 5.2.1 to use type declarations and reference attributes where appropriate.To specify an ordering or comparison, SQL allows us to issue a CREATE 6) 12) newstar.IN s address(newAddr1; CHAR(5O), declaration. declaration. Yet there are many SQL operations that require either an equality test or 7) yearPRIMARYyear INTEGER,KEYINTEGER, (title, year) BEGIN ! ExerciseIn 9.4.3:particular, In Exercise in the relations9.4.2 we suggestedPC: Laptop, that and model Printer numbers make in the modelORDERING at- statementsays that for two any members UDT. There of areUDT a numberT are ofconsidered forms this statementequal if all of their A REF(T) SCOPE R 13) 3)2, INSERTIN INTO c CHAR(10). Moviestar VALUES(newStar); both an equality and a "less than" test. For instance, we cannot eliminate BEGIN 3,4) 3,4) 1; incolorincolor BOOLEAN BOOLEAN 7) SET newAddr tables= AddressTypeO; PC,tribute Laptop,c)c) MarriageType,beMarriageType, aand reference Printer to with with couldthe theProductthe be datedatereferences tupleofof thethe tofor marriagemarriage tuples that model.of andandthe Productreferencesreferences toto thethe hus-corresponding components are equal. There is no < defined on objects of Figure 9.11: Creating a referenceable table END4) ; IN n CHAR(30) mayduplicates take, and if we can'tshall tellonly whether consider two the tuples two simplest are equal. options: We cannot group by an . . . 1 ;1 ; 8) SET newstar table.= StarTypeO Is it alsoband bandpossible ; andand to wife. wife.make the model attribute in Product a reference to UDT T. END ; If no scope is specified, the reference can go to any relation of type T 1 ! Exercise 9.4.3: In Exercise 9.4.2 we suggested that model numbers inattribute the whose type is a UDT unless there is an equality test for that UDT. the tuple in the relation for that type of product? Why or why not? 1. The statement Figure 9.11: Creating a referenceable table 9) 5) DECLAREnewAddr.street(s); newAddr AddressType;tables Exercise PC, Laptop, 9.4.2: andRedesign Printer our could running be references products todatabase tuples of schema the Product of Exer- GENERATED"ExampIe5)5) CREATE9.23byCREATE "DERIVED," : Reference TABLE TABLE thenMovie Movieattributes new OF OFtuples MovieType MovieTypeare would not sufficient get ( (their to value record of movieIDin MovieStar Exercise 9.4.2: Redesign our running products database schema Weof Exer-cannot2. The use following an ORDER statement BY clause or a comparison like < in a WHERE clause \Ve have omitted the body of the method because accomplishing the intended 10) 6) DECLAREnewAddr. newstar city (c) StarType; ; table.cise 5.2.1Is it alsoto use possible type declarationsto make the modeland reference attribute attributes in Product where a reference appropriate. to bythe some set6) 6)calculation,of all moviesREFREF performed IS theyIS movieID movieID starred by the SYSTEM in, SYSTEMsystem, but theyGENERATED, onGENERATED, the let values us record of the the primary-key best movie forFigure 9.12: Creating* Exercise and storingcise 9.4.4: 5.2.1 aRedesign toStarType use typeour running objectdeclarations battleships and reference database attributesschema of Exer-where appropriate.unless we can CREATEcompare ORDERING any two elements.FOR T EQUALS ONLY BY STATE; separation of the string string as intended is nontrivial, even in PSM. 11) newstar .name(n) ; theIn tupleparticular, in the inrelation the relations for that typePC: Laptop, of product? and WhyPrinter or why make not? the model at- attributeseach star.7)7) title Assume PRIMARYandPRIMARY that year we fromKEY KEYhave the(title,(title, declared same tuple.year) year)a relation Movie, and that the type of cise 5.2.4 Into useparticular, type declarations in the relations and reference PC: Laptop, attributes and where Printer appropriate. make the modelTo at-specify an ordering or comparison, SQL allows us to issue a CREATE GENERATED" by "DERIVED," then new tuples would get their value of movieID tribute be a reference to the Product tuple for that model. CREATE ORDERING FOR T this relation1; 1; is the UDT MovieType; we shall define both MovieType and 12)Movie BEGINnewstar. address(newAddr1;tribute be a reference to the Product tuple for that model. ORDERING statement for any UDT. There are a number of forms this statement 9.4.3 Declaring Relations with a UDT by some calculation, performed by the system, on the values of the primary-key The schema* Exercise from Exercise9.4.4: Redesign 9.1.3 should our suggestrunning where battleships reference database attributes schema are of Exer-says that two membersORDERING of UDT TFULL are consideredBY RELATIVE equal WITH if all F; of their Examplelater, in Fig.9.25 9.11. : Now, The let followingus see how is to a representnew definition the many-many of StarType relationship thatTo insert includes13) 7)a star INSERTintoSET MovieStar, newAddrINTO Moviestar = weAddressTypeO; can VALUES(newStar); call procedure Insertstar. may take, and we shall only consider the two simplest options: attributes title and year from the same tuple. useful. !cise! LookExercise Exercise 5.2.4 for many-oneto 9.4.3: use9.4.3: type relationshipsInIn declarations Exercise Exercise 9.4.2and9.4.2 and try wewereference to suggestedsuggested represent attributes that themthat model model usingwhere an numbersnumbersappropriate. incorresponding the components are equal. There is no < defined on objects of Having declared a type, we may declare one or more relations whose tuples are betweena11 attribute movies bestMovie and stars thatusing is references. a reference Previously,to a movie. we represented this 8)END ; SET newstar = StarTypeO ; FigureFigure 9.11: 9.11: Creating Creating a areferenceable referenceable table table attributeThetables tableswith schema a PC,referencePC, Laptop,fromLaptop, type.Exercise andand PrinterPrinter 9.1.3 should couldcould suggest bebe referencesreferences where reference toto tuplestuples attributes ofof thethe Product are1.UDT The T. statement of that type. The form of relation declarations is like that of Section 6.6.2, but relationshipExample by9.25 a relation: Now, letlike us StarsIn see how that to represent contains tuplesthe many-many with the keys relationship of 9) newAddr.street(s); says that any of the six comparisons (<, <=, >, >=, =, and <>) may be CALL InsertStar('345 Spruce St.',useful.table. table.'Glendale', Is LookIs itit also alsofor possible many-onepossible'Gwyneth toto relationships makemake Paltrow'); thethe modelmodel and attributeattributetry to represent inin ProductProduct them a usingreferencereference an to we use Moviebetween andCREATE moviesMovieStar. TYPE and StarType starsAs an using alternative, AS references.( we may Previously, define StarsIn we represented to have this10) newAddr. city (c) ; performed on objects of UDT T. To tell how objects xl and 22 compare, name CHAR(30) , attributethethe tupletuple with inin thethea reference relation relation type. forfor thatthat typetype ofof product?product? WhyWhy oror whywhy not? 2. The followingCREATE statement ORDERING FOR T EQUALS ONLY BY STATE; referencesGENERATED"relationshipGENERATED" to tuplesby byby "DERIVED," a "DERIVED," fromrelation these-two likethen then StarsIn relations.new new tuples tuples that would containswould get get tuplestheir their value withvalue theof of movieID keysmovieID11) of Figure newstar 9.12: Creating .name(n)9.5 and ;Operations storing a StarType on objectObject-Relational Data we apply the function F to these objects. This function must be writ- address AddressType, is an example. byMovieby someFirst, some andcalculation,we calculation, need MovieStar. to redefine performed performed As MovieStar an by byalternative, the the so system, system,it is a wereferenceable on on maythe the values definevalues table, of StarsInof the the thusly: primary-key primary-key to have12) newstar. address(newAddr1;Exercise 9.4.4: Redesign our running battleships database schema of Exer- bestMovie REF(MovieType) SCOPE Movie ** Exercise 9.4.4: Redesign our running battleships database schema of Exer-saysten that so twothat CREATEmembers F(x1,z2) ORDERING of < UDT 0 whenever FORT areT considered we want equal to conclude if all of thattheir xl < x2; in place of the list of attribute declarations in a normal SQL table declaration. attributesreferencesattributes title totitle tuples and and from year year these-two from from the the relations.same same tuple. tuple. 13) INSERT INTO-111 Moviestarappropriate9.5cisecise 5.2.45.2.4 SQLVALUES(newStar);Operations to to operations useuse typetype from declarationsdeclarations on previous Object-Relational andchaptersand referencereference apply toattributesattributes tables that whereDatawhere are appropriate. CREATE> ; TABLE MovieStar OF StarType ( It is much simpler to insert objects into a relation with a UDT if your correspondingF(xl,x2)= ORDERINGcomponents 0 means FULL that are equal.BYx1 =RELATIVE x2,There and is WITHF(x1,x2) no < F;defined > 0on means objects that. of x1 > 22. Other elements of a table declaration, such as keys, foreign keys, and tuple- First, we need to redefine MovieStar so it is a referenceable table, thusly:To insert aEND star ; into MovieStar,declared we ThewithThe can schemaaschema callUDT procedure or fromfrom that ExerciseExercise have Insertstar. attributes 9.1.39.1.3 shouldshould whose suggesttypesuggest is a where whereCDT. referencereferenceThere are attributes are ExampleExampleREF 9.25 9.25 IS : starIDNow,: Now, let letSYSTEM us us see see GENERATEDhow how to to represent represent the the many-many many-manyDBMS relationship relationship provides, or if you create, a generator-111 appropriate function SQL operationsthat takes from values previous for chapters apply to tables that areUDT If lveT. replace "ORDERING FULL" with "EQUALS ONLY," then F(x1,22) = 0 based constraints, may be added to the table declaration if desired, and apply Sow, if relation MovieStar is defined to have the UDT above, then each star also someuseful.useful. entirely Looknew Look operations forfor many-onemany-one we can relationshipsrelationships use, such as reference-follo~ving. andand trytry toto representrepresentHow- them them using an betweenCREATE movies TABLE and starsMovieStar using references.OF StarType Previously, ( we represented this declared with a UDT or that have attributes whose type is a CDT. There aresays that any of the six comparisons (<, <=, >, >=, =, and <>) may be only to this table, not to the UDT itself. between1; movies and stars using references. Previously, wethe represented attributesCALL InsertStar('345 this of the C'DT andSpruce ever,returns St.', some attributeattributea familiarsuitable'Glendale', withoperations.with object. aa referencereference'Gwyneth especiallyFor type.example,type. Paltrow'); those thatif we access or modify columns 2. Theindicates following thatstatement x1 = x2, rvhile any other value of F(x1, xz) means that tuple will haveREF aIS component starID SYSTEM that refers GENERATED to a Movie tuple - the star's best also some entirely new operations we can use, such as reference-follo~ving.How- relationshiprelationship by by a arelation relation like like StarsIn StarsIn that that contains contains tuples tuples have with with functionsthe the keys keys of ofAddressType(s Figure 9.12: Creating ,\\-hosec) and type andStarType(n, is storing a UDT, ainvolve StarTypea) that new returnobjectsyntax. objects of performedXI # on12. objects Comparison of UDT byT. 0 means on objects that. x1 of> 22.this UDT, we CREATE TABLE MovieStar OF StarType; It is much simpler to insert objects-111-111 appropriate intoappropriate a relation SQL SQL with operations operations a UDT fromfrom if your previousprevious chapterschapters applyapply toto tablestables thatthat are statementdefinition n-hereof this therelation: type of the table is a UDT (as in Section 9.4.3), we may Suppose9.5.1 x is a valueFollowing of type REF(T). References Then x refers to some tuple t of type T. couldIf sayslve replacedeclare: that any "ORDERING of the six FULL" comparisons with "EQUALS (<, <=, ONLY," >, >=, then =, and F(x1,22) <>) may = 0be CREATECREATECREATE TABLE TABLE TABLE StarsIn MovieStar MovieStar ( OF OF StarTypeStarType ( ( DBMSINSERTCALL provides, InsertStar('345INTO MovleStaror if you create,Spruce VALUES a St.', generatordeclared(declared 'Glendale', with withfunction aa UDTUDT that'Gwyneth oror takes thatthat havehavevaluesPaltrow'); attributesattributes for whosewhose typetype isis aa CDT.CDT. There are As a result, table MovieStar has two attributes, name and address. The first append a clause of the form: We can obtain tuple t itself, or components of t: by two means: performed on objects of UDT T. To tell how objects xl and 22 compare, starREFREF IS IS REF(StarType1starID starID SYSTEM SYSTEM SCOPE GENERATED GENERATED MovieStar, the attributes of the C'DT and returnsSupposealsoalso a some suitablesome x is entirely entirely a object.value new newof For type operationsoperations example, REF(T). wewe ifThen cancanwe use, use,x refers suchsuch to asas some reference-follo~ving.reference-follo~ving. tuple t of type T.indicatesHow- that x1 = x2, rvhile any other value of F(x1, xz) means that attribute, name, is an ordinary character string, but the second, address. has CREATE TABLE StarsIn ( StarType('Gwyneth Paltrow', we CREATEapply the ORDERING function FFOR to theseStarType objects. EQUALS This functionONLY BY must STATE; be writ- 1;1; movie REFREF(MovieType1 IS tattribute SCOPE name> Movie obtain has familiar familiar essentially tuplea) that toperations. operations.itself, thereturn sameor components objects especiallymeaning especially of as of those thosethis t: byoperator thatthat two access accessmeans: does orinor C.modifymodify columnsXI # 12. Comparison by < is impossible in this case. a type that is itself a UDT, namely the type AddressType. star REF(StarType1 SCOPE MovieStar, AddressType('345 Spruce St.', 'Glendale'))); ten so that F(x1,z2) 0 whenever we want to conclude that xl x2; 1; \\-hose\\-hose type type isis aa UDT,UDT, involveinvolve newnew syntax.syntax. < < movie REF(MovieType1 SCOPE Movie the indicated types, then we can makeThat the1. is, Operatorinsertion if x is a reference->at thehas endessentially to of a Exampletuple the t. sameand 9.28 a meaningis an attribute as this of operator t, then does inThat C. state~nentsays that t~-oobjects of StarType are equal if and only if their It is colrimon to have one relation for each type, and to think of that relation TheThen, attributeThen, we we may namemay declare declareis a name the the givenrelation relation to theStarsIn StarsIn column to to that have have will two two serve attributes, attributes, as an "object ~vhichIt ~vhich is much simpler to insert objects into a relation with a UDT if 56your ExampleF(xl,x2) 9.29: = Let 0 meansus consider that x1 a =possible x2, and ordering F(x1,x2) on> the0 means UDT that. StarType x1 > 22. 1; with an INSERT statement of a familiarx->a form:is Thatthe value is, ifof xthe is aattribute reference n into tuple a tuple t. t. and a is an attribute of t, then as the extent (in the sense of Section 1.3.4) of the class corresponding to that Optionally,areidentifier"are references, references, wefor could tuples.one one haveto to Thea adefinedmovie movie .-how tuplea tuplegenerated"UDT and asand above,one one clause to toand a aisstar thenstar typically tuple. declaredtuple. either: Here HereStarsIn is isDBMS a a direct direct provides, or if you create, a generator function that takes values for fromnames ExampleIf lve are replace 9.20. the sameIf"ORDERING we wantas character FULL"only an with equalitystrings, "EQUALS onand objectsONLY," their thenofaddresses this F(x1,22) UDT, are we =the 0 same as 9.5.4 Ordering Relationships9.5.19.5.1 onx->a UDT's FollowingisFollowing the value of ReferencesReferencesthe attribute n in tuple t. type. However, it is permissible to have many relations or none of a given type. todefinitionOptionally, definitionbe a table of ofof thiswe thisthat could relation: relation:type. have defined a UDT as above, and then declared theStarsIn attributes of the C'DT and2. returnsThe DEREF a suitableoperator object.applies toFor a referenceexample, andif we produces the tuple refer- couldobjects declare:indicates of UDT that AddressType.x1 = x2, rvhile any other value of F(x1, xz) means that 1. SYSTEM GENERATED. meaning that the DBIIS is responsible for maintain-INSERT INTO MovleStar VALUES ( to be a table of that type. have functions AddressType(s ,enced.c) SupposeandSuppose2. TheStarType(n, xDEREF x isis aa valueoperatorvaluea) ofthatof type typeapplies return REF(T).REF(T). to objects a reference ThenThen of xx refersandrefers produces toto somesome the tupletuple tuple tt of refer-typetype XI TheT. # 12.problem Comparison is that, by Let-> hashas us starred.essentiallyessentiallyuse the Recall relation thethe that samesame StarsIn the meaningmeaning schema from asisas Example thisthis operatoroperator 9.25That todoesfrom find state~nent in Example C. says 9.20. that If t~-owe wantobjects only of anStarType equality are on equal objects if and of thisonly UDT,if their we 1;1; That is, if x is a reference to a tuple t. and a is an attribute ofcould t,that then declare: two AddressType objects are equal if and only if their streets and cities through the notion of a reference. Tables whose type is a UDT may have Exercise 9.4.1 : Write type declarations for the following types:components identicalINSERT INTO will notMovleStar be considered VALUESthe movies ( equal That in is,unlesswhich if x JIelweis a Gibsontellreference the starred. system to a tupleRecall to t. that and thea is schema an attribute is names of t, thenare the same as character strings, and their addresses are the same as a reference column that serves as its "identity." This column could be the Examplea) NameType, 9.24: with Figure components 9.11 forsho~t-s first,how middle, the andUDT last MovieType names and anda9.5.4 title. relation Ordering RelationshipsStarsIn(star, onx->ax->a UDT's is is movie) thethe valuevalue ofof thethe attributeattribute nn inin tupletuple t.t. are each the same. 11-e could do so by: Optionally,Optionally, we we could could have have defined defined a aUDT UDT as as above, above, and and then then declaredregard declared them StarsIn StarsIn as equal. StarType('Gwyneth Similarly, there Paltrow', is no obvious way to sort the tuples of objects ofCREATE UDT AddressType.ORDERING FOR StarType EQUALS ONLY BY STATE; primary key of the table, if there is one, or it could be a colurhn whose values Moviea) NameType,could be declared with components so that Movie for first, is referenceable. middle, and lastThe names C'DT andis declared a title. StarsIn(star, movie) toto be be a atable table of ofthat that type. type. Objects that are ofAddressType('345 some LDT are inherently Spruce2. The abstract,St.', DEREF 'Glendale'))); operatorin the sense applies that to there a reference and produces the tupleThe refer- problem is that, unless we define an ordering for AddressType, an are generated and maintained unique by the DBMS, for example. \Ve shall in lines (1) through (4). Then the relation Movie is defined to have this type in 2. The DEREF operator applies to a reference and produces the tuple refer- is no way to compare two objects of the sameenced.enced. UDT, either to test whether they objectThat ofstate~nent that typesays is notthat event~-o objectsequal to of itself.StarType Thus, are weequal also if needand onlyto create if their defer the matter of defining reference columns until we first see how reference lines (5) through (7). Sotice that n-e have declared title and year, together, names are the same as character strings, and their addresses are the same as types are used. 9.4.59.4.5 ExercisesExercises for for Section Section 9.4 9.4 are9.5.4 "equal' orOrdering whether one Relationships is less than another. on EvenUDT's two objects that have all at least an equality test for AddressType. simple way to do So is to declare to be the key for relation Movie in line (7). ExampleExample 9.26:9.26: LetLet us us useuse thethe relationrelation StarsInStarsIn from from ExampleExample 9.25objects toto find of UDT AddressType. To refer to the tuples of a table with a reference column, an attribute may \\e see in line (6) that the name of the "identity" coluln~lfor components Movie is identical will not be considered equal unless we tell the system to that two AddressType objects are equal if and only if their streets and cities ExerciseExercise 9.4.1 9.4.1 : :Write Write type type declarations declarations for for the the following following types: types: Objects that are of some LDT are theinherentlythe movies movies abstract,in in whichwhich inJIelJIel the GibsonGibson sense thatstarred.starred. there RecallRecall thatthat thethe schemaschema isis The problem is that, unless we define an ordering for AddressType, an have as its type a reference to another type. If T is a UDT, then REF(T)is the movieID. This attribute. which automatically becomes a fourth attributeregard them of as equal. Similarly, there is no obvious way to sort the tuples of are each the same. 11-e could do so by: object of that type is not even equal to itself. Thus, we also need to create type of a reference to a tuple of type T. Further, the reference may be given Movie. along xith title, year, and incolor; may be used in queries islike no anyway to compare two objects of the same UDT, either to test whether they a)a) NameType, NameType, with with components components for for first, first, middle, middle, and and last last names names and and a a title. title. StarsIn(star,StarsIn(star, movie)movie) at least an equality test for AddressType. simple way to do So is to declare a scope, which is the name of the relation whose tuples are referred to. Thus, other attribute of Movie. are "equal' or whether one is less than another. Even two objects that have all an attribute -4 whose values are references to tuples in relation R, where R is Line (6) also says that the DBMS is responsible for generating the componentsvalue of identical will not be considered equal unless we tell the system to that two AddressType objects are equal if and only if their streets and cities a table whose type is the UDT T, would be declared by: movieID each time a new tuple is inserted into Movie. Had we replaced regard"SYSTEM them as equal. Similarly, there is no obvious way to sort the tuples of are each the same. 11-e could do so by: CREATING RECORDS OF COMPLEX TYPES

create type Book as • Collection and array types (title varchar(20), author-array varchar(20) array [10], pub-date date, publisher Publisher, keyword-set setof(varchar(20)))

Array construction array [‘Silberschatz’,`Korth’,`Sudarshan’]

Set value attributes set( v1, v2, …, vn)

To insert the preceding tuple into the relation books insert into books values (`Compilers’, array[`Smith’,`Jones’], null, Publisher(‘McGraw Hill’,`New York’ ), set(`parsing’,`analysis’))

57 WHAT WE COVERED

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

• Second Approach: Object-Relational Model • Conceptual view • Data Definition Language (Creating types, tables, and relationships) • Querying object-relational database (SQL-99)

Make use of the interesting features of Object-Oriented into database systems è ODBMSs 58 WHEN TO CONSIDER OODBMS OR ORDBMS

• Complex Relationships • A lot of many-to-many relationships, tree structures or network (graph) structures.

• Complex Data • Multi-dimensional arrays, nested structures, or binary data, images, multimedia, etc.

• Distributed Databases • Need for free objects without the rigid table structure.

• Repetitive use of Large Working Sets of Objects • To make use of inheritance and reusability

• Expensive Mapping Layer • Expensive decomposition of objects (normalization) and re- composition at query time

59 KEY BENEFITS OF ODBMS

Object Oriented Databases • Persistence & Versioning pointers must be persistent. • Created objects are maintained acrossImplementation different database Issues runs

(persistent) ! Persistence ! Sharing • Different evolving copies of the same! object Paging can be created over time (versioning) ! Back to the Beginning 1. Object-oriented databases give objects persistence, which enables objects to be stored between database runs. (NOTE: in the context of ODBMS, PERSISTENCE = POST RUN TIME PERSISTENCE), this facilitates versioning (i.e. a new, additional object is stored each time changes are made).

PersistentObject Superclass Approach

• Superclass encapsulates any class for storage and retrieval

• This superclass implements all functionalities of read/write operations

1. Object-oriented databases allow objects to be shared between processes60 in a distributed environment.

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (8 of 14) [10/13/2002 11:48:18 AM] KEY BENEFITS OF ODBMS (CONT’D)

• Sharing in highly distributed environment • Easier to share and distribute objects than tables

Object Oriented Databases

61

1. Object-oriented databases can reduce the need for paging by enabling only the currently required objects to be loaded into memory (relational databases load in tables containing both the equired data AND other unnecessary data ) ODBMS Relational DBMS

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (9 of 14) [10/13/2002 11:48:18 AM] Object Oriented Databases

KEY BENEFITS OF ODBMS (CONT’D)

• Better memory usage and less paging 1. Object-oriented databases can reduce the need for paging by enabling only the currently required • Bringingobjects only to be objectsloaded into memory of interest(relational databases load in tables containing both the equired data AND other unnecessary data ) ODBMS Relational DBMS

62

http://www.dis.port.ac.uk/~chandler/OOLectures/database/database.htm (9 of 14) [10/13/2002 11:48:18 AM] OBJECT-ORIENTED VS. OBJECT- RELATIONAL

• Object-oriented DBMSs • Did not achieve much success (until now) in the market place • No query support (Indexing, optimization) • No security layer

• Object-relational DBMSs • Better support from big vendors • Tries to make use of all advances in RDBMSs • Indexes, views, triggers, query optimizations, security layer, etc. • Work in progress --- Long way to go

63 MODIFICATIONS TO RDBMS

• Parsing • Type-checking for methods pretty complex

• New rewriting rules including complex types and collections

• Optimization • New algebra operators needed for complex types. • Must know how to integrate them into optimization. • WHERE clause exprs can be expensive! • Selection pushdown may be a bad idea.

64 MODIFICATIONS TO RDBMS (CONT’D)

• Execution • New algebra operators for complex types. • OID generation & reference handling. • Dynamic linking and overriding. • Support objects bigger than 1 page. • Caching of expensive methods.

• Access Methods • Indexes on methods, not just columns. • Indexes over collection hierarchies. • Need indexes for new WHERE clause exprs (not just <, >, =)

• Data Layout • Clustering of nested objects. • Chunking of arrays.

65 Object Database vs. Object-Relational Databases integrity is inherently maintained by the ODBMS. The object model used by the Object Database Management Group in its ODMG-93 standard is derived from the OMG Common Object Model, and the model has been supplemented with bindings for C++, Smalltalk, and Java as well as Object Definition Language (ODL, based on OMG's IDL), the aforementioned OQL, meta-object access, and object interchange.

The SQL3 object model is its own definition, a compromise that adds some object support while maintaining backward compatibility with SQL2. ORDBMSs have limited support for inheritance, with no consistent definition between vendors or with respect to SQL3 (e.g., constructed types). For all vendors, base types are abstract types, supporting inheritance of properties and functions. There is no such agreement for constructed typesCOMPARISON to be abstract types. Table 2

A Comparison of Database Management Systems Criteria RDBMS ORDBMS ODBMS Defining standard SQL2 (ANSI X3H2) SQL3/4 (in process) ODMG-V2.0 Poor; programmers spend 25% of coding Support for object-oriented Limited mostly to new time mapping the Direct and extensive programming data types program object to the database Table structures easy to Same as RDBMS, with OK for programmers; Simplicity of use understand; many end- some confusing some SQL access for user tools available extensions end users Objects are a natural Provides independence Provides independence way to model; can of data from application, of data from application, Simplicity of development accommodate a wide good for simple good for simple variety of types and relationships relationships relationships Can handle arbitrary Limited mostly to new complexity; users can Extensibility and content None data types write methods and on any structure Can handle arbitrary complexity; users can Complex data relationships Difficult to model Difficult to model write methods and on any structure 66

file:///E|/E_book/Database/Articles/Object%20Database%20vs_%20Object-Relational%20Databases.htm (12 of 21) [2/28/2004 5:44:39 PM]