You are on page 1of 32

Chapter9:ObjectBasedDatabases

DatabaseSystemConcepts
Silberschatz,KorthandSudarshan
Seewww.dbbook.comforconditionsonreuse
DatabaseSystemConcepts

Silberschatz,KorthandSudarshan

Chapter9:ObjectBasedDatabases
ComplexDataTypesandObjectOrientation
StructuredDataTypesandInheritanceinSQL
TableInheritance
ArrayandMultisetTypesinSQL
ObjectIdentityandReferenceTypesinSQL
ImplementingORFeatures
PersistentProgrammingLanguages
ComparisonofObjectOrientedandObjectRelationalDatabases

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ObjectRelationalDataModels
Extendtherelationaldatamodelbyincludingobjectorientationand

constructstodealwithaddeddatatypes.

Allowattributesoftuplestohavecomplextypes,includingnonatomic

valuessuchasnestedrelations.

Preserverelationalfoundations,inparticularthedeclarativeaccessto

data,whileextendingmodelingpower.

Upwardcompatibilitywithexistingrelationallanguages.

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ComplexDataTypes
Motivation:

Permitnonatomicdomains(atomicindivisible)
Exampleofnonatomicdomain:setofintegers,orsetof
tuples
Allowsmoreintuitivemodelingforapplicationswith
complexdata

Intuitivedefinition:

allowrelationswheneverweallowatomic(scalar)values
relationswithinrelations

Retainsmathematicalfoundationofrelationalmodel

Violatesfirstnormalform.

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ExampleofaNestedRelation
Example:libraryinformationsystem
Eachbookhas

title,

asetofauthors,

Publisher,and

asetofkeywords

Non1NFrelationbooks

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

4NFDecompositionofNestedRelation
Removeawkwardnessofflatbooksbyassumingthatthefollowing

multivalueddependencieshold:

titleauthor

titlekeyword

titlepubname,pubbranch

Decomposeflatdocinto4NFusingtheschemas:

(title,author)

(title,keyword)

(title,pubname,pubbranch)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

4NFDecompositionofflatbooks

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Problemswith4NFSchema
4NFdesignrequiresuserstoincludejoinsintheirqueries.
1NFrelationalviewflatbooksdefinedbyjoinof4NFrelations:

eliminatestheneedforuserstoperformjoins,
butlosestheonetoonecorrespondencebetweentuplesand
documents.
Andhasalargeamountofredundancy

Nestedrelationsrepresentationismuchmorenaturalhere.

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ComplexTypesandSQL:1999
ExtensionstoSQLtosupportcomplextypesinclude:

Collectionandlargeobjecttypes

Nestedrelationsareanexampleofcollectiontypes

Structuredtypes

Nestedrecordstructureslikecompositeattributes

Inheritance

Objectorientation

Includingobjectidentifiersandreferences

OurdescriptionismainlybasedontheSQL:1999standard

Notfullyimplementedinanydatabasesystemcurrently
Butsomefeaturesarepresentineachofthemajorcommercial
databasesystems

Readthemanualofyourdatabasesystemtoseewhatit
supports

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

StructuredTypesandInheritanceinSQL

StructuredtypescanbedeclaredandusedinSQL

createtypeNameas
(firstnamevarchar(20),
lastnamevarchar(20))

final
createtypeAddressas
(streetvarchar(20),
city
varchar(20),
zipcode varchar(20))
notfinal

Note:finalandnotfinalindicatewhethersubtypescanbecreated

Structuredtypescanbeusedtocreatetableswithcompositeattributes
createtablecustomer(
name
Name,
address Address,
dateOfBirthdate)
Dotnotationusedtoreferencecomponents:name.firstname

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

StructuredTypes(cont.)
Userdefinedrowtypes

createtypeCustomerTypeas(
nameName,
addressAddress,
dateOfBirthdate)
notfinal
Canthencreateatablewhoserowsareauserdefinedtype

createtablecustomerofCustomerType

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Methods
Canaddamethoddeclarationwithastructuredtype.

methodageOnDate(onDatedate)
returnsintervalyear
Methodbodyisgivenseparately.

createinstancemethodageOnDate(onDatedate)
returnsintervalyear
forCustomerType
begin
returnonDateself.dateOfBirth;
end
Wecannowfindtheageofeachcustomer:

selectname.lastname,ageOnDate(current_date)
fromcustomer

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Inheritance

Supposethatwehavethefollowingtypedefinitionforpeople:

create type Person


(name varchar(20),
address varchar(20))
Using inheritance to define the student and teacher types

