1 object-relational databases user-defined types nested tables
TRANSCRIPT
1
Object-Relational Object-Relational DatabasesDatabases
User-Defined TypesUser-Defined Types
Nested TablesNested Tables
2
Merging Relational and Merging Relational and Object ModelsObject Models
Object-oriented models support Object-oriented models support interesting data types --- not just flat interesting data types --- not just flat files.files. Structs, collectionsStructs, collections
The relational model supports very-The relational model supports very-high-level queries.high-level queries.
Object-relational databases are an Object-relational databases are an attempt to get the best of both.attempt to get the best of both.
3
Evolution of DBMS’sEvolution of DBMS’s
Object-oriented DBMS’s failed because Object-oriented DBMS’s failed because they did not offer the efficiencies of well-they did not offer the efficiencies of well-entrenched relational DBMS’s.entrenched relational DBMS’s.
Object-relational extensions to relational Object-relational extensions to relational DBMS’s capture much of the advantages DBMS’s capture much of the advantages of OO, yet retain the relation as the of OO, yet retain the relation as the fundamental abstraction.fundamental abstraction.
4
SQL-99 and Oracle FeaturesSQL-99 and Oracle Features
SQL-99 includes many of the object-SQL-99 includes many of the object-relational features to be described.relational features to be described.
However, being so new, different DBMS’s However, being so new, different DBMS’s use different approaches.use different approaches. We’ll sometimes use features and syntax from We’ll sometimes use features and syntax from
Oracle.Oracle.
5
User-Defined Data TypesUser-Defined Data Types
A A user-defined data typeuser-defined data type, or UDT, is , or UDT, is essentially a class definition, with a essentially a class definition, with a structure and methods.structure and methods.
Two uses:Two uses:1.1. As a As a rowtyperowtype, that is, the type of a relation., that is, the type of a relation.
2.2. As the type of an attribute of a relation.As the type of an attribute of a relation.
6
UDT DefinitionUDT Definition
CREATE TYPE <typename> AS (CREATE TYPE <typename> AS (
<list of elements, as in CREATE TABLE><list of elements, as in CREATE TABLE>
);); Oracle syntax:Oracle syntax:
1.1. Add “OBJECT” in CREATE … AS OBJECT.Add “OBJECT” in CREATE … AS OBJECT.
2.2. Example:Example:create or replace type Point as object ( create or replace type Point as object (
x number, x number,
y number); y number);
7
Example: UDT DefinitionExample: UDT Definition
CREATE TYPE StudentType AS (CREATE TYPE StudentType AS (name name CHAR(20),CHAR(20),addraddr CHAR(20),CHAR(20),
class_level CHARclass_level CHAR););CREATE TYPE CourseType AS (CREATE TYPE CourseType AS (
numbernumber CHAR(20),CHAR(20),locationlocation CHAR(20)CHAR(20)
););
8
ReferencesReferences
If If TT is a type, then REF is a type, then REF TT is the type of a is the type of a reference to reference to TT, that is, a pointer to an , that is, a pointer to an object of type object of type TT..
Often called an “object ID” in OO systems.Often called an “object ID” in OO systems. Unlike object ID’s, a REF is visible, Unlike object ID’s, a REF is visible,
although it is usually gibberish.although it is usually gibberish.
9
Example: REFExample: REF
CREATE TYPE EnrollmentType AS (CREATE TYPE EnrollmentType AS (
studentstudent REF StudentType,REF StudentType,
coursecourse REF CourseType,REF CourseType,
gradegrade FLOATFLOAT
);); EnrollmentType objects look like:EnrollmentType objects look like:
93.00
To a StudentTypeobject To a CoureType
object
10
UDT’s as RowtypesUDT’s as Rowtypes
A table may be defined to have a schema A table may be defined to have a schema that is a rowtype, rather than by listing its that is a rowtype, rather than by listing its elements.elements.
Syntax:Syntax:
CREATE TABLE <table name> OFCREATE TABLE <table name> OF
<type name>;<type name>;
11
Example: Creating a Example: Creating a RelationRelation
CREATE TABLE Student OF StudentType;CREATE TABLE Student OF StudentType;
CREATE TABLE Course OF CourseType;CREATE TABLE Course OF CourseType;
CREATE TABLE Enrollment OF CREATE TABLE Enrollment OF EnrollmentType;EnrollmentType;
12
Values of Relations with a Values of Relations with a RowtypeRowtype
Technically, a relation like Student, Technically, a relation like Student, declared to have a rowtype StudentType, declared to have a rowtype StudentType, is not a set of tuples --- it is a unary is not a set of tuples --- it is a unary relation, whose tuples are objects with relation, whose tuples are objects with components: name, addr ...components: name, addr ...
Each UDT has a Each UDT has a type constructortype constructor of the of the same name that wraps objects of that same name that wraps objects of that type.type.
13
Example: Type ConstructorExample: Type Constructor
The queryThe query
SELECT * FROM Student;SELECT * FROM Student; Produces “tuples” such as:Produces “tuples” such as:
StudentType(’Mike’, ’Maple St’, ‘U’)StudentType(’Mike’, ’Maple St’, ‘U’)
14
Accessing Values From a Accessing Values From a RowtypeRowtype
In Oracle, the dot works as expected.In Oracle, the dot works as expected.
Example:Example:
SELECT s.name, s.addrSELECT s.name, s.addr
FROM Student s;FROM Student s;
15
Accessing Values: SQL-99 Accessing Values: SQL-99 ApproachApproach
In SQL-99, each attribute of a UDT has In SQL-99, each attribute of a UDT has generatorgenerator (get the value) and (get the value) and mutatormutator (change the value) methods of the same (change the value) methods of the same name as the attribute.name as the attribute. The generator for The generator for AA takes no argument, as A(). takes no argument, as A(). The mutator for A takes a new value as The mutator for A takes a new value as
argument, as A(v).argument, as A(v).
16
Example: SQL-99 Value AccessExample: SQL-99 Value Access The same query in SQL-99 isThe same query in SQL-99 is
SELECT s.name(), s.addr()SELECT s.name(), s.addr()
FROM Student s;FROM Student s;
17
Inserting Rowtype ValuesInserting Rowtype Values
In Oracle, we can use a standard In Oracle, we can use a standard INSERT statement, remembering that a INSERT statement, remembering that a relation with a rowtype is really unary relation with a rowtype is really unary and needs that type constructor.and needs that type constructor.
Example:Example:
INSERT INTO Student VALUES(INSERT INTO Student VALUES(
StudentType(’Mike’, ’Maple StudentType(’Mike’, ’Maple St.’,’U’)St.’,’U’)
););
18
Inserting Values: SQL-99 Inserting Values: SQL-99 StyleStyle
1.1. Create a variable Create a variable XX of the suitable type, of the suitable type, using the constructor method for that using the constructor method for that type.type.
2.2. Use the mutator methods for the Use the mutator methods for the attributes to set the values of the fields attributes to set the values of the fields of of XX..
3.3. Insert Insert XX into the relation. into the relation.
19
The following must be part of a The following must be part of a procedure, e.g., PSM, so we have a procedure, e.g., PSM, so we have a variable newStudent.variable newStudent.
SET newStudent = StudentType();SET newStudent = StudentType();
newStudent.name(’Mike’);newStudent.name(’Mike’);
newStudent.addr(’Maple St.’);newStudent.addr(’Maple St.’);
newStudent.class(’U’);newStudent.class(’U’);
INSERT INTO Student VALUES(newStudent);INSERT INTO Student VALUES(newStudent);
Mutator methodschange newStudent’sName, addr, and classcomponents.
Example: SQL-99 InsertExample: SQL-99 Insert
20
UDT’s as Column TypesUDT’s as Column Types
A UDT can be the type of an attribute.A UDT can be the type of an attribute. In either another UDT definition, or in a In either another UDT definition, or in a
CREATE TABLE statement, use the name of CREATE TABLE statement, use the name of the UDT as the type of the attribute.the UDT as the type of the attribute.
21
Values of addr andfavCourse componentsare objects with their own fields.
Example: Column TypeExample: Column Type
CREATE TYPE AddrType AS (CREATE TYPE AddrType AS (streetstreetCHAR(30),CHAR(30),citycity CHAR(20),CHAR(20),zipzip INTINT
););CREATE TABLE Student (CREATE TABLE Student (
namename CHAR(30),CHAR(30),addraddr AddrType,AddrType,favCourefavCoure CourseTypeCourseType
););
22
Oracle Problem With Field Oracle Problem With Field AccessAccess
You can access a field You can access a field FF of an object that of an object that is the value of an attribute is the value of an attribute AA by by A.FA.F . .
However, you must use an alias, say However, you must use an alias, say rrrr, , for the relation for the relation RR with attribute with attribute AA, as , as rr.A.Frr.A.F . .
23
Example: Field Access in Example: Field Access in OracleOracle
Wrong:Wrong:SELECT favCourse.numberSELECT favCourse.numberFROM Student;FROM Student;
Wrong:Wrong:SELECT Student.favCourse.numberSELECT Student.favCourse.numberFROM Student;FROM Student;
Right:Right:SELECT s.favCourse.numberSELECT s.favCourse.numberFROM Student s;FROM Student s;
24
Following REF’sFollowing REF’s
AA -> -> BB makes sense if: makes sense if:1.1. AA is of type REF is of type REF TT..
2.2. BB is an attribute (component) of objects of is an attribute (component) of objects of type type TT..
Denotes the value of the Denotes the value of the BB component component of the object pointed to by of the object pointed to by AA..
25
Remember: Enrollment is a relation with Remember: Enrollment is a relation with rowtype EnrollmentType(student, course, rowtype EnrollmentType(student, course, price), where student and course are price), where student and course are REF’s to objects of types StudentType REF’s to objects of types StudentType and CourseType.and CourseType.
Find the courses took by Joe:Find the courses took by Joe:
SELECT e.course()->numberSELECT e.course()->number
FROM Enrollment eFROM Enrollment e
WHERE e.student()->name = ’Joe’;WHERE e.student()->name = ’Joe’;
Then use thearrow to get thenumbers of the coursesand student referenced
First, use generator methods toaccess the course and student components
Example: Following REF’sExample: Following REF’s
26
Following REF’s: Oracle Following REF’s: Oracle StyleStyle
REF-following is implicit in the dot.REF-following is implicit in the dot. Just follow a REF by a dot and a field of the Just follow a REF by a dot and a field of the
object referred to.object referred to. Example:Example:
SELECT e.course.numberSELECT e.course.number
FROM Enrollment eFROM Enrollment e
WHERE e.student.name = ’Joe’;WHERE e.student.name = ’Joe’;
27
Oracle’s DEREF Operator -- Oracle’s DEREF Operator -- MotivationMotivation
If we want the set of courses objects took If we want the set of courses objects took by Joe, we might try:by Joe, we might try:
SELECT e.courseSELECT e.course
FROM Enrollment eFROM Enrollment e
WHERE e.student.name = ’Joe’;WHERE e.student.name = ’Joe’; Legal, but e.course is a set of REF, hence Legal, but e.course is a set of REF, hence
gibberish.gibberish.
28
Using DEREFUsing DEREF
To see the CourseType objects, use:To see the CourseType objects, use:
SELECT DEREF(e.course)SELECT DEREF(e.course)
FROM Enrollment eFROM Enrollment e
WHERE e.student.name = ’Joe’;WHERE e.student.name = ’Joe’; Produces values like:Produces values like:
CourseType(00101,’Database CourseType(00101,’Database Design’,’GAB205’)Design’,’GAB205’)
29
Methods --- Oracle SyntaxMethods --- Oracle Syntax
Classes are more than structures; they Classes are more than structures; they may have methods.may have methods.
We’ll study the Oracle syntax. Declare in We’ll study the Oracle syntax. Declare in CREATE TYPE, and define methods in a CREATE TYPE, and define methods in a CREATE TYPE BODY statement.CREATE TYPE BODY statement. Use PL/SQL syntax for methods.Use PL/SQL syntax for methods. Variable SELF refers to the object to which the Variable SELF refers to the object to which the
method is applied.method is applied.
30
Let’s add method gradeInScale to Enrollment.Let’s add method gradeInScale to Enrollment.CREATE TYPE EnrollmentType AS OBJECT (CREATE TYPE EnrollmentType AS OBJECT (
student student REF StudentType,REF StudentType,
coursecourse REF CourseType,REF CourseType,
gradegrade FLOAT,FLOAT,
MEMBER FUNCTION gradeInScale(scale IN FLOAT) MEMBER FUNCTION gradeInScale(scale IN FLOAT) RETURN FLOAT,RETURN FLOAT,
PRAGMA RESTRICT_REFERENCES(gradeInSacle, WNDS)PRAGMA RESTRICT_REFERENCES(gradeInSacle, WNDS)
););
//“ Write no database state.”That is, whatever gradeInScale doesit won’t modify the database.
What Oracle callsmethods.
Example: Method Example: Method DeclarationDeclaration
31
Method Definition – Oracle Method Definition – Oracle StyleStyle
Form of create-body statement:Form of create-body statement:
CREATE TYPE BODY <type name> ASCREATE TYPE BODY <type name> AS<method definitions = PL/SQL <method definitions = PL/SQL procedure procedure definitions, usingdefinitions, using
““MEMBER FUNCTION” in place ofMEMBER FUNCTION” in place of
““PROCEDURE”>PROCEDURE”>
END;END;
//
32
CREATE TYPE BODY EnrollmentType ASCREATE TYPE BODY EnrollmentType AS
MEMBER FUNCTIONMEMBER FUNCTION
gradeInScale(scale FLOAT) RETURN FLOAT ISgradeInScale(scale FLOAT) RETURN FLOAT IS
BEGINBEGIN
RETURN scale* SELF.grade/100.0;RETURN scale* SELF.grade/100.0;
END;END;
END;END;
// Use parentheses onlywhen there is atleast one argument
No mode (IN)in body, justin declaration
Example: Method DefinitionExample: Method Definition
33
Method UseMethod Use
Follow a name for an object by a dot Follow a name for an object by a dot and the name of the method, with and the name of the method, with arguments if any.arguments if any.
Example:Example:SELECT e.course.number, SELECT e.course.number, e.course.gradeInScale(4)e.course.gradeInScale(4)
FROM Enrollment eFROM Enrollment e
WHERE e.student.name = ’Joe’;WHERE e.student.name = ’Joe’;
34
Order Methods: SQL-99Order Methods: SQL-99
Each UDT Each UDT TT may define two methods may define two methods called EQUAL and LESSTHAN.called EQUAL and LESSTHAN. Each takes an argument of type Each takes an argument of type TT and is and is
applied to another object of type applied to another object of type TT.. Returns TRUE if and only if the target object is Returns TRUE if and only if the target object is
= (resp. <) the argument object.= (resp. <) the argument object. Allows objects of type T to be compared Allows objects of type T to be compared
by =, <, etc. in WHERE clauses and for by =, <, etc. in WHERE clauses and for sorting (ORDER BY).sorting (ORDER BY).
35
Order Methods: OracleOrder Methods: Oracle
We may declare any one method for any We may declare any one method for any UDT to be an UDT to be an order methodorder method..
The order method returns a value <0, =0, The order method returns a value <0, =0, or >0, as the value of object SELF is <, =, or >0, as the value of object SELF is <, =, or > the argument object.or > the argument object.
36
Order StudentType objects by name:Order StudentType objects by name:CREATE TYPE StudentType AS OBJECT (CREATE TYPE StudentType AS OBJECT (
namename CHAR(20),CHAR(20),
addraddr CHAR(20),CHAR(20),
ORDER MEMBER FUNCTION before(ORDER MEMBER FUNCTION before(
s2 IN StudentType) RETURN INT,s2 IN StudentType) RETURN INT,
PRAGMA RESTRICT_REFERENCES(before,PRAGMA RESTRICT_REFERENCES(before,
WNDS, RNDS, WNPS, RNPS)WNDS, RNDS, WNPS, RNPS)
););
// Read/write no database state/package state. A“package” is a collection of procedures and variablesthat can communicate values among them.
Example: Order Method Example: Order Method DeclarationDeclaration
37
Example: Order Method Example: Order Method DefinitionDefinition
CREATE TYPE BODY StudentType ASCREATE TYPE BODY StudentType AS
ORDER MEMBER FUNCTIONORDER MEMBER FUNCTION
before(s2 StudentType) RETURN INT ISbefore(s2 StudentType) RETURN INT IS
BEGINBEGIN
IF SELF.name < s2.name THEN RETURN –1;IF SELF.name < s2.name THEN RETURN –1;
ELSIF SELF.name = s2.name THEN RETURN 0;ELSIF SELF.name = s2.name THEN RETURN 0;
ELSE RETURN 1;ELSE RETURN 1;
END IF;END IF;
END;END;
END;END;
//
38
Oracle Nested TablesOracle Nested Tables
Allows values of tuple components to be Allows values of tuple components to be whole relations.whole relations.
If If TT is a UDT, we can create a type is a UDT, we can create a type SS whose values are relations with rowtype whose values are relations with rowtype TT, , by:by:
CREATE TYPE CREATE TYPE SS AS TABLE OF AS TABLE OF TT ; ;
39
Example: Nested Table Example: Nested Table TypeType
CREATE TYPE StudentType AS OBJECT (CREATE TYPE StudentType AS OBJECT (namename CHAR(20),CHAR(20),addressaddress CHAR(10),CHAR(10),class_levelclass_level CHAR(10)CHAR(10)
););//CREATE TYPE StudentTableType AS CREATE TYPE StudentTableType AS
TABLE OF StudentType;TABLE OF StudentType;//
40
Example --- ContinuedExample --- Continued
Use StudentTableType in a Department Use StudentTableType in a Department relation that stores the set of students by relation that stores the set of students by each department in one tuple for that each department in one tuple for that department.department.
CREATE TABLE Department (CREATE TABLE Department (
namename CHAR(30),CHAR(30),
addraddr CHAR(50),CHAR(50),
studentsstudents StudentTableTypeStudentTableType
););
41
Storing Nested RelationsStoring Nested Relations
Oracle doesn’t really store each nested Oracle doesn’t really store each nested table as a separate relation --- it just table as a separate relation --- it just makes it look that way.makes it look that way.
Rather, there is one relation Rather, there is one relation R R in which in which all the tuples of all the nested tables for all the tuples of all the nested tables for one attribute one attribute AA are stored. are stored.
Declare in CREATE TABLE by:Declare in CREATE TABLE by:
NESTED TABLE NESTED TABLE AA STORE AS STORE AS RR
42
Example: Storing Nested Example: Storing Nested TablesTables
CREATE TABLE Manfs (CREATE TABLE Manfs (
namename CHAR(30),CHAR(30),
addraddr CHAR(50),CHAR(50),
studentsstudents StudentTableTypeStudentTableType
))
NESTED TABLE students STORE AS NESTED TABLE students STORE AS StudentTable;StudentTable;
43
Querying a Nested TableQuerying a Nested Table
We can print the value of a nested table We can print the value of a nested table like any other value.like any other value.
But these values have two type But these values have two type constructors:constructors:
1.1. For the table.For the table.
2.2. For the type of tuples in the table.For the type of tuples in the table.
44
Example: Query a Nested Example: Query a Nested TableTable
Find the students of computer science:Find the students of computer science:
SELECT students FROM DepartmentSELECT students FROM Department
WHERE name = ’Computer Science’;WHERE name = ’Computer Science’; Produces one value like:Produces one value like:
StudentTableType(StudentTableType(
StudentType(’Sally’, ’Maple St’, ’U’),StudentType(’Sally’, ’Maple St’, ’U’),
Studenttype(’Mike’, ’Ave C’, ’G’),…Studenttype(’Mike’, ’Ave C’, ’G’),…
))
45
Querying Within a Nested Querying Within a Nested TableTable
A nested table can be converted to an A nested table can be converted to an ordinary relation by applying THE(…).ordinary relation by applying THE(…).
This relation can be used in FROM clauses This relation can be used in FROM clauses like any other relation.like any other relation.
46
Find the graduate students of computer Find the graduate students of computer science:science:
SELECT s.nameSELECT s.name
FROM THE(FROM THE(
SELECT studentsSELECT students
FROM DepartmentFROM Department
WHERE name = ’Computer Science’WHERE name = ’Computer Science’
) s) s
WHERE s.class_level = ’G’;WHERE s.class_level = ’G’;
An alias for the nestedtable, which has no name
The one nestedtable for theStudents of computerscience
Example: Use of THEExample: Use of THE
47
Turning Relations Into Nested Turning Relations Into Nested TablesTables
Any relation with the proper number and Any relation with the proper number and types of attributes can become the value types of attributes can become the value of a nested table.of a nested table.
Use CAST(MULTISET(…) AS <type> ) on Use CAST(MULTISET(…) AS <type> ) on the relation to turn it into the value with the relation to turn it into the value with the proper type for a nested table.the proper type for a nested table.
48
Example: CAST --- 1Example: CAST --- 1
Suppose we have a relation Suppose we have a relation Stuent(student, dept, building), where Stuent(student, dept, building), where student is a StudentType object, dept a student is a StudentType object, dept a string --- the department of the student, string --- the department of the student, building a string – building name.building a string – building name.
We want to insert into Department a new We want to insert into Department a new tuple, with computer science as the name, tuple, with computer science as the name, a set of students of that department, and a set of students of that department, and ‘RP F201’ as the building name.‘RP F201’ as the building name.
49
INSERT INTO Department VALUES (INSERT INTO Department VALUES (
’’Computer Science’, Computer Science’,
CAST(CAST(
MULTISET(MULTISET(
SELECT s.studentSELECT s.student
FROM Student sFROM Student s
WHERE s.department = ’Computer WHERE s.department = ’Computer Science’Science’
) AS StudentTableType) AS StudentTableType
), ‘RP F201’), ‘RP F201’
););
Turn the set of objectsinto a nested relation
The set of StudentTypeobjects for computer science
Example: CAST --- 2Example: CAST --- 2