OBJECT-ORIENTED & OBJECT- RELATIONAL DATABASES
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 database 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, query optimization, and theory
• What is missing?? • Handling of complex objects • Handling of complex data types • Code is not coupled with data • No inherence, encapsulation, etc.
5 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 DATABASE DESIGN PROCESS
Application Domain or Universe of Discourse
using ER model or UML
Data Modelling
Conceptual Model
using Data Model of the target DBMS
Logical Database Design
Logical Model
DBMS specific resource-based optimization Physical Database Design
Physical Model 9 LOGICAL & PHYSICAL LAYERS
Relational SQL ER diagram Normalization & RDBMS database design Physical design table 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 database schema Optimization OODBMS in ODL
10 EXAMPLE OF UML CLASSES
Person Class Name
name: {firstName: string, middleName: string, Attributes lastName: string} address: string birthDate: date
age(): Integer Operations changeAddress(newAdd: string)
p:Person A Person object
name: {Norman, William, Preston} address: Stockport birthDate: 11-JUN-70
11 FIRST APPROACH: OBJECT-ORIENTED MODEL
• Relations are not the central concept, classes and objects are the main concept
• Object-Oriented DBMS(OODBMS) are DBMS based on an Object- Oriented Data Model inspired by OO programming languages
• Main Features: • Powerful type system • Classes • Object Identity • Inheritance
• OODBMS are capable of storing complex objects, I.e., objects that are composed of other objects, and/or multi-valued attributes. 12 FEATURE 1: POWERFUL TYPE SYSTEM
• Primitive types • Integer, string, date, Boolean, float, etc.
• Structure type • Attribute can be a record with a schema Struct {integer x, string y} • Collection type • Attribute can be a Set, Bag, List, Array of other types
• Reference type • Attribute can be a Pointer to another object
13 FEATURE 2: CLASSES
• A ‘class’ is in replacement of ‘relation’
• Same concept as in OO programming languages • All objects belonging to a same class share the same properties and behavior
• An ‘object’ can be thought of as ‘tuple’ (but richer content)
• Classes encapsulate data + methods + relationships • Unlike relations that contain data only
• In OODBMSs objects are persistency (unlike OO programming languages)
14 FEATURE 3: OBJECT IDENTITY
• OID is a unique identity of each object regardless of its content • Even if all attributes are the same, still objects have different OIDs
• Easier for references
• An object is made of two things: • State: attributes (name, address, birthDate of a person) • Behaviour: operations (age of a person is computed from birthDate and current date)
15 FEATURE 4: INHERITANCE
• A class can be defined in terms of Person 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 object database • ODL: Object Definition Language • OQL: Object Query Language
• ODL is somehow similar to DDL (Data Definition Language) in SQL
17 Overview of ODL & OQL
18 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 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 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 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 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 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 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 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 \ 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 tuples. 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) subset 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 synonym 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 Set 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 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 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 partition 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 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 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 cursor-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 • 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 information 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 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 view, 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 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 • 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 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 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 * 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 * 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 • 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 * 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 * 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) 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. 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 • Query Rewriting • 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] { ("Gone With the Wind", 1939, 231, color)