OOPDBMS
OOPDBMS
8.1!
8.2!
1!
Object-Oriented Data Model!
8.3!
Object Structure!
8.4!
2!
Messages and Methods!
8.5!
Object Classes!
8.6!
3!
Class Definition Example!
!class employee {
!/*Variables */
! !string name;
" "string address;
" "date start-date;
" "int salary;
/* Messages */
! !int annual-salary();
! !string get-name();
! !string get-address();
! !int set-address(string new-address);
" "int employment-length();
};!
■ Methods to read and set the other variables are also needed with
strict encapsulation!
■ Methods are defined separately!
é E.g. int employment-length() { return today() – start-date;}
int set-address(string new-address) { address = new-address;}!
8.7!
Inheritance!
■ E.g., class of bank customers is similar to class of bank
employees, although there are differences !
é both share some variables and messages, e.g., name and address. !
é But there are variables and messages specific to each class e.g.,
salary for employees and credit-rating for customers.!
■ Every employee is a person; thus employee is a specialization of
person"
■ Similarly, customer is a specialization of person.!
■ Create classes person, employee and customer"
é variables/messages applicable to all persons associated with class
person."
é variables/messages specific to employees associated with class
employee; similarly for customer"
8.8!
4!
Inheritance (Cont.)!
8.9!
5!
Class Hierarchy Example (Cont.)!
■ Full variable list for objects in the class officer:"
é office-number, expense-account-number: defined locally!
é start-date, salary: inherited from employee"
é name, address: inherited from person!
■ Methods inherited similar to variables.!
■ Substitutability — any method of a class, say person, can be invoked
equally well with any object belonging to any subclass, such as
subclass officer of person."
■ Class extent: set of all objects in the class. Two options:!
1. !Class extent of employee includes all officer, teller and secretary objects.!
2. Class extent of employee includes only employee objects that are not in a
subclass such as officer, teller, or secretary"
★ This is the usual choice in OO systems!
★ Can access extents of subclasses to find all objects of
subtypes of employee!
8.11!
8.12!
6!
Multiple Inheritance!
■ With multiple inheritance a class may have more than one superclass.!
é The class/subclass relationship is represented by a directed acyclic graph
(DAG) !
é Particularly useful when objects can be classified in more than one way,
which are independent of each other !
Ø E.g. temporary/permanent is independent of Officer/secretary/teller!
Ø Create a subclass for each combination of subclasses !
– Need not create subclasses for combinations that are not possible in
the database being modeled!
■ A class inherits variables and methods from all its superclasses!
■ There is potential for ambiguity when a variable/message N with the
same name is inherited from two superclasses A and B!
é No problem if the variable/message is defined in a shared superclass!
é Otherwise, do one of the following!
Ø flag as an error,!
Ø rename variables (A.N and B.N)!
Ø choose one.!
8.13!
8.14!
7!
Object Identity!
8.15!
Object Identifiers!
■ Object identifiers used to uniquely identify objects!
é Object identifiers are unique: !
Ø no two objects have the same identifier!
Ø each object has only one object identifier!
é E.g., the spouse field of a person object may be an identifier of
another person object.!
é can be stored as a field of an object, to refer to another object.!
é Can be !
Ø system generated (created by database) or !
Ø external (such as social-security number)!
é System generated identifiers:!
Ø Are easier to use, but cannot be used across database systems!
Ø May be redundant if unique identifier already exists!
8.16!
8!
Object Containment!
8.17!
Object-Oriented Languages!
8.18!
9!
Persistent Programming Languages!
8.19!
8.20!
10!
Persistence of Objects!
8.21!
8.22!
11!
Object Identity and Pointers (Cont.)!
8.23!
8.24!
12!
Persistent C++ Systems!
■ C++ language allows support for persistence to be added without
changing the language!
é Declare a class called Persistent_Object with attributes and methods
to support persistence!
é Overloading – ability to redefine standard function names and
operators (i.e., +, –, the pointer deference operator –>) when applied
to new types!
é Template classes help to build a type-safe type system supporting
collections and persistent types.!
■ Providing persistence without extending the C++ language is !
é relatively easy to implement!
é but more difficult to use!
■ Persistent C++ systems that add features to the C++ language
have been built, as also systems that avoid changing the
language!
8.25!
8.26!
13!
ODMG Types!
8.27!
8.28!
14!
ODMG C++ ODL: Example (Cont.)!
8.29!
Implementing Relationships!
8.30!
15!
Implementing Relationships!
■ E.g.!
!extern const char _owners[ ], _accounts[ ];
class Account : public d.Object {
….
d_Rel_Set <Customer, _accounts> owners;
}
// .. Since strings can’t be used in templates …
const char _owners= “owners”;
const char _accounts= “accounts”;
8.31!
8.32!
16!
ODMG C++OML: Database and Object
Functions!
■ Class d_Database provides methods to !
é open a database: open(databasename) !
é give names to objects: set_object_name(object, name)!
é look up objects by name: lookup_object(name)!
é rename objects: rename_object(oldname, newname)!
é close a database (close());!
■ Class d_Object is inherited by all persistent classes.!
é provides methods to allocate and delete objects!
é method mark_modified() must be called before an object is
updated. !
Ø Is automatically called when object is created!
8.33!
Trans.commit();
}
8.34!
17!
ODMG C++ OML: Example (Cont.)!
8.35!
int print_customers() {
Database bank_db_obj;
Database * bank_db = &bank_db_obj;
bank_db->open (“Bank-DB”);
d_Transaction Trans; Trans.begin ();
d_Extent<Customer> all_customers(bank_db);
d_Iterator<d_Ref<Customer>> iter;
iter = all_customers–>create_iterator();
d_Ref <Customer> p;
while{iter.next (p))
print_cust (p); // Function assumed to be defined elsewhere
Trans.commit();
}
8.36!
18!
ODMG C++ Binding: Other Features!
■ Declarative query language OQL, looks like SQL !
é Form query as a string, and execute it to get a set of results
(actually a bag, since duplicates may be present) !
!d_Set<d_Ref<Account>> result;
d_OQL_Query q1("select a
from Customer c, c.accounts a
where c.name=‘Jones’
and a.find_balance() > 100");
d_oql_execute(q1, result);
■ Provides error handling mechanism based on C++ exceptions,
through class d_Error
■ Provides API for accessing the schema of a database.!
8.37!
8.38!
19!
Persistent Java Systems!
8.39!
ODMG Java!
8.40!
20!
Object-Relational Databases!
■ Nested Relations!
■ Complex Types and Object Orientation!
■ Querying with Complex Types!
■ Creation of Complex Values and Objects!
■ Comparison of Object-Oriented and Object-Relational
Databases!
8.41!
8.42!
21!
Nested Relations!
■ Motivation:!
é Permit non-atomic domains (atomic ≡ indivisible)!
é Example of non-atomic domain: set of integers,or set of
tuples!
é Allows more intuitive modeling for applications with
complex data!
■ Intuitive definition:!
é allow relations whenever we allow atomic (scalar) values
— relations within relations!
é Retains mathematical foundation of relational model !
é Violates first normal form.!
8.43!
8.44!
22!
1NF Version of Nested Relation!
flat-books!
8.45!
8.46!
23!
4NF Decomposition of flat–books!
8.47!
8.48!
24!
Complex Types and SQL:1999!
■ Extensions to SQL to support complex types include:!
é Collection and large object types!
Ø Nested relations are an example of collection types!
é Structured types!
Ø Nested record structures like composite attributes !
é Inheritance!
é Object orientation!
Ø Including object identifiers and references!
■ Our description is mainly based on the SQL:1999 standard!
é Not fully implemented in any database system currently!
é But some features are present in each of the major commercial
database systems!
Ø Read the manual of your database system to see what it
supports!
é We present some features that are not in SQL:1999!
Ø These are noted explicitly!
8.49!
Collection Types!
■ Set type (not in SQL:1999)!
create table books (
…..
keyword-set setof(varchar(20))
……
)
■ Sets are an instance of collection types. Other instances include
é Arrays (are supported in SQL:1999)
Ø E.g. author-array varchar(20) array[10]
Ø Can access elements of array in usual fashion:
– E.g. author-array[1]
é Multisets (not supported in SQL:1999)
Ø I.e., unordered collections, where an element may occur multiple
times
é Nested relations are sets of tuples
Ø SQL:1999 supports arrays of tuples
8.50!
25!
Large Object Types!
8.51!
8.52!
26!
Structured and Collection Types (Cont.)!
8.53!
8.54!
27!
Creation of Values of Complex Types!
■ Values of structured types are created using constructor functions
é E.g. Publisher(‘McGraw-Hill’, ‘New York’)
é Note: a value is not an object
■ SQL:1999 constructor functions
é E.g.
create function Publisher (n varchar(20), b varchar(20))
returns Publisher
begin
set name=n;
set branch=b;
end
é Every structured type has a default constructor with no arguments,
others can be defined as required
■ Values of row type can be constructed by listing values in parantheses
é E.g. given row type row (name varchar(20),
branch varchar(20))!
é We can assign (`McGraw-Hill’,`New York’) as a value of above type
8.55!
8.56!
28!
Inheritance!
■ Suppose that we have the following type definition for people:!
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
8.57!
Multiple Inheritance!
■ SQL:1999 does 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)
8.58!
29!
Table Inheritance!
■ Table inheritance allows an object to have multiple types by
allowing an entity to exist in more than one table at once.!
■ E.g. people table: create table people of Person
■ We can then define the students and teachers tables as
subtables of people!
! !create table students of Student
under people
create table teachers of Teacher
under people
■ Each tuple in a subtable (e.g. students and teachers) is implicitly
present in its supertables (e.g. people)"
■ Multiple inheritance is possible with tables, just as it is possible with
types.
create table teaching-assistants of Teaching Assistant
under students, teachers
é Multiple inheritance not supported in SQL:1999
8.59!
8.60!
30!
Table Inheritance: Consistency Requirements!
8.61!
■ Storage alternatives!
1. Store only local attributes and the primary key of the supertable in
subtable!
Ø Inherited attributes derived by means of a join with the
supertable!
2. Each table stores all inherited and locally defined attributes!
Ø Supertables implicitly contain (inherited attributes of) all tuples in
their subtables!
Ø Access to all attributes of a tuple is faster: no join required!
Ø If entities must have most specific type, tuple is stored only in
one table, where it was created!
★ Otherwise, there could be redundancy!
8.62!
31!
Reference Types!
■ We will study how to define references first, and later see how to use
references!
8.63!
8.64!
32!
Initializing Reference Typed Values!
■ In Oracle, to create a tuple with a reference value, we can first
create the tuple with a null reference and then set the reference
separately by using the function ref(p) applied to a tuple variable!
■ E.g. to create a department with name CS and head being the
person named John, we use!
!insert into departments"
! values (`CS’, null)!
!update departments"
! set head = (select ref(p)!
! ! from people as p"
! ! ! where name=`John’)!
! where name = `CS’!
8.65!
8.66!
33!
User Generated Identifiers!
■ SQL:1999 allows object identifiers to be user-generated!
é The type of the object-identifier must be specified as part of the type
definition of the referenced table, and!
é The table definition must specify that the reference is user generated!
é E.g. !
! create type Person
(name varchar(20)
address varchar(20))
ref using varchar(20)
create table people of Person
ref is oid user generated!
■ When creating a tuple, we must provide a unique value for the
identifier (assumed to be the first attribute):!
insert into people values
(‘01284567’, ‘John’, `23 Coyote Run’)!
!!
8.67!
8.68!
34!
Path Expressions!
8.69!
■ Find the title and the name of the publisher of each book. !
! !select title, publisher.name
"from books"
Note the use of the dot notation to access fields of the composite
attribute (structured type) publisher"
8.70!
35!
Collection-Value Attributes!
■ Collection-valued attributes can be treated much like relations, using
the keyword unnest!
é The books relation has array-valued attribute author-array and set-
valued attribute keyword-set!
■ To find all books that have the word “database” as one of their
keywords, ! !
select title
"from books
"where ‘database’ in (unnest(keyword-set))!
é Note: Above syntax is valid in SQL:1999, but the only collection type
supported by SQL:1999 is the array type !
■ To get a relation containing pairs of the form “title, author-name” for
each book and each author of the book!
select B.title, A
" from books as B, unnest (B.author-array) as A!
! !!
8.71!
8.72!
36!
Unnesting!
■ The transformation of a nested relation into a form with fewer (or no)
relation-valued attributes us called unnesting.!
■ E.g.!
select title, A as author, publisher.name as pub_name,
publisher.branch as pub_branch, K as keyword"
from books as B, unnest(B.author-array) as A, unnest (B.keyword-
list) as K"
8.73!
Nesting!
■ Nesting is the opposite of unnesting, creating a collection-valued attribute!
■ NOTE: SQL:1999 does not support nesting!
■ Nesting can be done in a manner similar to aggregation, but using the
function set() in place of an aggregation operation, to create a set!
■ To nest the flat-books relation on the attribute keyword:!
!select title, author, Publisher(pub_name, pub_branch) as publisher,
set(keyword) as keyword-list
from flat-books
groupby title, author, publisher"
■ To nest on both authors and keywords:!
select title, set(author) as author-list,
Publisher(pub_name, pub_branch) as publisher,
set(keyword) as keyword-list
from flat-books
groupby title, publisher"
8.74!
37!
Nesting (Cont.)!
8.75!
8.76!
38!
SQL Functions!
■ Define a function that, given a book title, returns the count of the
number of authors (on the 4NF schema with relations books4
and authors).!
create function author-count(name varchar(20))
returns integer
begin
declare a-count integer;
select count(author) into a-count
from authors
where authors.title=name
return a=count;
end!
■ Find the titles of all books that have more than one author.!
! !select name
"from books4
"where author-count(title)> 1"
8.77!
SQL Methods!
8.78!
39!
SQL Functions and Procedures (cont.)!
■ The author-count function could instead be written as procedure:!
!create procedure author-count-proc (in title varchar(20),
out a-count integer)
begin
! select count(author) into a-count
from authors
where authors.title = title
end!
■ Procedures can be invoked either from an SQL procedure or from
embedded SQL, using the call statement.!
é E.g. from an SQL procedure!
! !declare a-count integer;
!call author-count-proc(`Database systems Concepts’, a-count);!
■ SQL:1999 allows more than one function/procedure of the same name
(called name overloading), as long as the number of
arguments differ, or at least the types of the arguments differ!
8.79!
8.80!
40!
External Language Routines (Cont.)!
■ Benefits of external language functions/procedures: !
é more efficient for many operations, and more expressive
power!
■ Drawbacks!
é Code to implement function may need to be loaded into
database system and executed in the database system’s
address space!
Ø risk of accidental corruption of database structures!
Ø security risk, allowing users access to unauthorized data!
é There are alternatives, which give good security at the cost of
potentially worse performance!
é Direct execution in the database system’s space is used
when efficiency is more important than security!
8.81!
8.82!
41!
Procedural Constructs!
■ SQL:1999 supports a rich variety of procedural constructs
■ Compound statement
é is of the form begin … end,
é may contain multiple SQL statements between begin and end.
é Local variables can be declared within a compound statements
■ While and repeat statements
declare n integer default 0;
while n < 10 do
set n = n+1
end while
repeat
set n = n – 1
until n = 0
end repeat
8.83!
■ For loop
é Permits iteration over all results of a query
é E.g. find total of all balances at the Perryridge branch
8.84!
42!
Procedural Constructs (cont.)!
■ Conditional statements (if-then-else)
E.g. To find sum of balances for each of three categories of accounts
(with balance <1000, >=1000 and <5000, >= 5000)!
! !if r.balance < 1000
! then set l = l + r.balance
"elseif r.balance < 5000
! then set m = m + r.balance
"else set h = h + r.balance
"end if !
■ SQL:1999 also supports a case statement similar to C case statement!
■ Signaling of exception conditions, and declaring handlers for exceptions!
! !declare out_of_stock condition
!declare exit handler for out_of_stock
"begin
!…
.. signal out-of-stock
!end!
é The handler here is exit -- causes enclosing begin..end to be exited!
é Other actions possible on exception!
8.85!
8.86!
43!
Finding all employees of a manager!
■ Procedure to find all employees who work directly or indirectly for mgr "
■ Relation manager(empname, mgrname)specifies who directly works for whom!
■ Result is stored in empl(name)!
!create procedure findEmp(in mgr char(10))
begin
!create temporary table newemp(name char(10));
!create temporary table temp(name char(10));
!insert into newemp -- store all direct employees of mgr in newemp
" select empname
" from manager
" where mgrname = mgr
"!
8.87!
8.88!
44!
■ Slides adapted from!
8.89!
45!