create type Student


under Person
(degree
varchar(20),
department varchar(20))
create type Teacher
under Person
(salary
integer,
department varchar(20))

Subtypes can redefine methods by using overriding method in place of

method in the method declaration

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

MultipleInheritance
SQL:1999 and SQL:2003 do not support multiple inheritance
If our type system supports multiple inheritance, we can define a type for

teaching assistant as follows:


create type Teaching Assistant
under Student, Teacher

To avoid a conflict between the two occurrences of department we can

rename them

create type Teaching Assistant


under
Student with (department as student_dept ),
Teacher with (department as teacher_dept )

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ConsistencyRequirementsforSubtables
Consistencyrequirementsonsubtablesandsupertables.

Eachtupleofthesupertable(e.g.people)cancorrespondtoatmost
onetupleineachofthesubtables(e.g.studentsandteachers)
AdditionalconstraintinSQL:1999:
Alltuplescorrespondingtoeachother(thatis,withthesamevalues
forinheritedattributes)mustbederivedfromonetuple(insertedinto
onetable).

Thatis,eachentitymusthaveamostspecifictype
Wecannothaveatupleinpeoplecorrespondingtoatupleeach
instudentsandteachers

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ArrayandMultisetTypesinSQL

Exampleofarrayandmultisetdeclaration:

createtypePublisheras
(namevarchar(20),
branchvarchar(20))
createtypeBookas
(titlevarchar(20),
authorarrayvarchar(20)array[10],
pubdatedate,
publisherPublisher,
keywordsetvarchar(20)multiset)

createtablebooksofBook

Similartothenestedrelationbooks,butwitharrayofauthors
insteadofset

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

CreationofCollectionValues
Array construction

array [ Silberschatz ,`Korth ,`Sudarshan ]


Multisets

multisetset [ computer , database , SQL ]

To create a tuple of the type defined by the books relation:

( Compilers , array[`Smith ,`Jones ],


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

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

QueryingCollectionValuedAttributes
Tofindallbooksthathavetheworddatabaseasakeyword,

selecttitle
frombooks
wheredatabasein(unnest(keywordset))
Wecanaccessindividualelementsofanarraybyusingindices

E.g.:Ifweknowthataparticularbookhasthreeauthors,wecouldwrite:
selectauthorarray[1],authorarray[2],authorarray[3]
frombooks
wheretitle=`DatabaseSystemConcepts

Togetarelationcontainingpairsoftheformtitle,authornameforeach

bookandeachauthorofthebook
selectB.title,A.author
frombooksasB,unnest(B.authorarray)asA(author)
Toretainorderinginformationweaddawithordinalityclause

selectB.title,A.author,A.position
frombooksasB,unnest(B.authorarray)withordinalityas
A(author,position)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Unnesting
Thetransformationofanestedrelationintoaformwithfewer(orno)

relationvaluedattributesuscalledunnesting.

E.g.

selecttitle,Aasauthor,publisher.nameaspub_name,
publisher.branchaspub_branch,K.keyword
frombooksasB,unnest(B.author_array)asA(author),
unnest(B.keyword_set)asK(keyword)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Nesting

Nestingistheoppositeofunnesting,creatingacollectionvaluedattribute

NOTE:SQL:1999doesnotsupportnesting

Nestingcanbedoneinamannersimilartoaggregation,butusingthefunction
colect()inplaceofanaggregationoperation,tocreateamultiset

Tonesttheflatbooksrelationontheattributekeyword:

selecttitle,author,Publisher(pub_name,pub_branch)aspublisher,
collect(keyword)askeyword_set
fromflatbooks
groupbytitle,author,publisher
Tonestonbothauthorsandkeywords:
selecttitle,collect(author)asauthor_set,
Publisher(pub_name,pub_branch)aspublisher,

collect(keyword)askeyword_set
fromflatbooks
groupbytitle,publisher

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

1NFVersionofNestedRelation
1NFversionofbooks

flatbooks

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

Nesting(Cont.)
Anotherapproachtocreatingnestedrelationsistousesubqueriesin

theselectclause.

selecttitle,
array(selectauthor
fromauthorsasA
whereA.title=B.title
orderbyA.position)asauthor_array,
Publisher(pubname,pubbranch)aspublisher,
multiset(selectkeyword
fromkeywordsasK
whereK.title=B.title)askeyword_set
frombooks4asB

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ObjectIdentityandReferenceTypes
DefineatypeDepartmentwithafieldnameandafieldheadwhichisa

referencetothetypePerson,withtablepeopleasscope:

createtypeDepartment(
namevarchar(20),
headref(Person)scopepeople)
Wecanthencreateatabledepartmentsasfollows

createtabledepartmentsofDepartment
Wecanomitthedeclarationscopepeoplefromthetypedeclarationand

insteadmakeanadditiontothecreatetablestatement:
createtabledepartmentsofDepartment
(headwithoptionsscopepeople)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

InitializingReferenceTypedValues
Tocreateatuplewithareferencevalue,wecanfirstcreatethetuple

withanullreferenceandthensetthereferenceseparately:
insertintodepartments
values(`CS,null)
updatedepartments
sethead=(selectp.person_id
frompeopleasp
wherename=`John)
wherename=`CS

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

UserGeneratedIdentifiers
Thetypeoftheobjectidentifiermustbespecifiedaspartofthetype

definitionofthereferencedtable,and

Thetabledefinitionmustspecifythatthereferenceisusergenerated

createtypePerson
(namevarchar(20)
addressvarchar(20))
refusingvarchar(20)
createtablepeopleofPerson
refisperson_idusergenerated
Whencreatingatuple,wemustprovideauniquevaluefortheidentifier:

insertintopeople(person_id,name,address)values
(01284567,John,`23CoyoteRun)

Wecanthenusetheidentifiervaluewheninsertingatupleinto

departments
Avoidsneedforaseparatequerytoretrievetheidentifier:
insertintodepartments
values(`CS,`02184567)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

UserGeneratedIdentifiers(Cont.)
Canuseanexistingprimarykeyvalueastheidentifier:

createtypePerson
(namevarchar(20)primarykey,
addressvarchar(20))
reffrom(name)
createtablepeopleofPerson
refisperson_idderived
Wheninsertingatuplefordepartments,wecanthenuse

insertintodepartments
values(`CS,`John)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

PathExpressions
Findthenamesandaddressesoftheheadsofalldepartments:

selecthead >name,head >address


fromdepartments
Anexpressionsuchashead >nameiscalledapathexpression
Pathexpressionshelpavoidexplicitjoins

Ifdepartmentheadwerenotareference,ajoinofdepartments
withpeoplewouldberequiredtogetattheaddress
Makesexpressingthequerymucheasierfortheuser

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ImplementingORFeatures
SimilartohowERfeaturesaremappedontorelationschemas
Subtableimplementation

Eachtablestoresprimarykeyandthoseattributesdefinedinthat
table

or,

Eachtablestoresbothlocallydefinedandinheritedattributes

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

PersistentProgrammingLanguages
Languagesextendedwithconstructstohandlepersistentdata
Programmercanmanipulatepersistentdatadirectly

noneedtofetchitintomemoryandstoreitbacktodisk(unlike
embeddedSQL)

Persistentobjects:

byclassexplicitdeclarationofpersistence

bycreationspecialsyntaxtocreatepersistentobjects

bymarkingmakeobjectspersistentaftercreation

byreachabilityobjectispersistentifitisdeclaredexplicitlytobe
soorisreachablefromapersistentobject

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ObjectIdentityandPointers
Degreesofpermanenceofobjectidentity

Intraprocedure:onlyduringexecutionofasingleprocedure

Intraprogram:onlyduringexecutionofasingleprogramorquery

Interprogram:acrossprogramexecutions,butnotifdatastorage
formatondiskchanges
Persistent:interprogram,pluspersistentacrossdata
reorganizations

PersistentversionsofC++andJavahavebeenimplemented

C++

ODMGC++

ObjectStore

Java

JavaDatabaseObjects(JDO)

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

ComparisonofOOandORDatabases
Relationalsystems

simpledatatypes,powerfulquerylanguages,highprotection.

PersistentprogramminglanguagebasedOODBs

complexdatatypes,integrationwithprogramminglanguage,high
performance.

Objectrelationalsystems

complexdatatypes,powerfulquerylanguages,highprotection.

Note:Manyrealsystemsblurtheseboundaries

E.g.persistentprogramminglanguagebuiltasawrapperona
relationaldatabaseoffersfirsttwobenefits,butmayhavepoor
performance.

DatabaseSystemConcepts5thEdition,Aug9,2005.

9.<number>

Silberschatz,KorthandSudarshan

EndofChapter

DatabaseSystemConcepts
Silberschatz,KorthandSudarshan
Seewww.dbbook.comforconditionsonreuse
DatabaseSystemConcepts

Silberschatz,KorthandSudarshan

You might also like