Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Advanced Database Topics Copyright © Ellis Cohen 2002-2005 Objects and Relational Databases These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike.

Similar presentations


Presentation on theme: "1 Advanced Database Topics Copyright © Ellis Cohen 2002-2005 Objects and Relational Databases These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike."— Presentation transcript:

1 1 Advanced Database Topics Copyright © Ellis Cohen 2002-2005 Objects and Relational Databases These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. For more information on how you may use them, please see http://www.openlineconsult.com/db

2 2 © Ellis Cohen 2002-2005 Topics Object-Relational Mapping OR Mapping Approaches & Issues Object-Relational Databases Referenced Objects & Navigation Contained Objects Nested Tables Nested Collections

3 3 © Ellis Cohen 2002-2005 Drivers for OO & RDB Integration Persistent Object Storage –Need for a way to easily save and restore computation state of programs built via OOPL's using standard RDBs OO Programming for RDB Data –Treat rows of a table (plus asssociated data in other tables) like an object for programmatic access & modification OO Database Programming –Brings benefits of OO approach to RDB's

4 4 © Ellis Cohen 2002-2005 Object-Relational Mapping

5 5 © Ellis Cohen 2002-2005 OR Mapping Motivations Want to persist OO data so it is queryable (e.g. w OQL), but using the standard RDB your organization is already using. Want to write OO programs that use and manipulate data stored in an RDB. –OO programmers did this anyway before advent of technologies like JDO. –Painful enough that the correspondence between relations & objects was referred to as an impedance mismatch.

6 6 © Ellis Cohen 2002-2005 Object Model & Actual RDB 30SALES 10ACCOUNTING 50SUPPORT deptno dname Depts empno name addr deptno 7499ALLEN...30 7654MARTIN…30 7844TURNER…30 7212LAVICH… 7698BLAKE…10 7986STERN…10 Emps empno: 7499 name : ALLEN addr : … dept : empno: 7654 name : MARTIN addr : … dept : deptno: 30 dname : SALES

7 7 © Ellis Cohen 2002-2005 OR Mapping Approaches Programmatic Approach: Write the code to transform the object when loading it into the cache, and when persisting it to the RDB, Declarative/Automatic Approach: Provide a description of how the OOPL & RDB models are mapped to one another. The mapping layer uses the description to automatically transform the representations on object loading and persistence! The mapping layer translates OO queries (e.g. OQL, HQL, JDOQL, OPath) automatically into SQL The representation of an object in an OOPL may be quite different from its representation when stored in an RDB

8 8 © Ellis Cohen 2002-2005 Current Systems (1) JDO –Java standard –Uses transparent persistence –Many commercial implementations, including Kodo & ObjectBridge –Uses JDOQL, a limited Java-based query language (improved in 2.0) –JDO 2.0 adds significant support to control the OR mapping Castor –Java-based system using JDO API –Will use OQL as its query language

9 9 © Ellis Cohen 2002-2005 Current Systems (2) Hibernate –Most popular Java-based system –Uses explicit persistence –Uses HQL, a limited query language derived from OQL ObjectSpaces –Microsoft's system for.NET –Uses transparent persistence –Use OPath query language, loosely derived from XML's XPath

10 10 © Ellis Cohen 2002-2005 Mapping OQL to SQL SELECT e.ename, e.dept.dname FROM emps e in OQL is mapped to the SQL: SELECT e.ename, (SELECT d.dname FROM Depts d WHERE e.deptno = d.deptno) FROM Emps e A good optimizer will treat this as equivalent to SELECT ename, dname FROM Emps NATURAL JOIN Depts

11 11 © Ellis Cohen 2002-2005 Early OPath Filters placed in square brackets used instead of WHERE clauses Employee[empno = 3417] The employee whose empno is 3417 Employee[job = 'ANALYST'] The employees who are analysts Navigation represented by a dot; can be applied to a collection Employee[dept.dname = 'RESEARCH'] Dept[dname = 'RESEARCH'].empls Employees in the research department Employee[job = 'CLERK'].dept.dname Dept[empls.job = 'CLERK'] Departments that have clerks Early versions of OPath were very closely related to XML's XPath query language. OPath has since evolved away from this model

12 12 © Ellis Cohen 2002-2005 Mapping Early OPath to SQL Employee[job = 'CLERK'].dept.dname in Early OPath is mapped to the SQL: SELECT DISTINCT (SELECT d.dname FROM Depts d WHERE e.deptno = d.deptno) FROM Emps e WHERE job = 'CLERK' A decent optimizer will treat this as equivalent to SELECT DISTINCT dname FROM Emps NATURAL JOIN Depts WHERE job = 'CLERK'

13 13 © Ellis Cohen 2002-2005 OR Mapping Approaches & Issues

14 14 © Ellis Cohen 2002-2005 OOPL  RDB Mapping Approaches (1) OOPL model (ODL / Java / C#) RDB Model OOPL  RDB Map OOPL model (ODL / Java / C#) RDB Model RDB  OOPL Map Generate Start with Define

15 15 © Ellis Cohen 2002-2005 OOPL  RDB Mapping Approaches (2) OOPL model (ODL / Java / C#) RDB Model OOPL / RDB Map OOPL model (ODL / Java / C#) RDB Model ER  RDB & OOPL Map ER Model Generate Just Define Start with Define

16 16 © Ellis Cohen 2002-2005 Mapping RDB  OOPL Given a legacy RDB Design the corresponding OOPL. How are FK's treated –retain and/or convert to relationships –one or two-way relationships Specify field types (when not obvious) Mapping enums Generate OIDs –Unique to class Primary Key –Unique to application (allows application to use OIDs to retrieve objects) TableName + PrimaryKey ROWIDs –Globally unique (OIDs can be used to retrieve objects across a global network) ip address + DB instance + app name + unique-to-application

17 17 © Ellis Cohen 2002-2005 Example RDB  OOPL Spec --getOid will return tableName || '|' || primaryKey -- build Employee fields from Emps columns -- Emps' sal column should become Employee's salary field -- Emps job='MANAGER'  Employee job=1 … -- Emps mgr is a foreign key for an Emps -- so in Emps, have it hold a reference to an Employee

18 18 © Ellis Cohen 2002-2005 Mapping OOPL/ER  RDB Given a new OO or ER model Design the corresponding RDB. Determining Primary Keys –Object class field –Automatically generated surrogate keys unique to class, database, GUIDs Specify column types & constraints Generate OIDs –Same as for RDB  ER –Related to how PK's are determined Converting References –FK to primary key or other unique columns Mapping Enums

19 19 © Ellis Cohen 2002-2005 Example OOPL  RDB Spec Example OOPL  RDB Mapping (non-standard) --all tables will get globally unique surrogate PK's, which will be returned as OIDs -- build Emps column from Employee fields, with empno as PK -- Employee's salary field should become Emps' sal column -- Employee job=1  Emps job='MANAGER' … -- Employee's mgr is a ptr to an Employee -- so in Emps, have mgr instead hold a foreign key for an Emps

20 20 © Ellis Cohen 2002-2005 Using GUIDs as PKs Initial Design: OOPL or ODL Goal: Design an RDB Schema which associates OIDs with each tuple Emps 304729…20Accounting 8B6B2A..30Research 516123..50IT deptoid deptno deptnam Depts empoid empno deptoid A134E2…20693…304729… C0E11A…19419304729… D44472…823318B6B2A.. 7C91EE…30492304729… 437A23…93200516123.. Includes deptoid instead of deptno What are pros and cons of using OIDs as PK/FKs?

21 21 © Ellis Cohen 2002-2005 Object-Based Integration OODB RDB Files CORBA Service Client Issue OQL Query OQL CORBA Request Read/Parse SQL/SQLX Object Integration Server Develop Object Model for each data source Maps OQL to distributed native queries/request Maps combined results to objects MDDB MDX

22 22 © Ellis Cohen 2002-2005 Integrated Relational Querying Use an RDB, View both as OO Data –User still sees OO data as OO. Its mapping to the RDB is hidden –User sees an OO representation of the relational data as well, based on a hidden mapping –User queries all data with OQL, automatically mapped to SQL Use an RDB, View both as Relational Data –User sees relational data as is –User sees OO data in terms of its relational representation, based on a public mapping –User uses SQL to query all data Use an Object-Relational Database –RDB w user-defined object data types + references –Incorporates navigation into SQL Suppose we have both persistent OO and Relational data. How can we arrange to do queries joining both of them?

23 23 © Ellis Cohen 2002-2005 Object-Relational Databases (ORDBs)

24 24 © Ellis Cohen 2002-2005 ORDBs Object-Relational Databases integrate an Object Model with the Relational Model. Users can extend the built-in data types (number, date, etc.) with arbitrary object types. Columns can hold references to objects. SQL is extended to support field access and navigation just as in OQL. Tables (containing objects or references to object) are the primary (or sometimes only) collection type. Moreover, objects are not stored independently as in OODBs; they must be placed in tables.

25 25 © Ellis Cohen 2002-2005 Rows as Objects/Entities empno: 7654 name : MARTIN sal : 1250 comm : 1400 an Employee Object It can be useful to think of each row as an object or entity (i.e. an instance of an entity class) and the table as a collection of these objects The columns of the table correspond to the instance variables for each object It can be useful to think of each row as an object or entity (i.e. an instance of an entity class) and the table as a collection of these objects The columns of the table correspond to the instance variables for each object empno name sal comm Emps 7499ALLEN1600300 7654MARTIN12501400 7698BLAKE2850 7839KING5000 7844TURNER15000 7986STERN1500

26 26 © Ellis Cohen 2002-2005 Object Tables Object-Relational Databases actually allow rows to be objects (known as row objects), and allow cells to contain references to these row objects. –Referential Integrity constraints can be replaced by actual references –Joins can be replaced by Navigation –Instead of automatically associating an extent with an object, an object is explicitly stored in some table (multiple tables can hold the same type of object) –Every row object has an OID (invisibly provided by the database)

27 27 © Ellis Cohen 2002-2005 Object Types & Tables CREATE TYPE DeptObj AS OBJECT ( deptno number(3), dname varchar(20), loc varchar(15), … ) CREATE TABLE DeptTable OF DeptObj (deptno PRIMARY KEY); DeptTable can be viewed as either a table containing 3 columns: deptno, dname, loc a table containing a single column: a DeptObj * SQL Syntax loosely based on Oracle

28 28 © Ellis Cohen 2002-2005 Returning Column Values from Object Tables SELECT d.dname FROM DeptTable d WHERE d.loc = 'HOUSTON' – returns the department names SELECT d.* FROM DeptTable d WHERE d.loc = 'HOUSTON' – returns a row (just as from an ordinary table) 30SALESNY 10ACCOUNTINGLA 50SUPPORTHOUSTON 99PARTYMIAMI

29 29 © Ellis Cohen 2002-2005 Returning Column Values vs. Objects SELECT d.* FROM DeptTable d WHERE d.loc = 'HOUSTON' – returns rows of values (just as from an ordinary table) 30SALESNY 10ACCOUNTINGLA 50SUPPORTHOUSTON 99PARTYMIAMI SELECT d FROM DeptTable d WHERE d.loc = 'HOUSTON' – returns entire DeptObj objects! 30SALESNY 10ACCOUNTINGLA 50SUPPORTHOUSTON 99PARTYMIAMI A DeptObj Object

30 30 © Ellis Cohen 2002-2005 Row Objects Have OIDs 27622AuditingCHICAGO… deptno dname loc … A row object's OID can be represented as a ROWID + a generation #, which also appears in the row object's header AAAGDxAABA AAH9EAAD27

31 31 © Ellis Cohen 2002-2005 Object Views CREATE TABLE Depts ( deptno number( 5 ), dname varchar( 30 ), loc varchar(30) ) Given an existing table, create an object view of it, but requires OID for each tuple CREATE TYPE DeptObj AS OBJECT ( deptno number( 5 ), dname varchar( 30 ), loc varchar(30) ) CREATE VIEW DeptView OF DeptObj WITH OBJECT OID (deptno) AS SELECT * FROM Depts Note: No objects really exist or are created, so even though DeptView looks like a table of objects, the OID is just (id of Depts) + deptno, which is better than the ROWID (which can be reused) if deptno's are not changed or reused.

32 32 © Ellis Cohen 2002-2005 Type Inheritance CREATE TYPE EmpObj UNDER PersonObj ( empno number(4), … … ) CREATE TABLE PersonTable OF PersonObj PersonTable can hold plain PersonObjs as well as EmpObjs & other subclasses ssnonameaddr 202406129ALLEN20 B St, …empnosal …JONES…14272500 …CHU… University …SONI…Myanard Wales Univ …HALMA… …BONI…empnosal …STERN…60413300 EmpObj GradObj EmpObj PersonObj

33 33 © Ellis Cohen 2002-2005 Type Checking & Casting Suppose we want to get the empno's of all the employees in PersonTable SELECT p.empno FROM PersonTable p WHERE p IS OF TYPE EmpObj Almost works, except we also need to claim that p is an EmpObj rather than just a PersonObj before getting its empno attribute SELECT TREAT(p AS EmpObj).empno FROM PersonTable p WHERE p IS OF TYPE EmpObj

34 34 © Ellis Cohen 2002-2005 Referenced Objects & Navigation

35 35 © Ellis Cohen 2002-2005 Object References A column can contain a reference to a row object 30SALES… 10ACCOUNTING… 50SUPPORT… 99PARTY… deptno dname loc DeptTable empno name … dept 7499ALLEN... 7654MARTIN… 7698BLAKE… 7839KING… 7844TURNER… 7986STERN… EmpTable

36 36 © Ellis Cohen 2002-2005 Scoped References CREATE TYPE EmpObj AS OBJECT ( empno number(4), name varchar(30), … dept REF DeptObj SCOPE DeptTable ) – replaces the referential integrity constraint deptno number(3) REFERENCES DeptTable CREATE TABLE EmpTable OF EmpObj (PRIMARY KEY empno) REF(obj) creates a reference to the specified object, which can then be returned in a result set UPDATE EmpTable SET dept = (SELECT REF(d) FROM DeptTable d WHERE d.dname = 'ACCOUNTING') WHERE name = 'SMITH' This attribute holds a reference to a DeptObj in DeptTable Change SMITH's dept to ACCOUNTING

37 37 © Ellis Cohen 2002-2005 Comparing Queries In a vanilla RDB, to find the department name in which JONES works, you might do SELECT dname FROM Emps NATURAL JOIN Depts WHERE ename = 'JONES' In an ORDB using EmpObj (which contains a REF DeptObj) how would you get the dept name in which JONES works? (Assume only one employee named JONES)

38 38 © Ellis Cohen 2002-2005 ORDBs Use Direct Navigation CREATE TYPE EmpObj AS OBJECT ( empno number(4), name varchar(30), …, dept REF DeptObj SCOPE DeptObj ) CREATE TABLE EmpTable OF EmpObj (PRIMARY KEY empno) SELECT e. name, e.dept.dname FROM EmpTable e WHERE ename = 'JONES' List the names of employees whose departments are located in Denver.

39 39 © Ellis Cohen 2002-2005 Simple Query Solution List the names of employees whose departments are located in Denver. SELECT e.name FROM EmpTable e WHERE e.dept.loc = 'DENVER'

40 40 © Ellis Cohen 2002-2005 Tables vs Extents Object types do not have a single associated extent There can be multiple tables which hold objects of the same type CREATE TABLE DeptTable1 OF DeptObj (deptno PRIMARY KEY); CREATE TABLE DeptTable2 OF DeptObj (deptno PRIMARY KEY); CREATE TABLE DeptTable3 OF DeptObj (deptno PRIMARY KEY); The user chooses where to store an object INSERT INTO DeptTable2 VALUES ( 50, 'SUPPORT', 'HOUSTON' ); Less signficant issue for DB's which support partitioned tables

41 41 © Ellis Cohen 2002-2005 Unscoped References CREATE TYPE EmpObj AS OBJECT ( empno number(4), name varchar(30), … dept REF DeptObj SCOPE DeptTable ) CREATE TYPE EmpObj AS OBJECT ( empno number(4), name varchar(30), … dept REF DeptObj ) This DeptObj could be located in any table. Must use a full-size OID to represent the reference This DeptObj must be located in DeptTable. Could use a table-relative mini-OID to represent the reference

42 42 © Ellis Cohen 2002-2005 Dereferencing Unscoped References Even if departments are spread across multiple tables, an unscoped reference will find the department (by its OID!) SELECT e.dept.dname FROM EmpTable e WHERE e.ename = 'JONES' Suppose in a vanilla RDB, depts were spread across Depts1, Depts2 & Depts3. How would you get the name of the department in which JONES works?

43 43 © Ellis Cohen 2002-2005 Unions for Multi-Table Navigation Suppose in a vanilla RDB, depts were spread across Depts1, Depts2 & Depts3. How would you get the name of the department in which JONES works? SELECT dname FROM Emps NATURAL JOIN Depts1 WHERE ename = 'JONES' UNION SELECT dname FROM Emps NATURAL JOIN Depts2 WHERE ename = 'JONES' UNION SELECT dname FROM Emps NATURAL JOIN Depts3 WHERE ename = 'JONES'; In practice, tables are split for many reasons different divisions; pending vs active vs inactive, etc. Using an Object Model with unscoped references allows simple navigation to replace unioned joins

44 44 © Ellis Cohen 2002-2005 DELETE & Dangling References DELETE deletes objects from tables of objects Scoped References: provide referential integrity checking: –Can't delete referenced department (default) –ON DELETE SET NULL –ON DELETE CASCADE Unscoped References: no referential integrity checking –If a DeptObj is deleted, a REF DeptObj may hold an invalid OID (a dangling reference) –Use IS DANGLING to check: SELECT DISTINCT e.dept.dname FROM EmpTable e WHERE e.job = 'SALESMAN' AND e.dept IS NOT DANGLING

45 45 © Ellis Cohen 2002-2005 Explicit Dereferencing If e denotes an EmpObj thene.name denotes the name attribute of that EmpObj If re denotes a REF EmpObj then DEREF(re) denotes the EmpObj it references and eitherDEREF(re).name orre.name denotes the name attribute of the EmpObj it references

46 46 © Ellis Cohen 2002-2005 Contained Objects

47 47 © Ellis Cohen 2002-2005 Containment ORDB's are non-1NF: Cells may contain objects as well as primitive types of values. These are also called cell objects or column objects. CREATE TYPE Address AS OBJECT( street varchar(100), city varchar(40), state char(2), zip char(5)) CREATE TYPE PersonObj AS OBJECT( name varchar(30), addr Address ) CREATE TABLE PersonTable OF PersonObj

48 48 © Ellis Cohen 2002-2005 Cell Objects SMITH JONES GOMEZ SONI nameaddr ……MA02139 ……IL51320 ……CA93710 ……MA02445 pp.name p.addrp.addr.state

49 49 © Ellis Cohen 2002-2005 Creating Cell Objects INSERT INTO PersonTable VALUES ( 'STERN', Address( '11 Global Way', 'Hereville', MS, 39452 ) ) Cell Objects do not have OIDs REFs to Cell Objects are not allowed

50 50 © Ellis Cohen 2002-2005 Object Type Methods CREATE TYPE AddrObj AS OBJECT ( street varchar(100), city varchar(40), state char(2), zip char(5), MEMBER FUNCTION toString RETURN varchar … ) CREATE TYPE PersonObj AS OBJECT( name varchar(30), addr Address ) CREATE TABLE PersonTable OF PersonObj SELECT name, addr.toString() FROM PersonTable

51 51 © Ellis Cohen 2002-2005 Ordering by Object Types SELECT name FROM PersonTable ORDER BY addr How is an order defined on addresses? Oracle (e.g.) allows a single MAP member function to be defined for AddrObjs. It returns a primitive type, used as the basis of ordering MAP MEMBER FUNCTION getZip RETURN char(5) IS RETURN zip; END Oracle instead allows the ORDER member function; it compare two objects, returning -1 if the first is smaller 0 if they are equal 1 if the first is larger Order AddrObjs based on their zip values

52 52 © Ellis Cohen 2002-2005 Selecting with Member Functions CREATE TABLE Positions( posid int, – id of the position coord Coordinate, – location of the position … ) SELECT posid FROM Positions WHERE coord.inRegion( 0, 0, 100, 100) > 0 CREATE TYPE Coordinate AS OBJECT x number, y number, MEMBER FUNCTION inRegion RETURN INT … – returns 1 if coordinate is within the specified region … )

53 53 © Ellis Cohen 2002-2005 Type-Specific Indexing ORDB databases generally support type-specific indices InRegion queries can be implemented as the intersection of x and y range queries based on B- tree indices, however Coordinate-specific indices such as quadtree and R-tree indices select inRegion tuples much more quickly

54 54 © Ellis Cohen 2002-2005 Nested Tables

55 55 © Ellis Cohen 2002-2005 Nested Tables 23HRNY 31SALESLA ……… … deptno dname loc empls 3049SMITH…… 6471JONES…… 8187GOMEZ…… 2069SONI…… 8142EMEBI…… Purist approaches to ORDB's (e.g. Date) only allows Nested Tables (and other Contained Objects and Collections), but do NOT allow Row Objects and References.

56 56 © Ellis Cohen 2002-2005 Nested Tables of Objects CREATE TYPE DeptEmpsObj As OBJECT ( deptno number(4), dname varchar(30), loc varchar(30), empls TABLE OF EmpObj ) CREATE TABLE DeptEmpsTable OF DeptEmpsObj PRIMARY KEY deptno SELECT dname FROM DeptEmpsTable d WHERE EXISTS( SELECT * FROM d.empls e WHERE e.job = 'SALESMAN') SELECT e.name FROM DeptEmpsTable d, d.empls e WHERE d.loc = 'BOSTON' List names of depts which have salesmen List employees of depts located in Boston Correlated table expressions allowed on nested tables Now, of those employees, determine how many have each kind of job

57 57 © Ellis Cohen 2002-2005 Correlation Grouping Solution Of the employees in departments located in Boston, determine how many have each kind of job. SELECT e.job, count(*) FROM DeptEmpsTable d, d.empls e WHERE d.loc = 'BOSTON' GROUP BY e.job

58 58 © Ellis Cohen 2002-2005 Nested Update Problem Nested Tables can be very efficient for some operations SELECT e.name FROM DeptEmpsTable d, d.empls WHERE d.loc = 'NY' AND e.job = 'ANALYST' How do you add 100 to the salary of these employees? You must use views!

59 59 © Ellis Cohen 2002-2005 Nested Tables & Unnested Views 23HRNY 31SALESLA ……… … deptno dname loc empls 3049SMITH…… 6471JONES…… 8187GOMEZ…… 2069SONI…… 8142EMEBI…… 23HRNY3049SMITH…… 23HRNY6471JONES…… 23HRNY8187GOMEZ…… 31SALESLA2069SONI…… …………… deptno dname loc DeptEmpView DeptEmpsTable

60 60 © Ellis Cohen 2002-2005 Views for Updating CREATE VIEW DeptEmpView AS SELECT d.deptno, d.name, d.loc, e.* FROM DeptEmpsTable d, d.empls e UPDATE DeptEmpView SET sal = sal + 100 WHERE loc = 'NY' AND job = 'ANALYST' Can we update deptno? UPDATE DeptEmpView SET deptno = 31 WHERE empno = 6471 Updating deptno means moving the employee from one nested table to another. Might be supported in an ORDB system, but perhaps it would be better for Emps & Depts to be the actual tables, and to create a nested table view

61 61 © Ellis Cohen 2002-2005 Result Sets with Nested Tables Given Depts (only dept info) and Emps (only employee info, except that Emps.deptno references Depts) Generate a result set: each tuple corresponds to each of the departments – it contains the name of the department, and a table of the names of each employee in the department. SELECT d.dname, TABLE( SELECT ename FROM Emps e WHERE e.deptno = d.deptno ) FROM Depts d Given Depts and Emps, create a view that corresponds to DeptEmpsTable (with its nested table of employees)

62 62 © Ellis Cohen 2002-2005 Creating Nested Table Views CREATE VIEW DeptEmpsTableView OF DeptObj WITH OBJECT OID (deptno) AS SELECT d.*, TABLE( SELECT empno, … FROM Emps e WHERE d.deptno = e.deptno) AS empls FROM Depts d Oracle also allows definition of the original DeptEmpsTable, with the combined nested tables of all the Employees implemented as a single query-able table Given Depts and Emps, create a view that corresponds to DeptEmpsTable (with its nested table of employees)

63 63 © Ellis Cohen 2002-2005 Nested Result Sets from References Generate a result set: each tuple contains a department name and a table of the names of the dept employees 30SALES… 10ACCOUNTING… 50SUPPORT… 99PARTY… deptno dname loc DeptTable empno name … dept 7499ALLEN... 7654MARTIN… 7698BLAKE… 7839KING… 7844TURNER… 7986STERN… EmpTable

64 64 © Ellis Cohen 2002-2005 Result Set Solution SELECT d.dname, TABLE( SELECT name FROM EmpTable e WHERE e.dept = REF(d) ) FROM DeptTable d Generate a result set: each tuple contains a department name and a table of the names of the dept employees Generate the same result set, but given DeptEmpsTable (each dept has empls, a nested table of employees)

65 65 © Ellis Cohen 2002-2005 Related Nested Result Set SELECT d.dname, TABLE( SELECT name FROM d.empls ) FROM DeptEmpsTable d Notice that SELECT d.dname, d.empls.name FROM DeptEmpsTable d is incorrect! Generate a result set: each tuple contains a department name and a table of the names of the dept employees, given DeptEmpsTable

66 66 © Ellis Cohen 2002-2005 Cross Referencing 30SALES 10ACCOUNTING 50SUPPORT deptno dname empls DeptTable empno name … dept 7499ALLEN... 7654MARTIN… 7698BLAKE… 7839KING… 7844TURNER… 7986STERN… EmpTable Suppose we keep the employees in a separate table And every department contains a table containing just references to the employees in that department

67 67 © Ellis Cohen 2002-2005 Nested Tables of Refs CREATE TYPE RefEmp AS REF EmpObj SCOPE EmpTable; CREATE TYPE DeptObj AS OBJECT ( deptno number(4), dname varchar(30), loc varchar(30), empls TABLE OF RefEmp ) CREATE TABLE DeptTable OF DeptObj PRIMARY KEY deptno SELECT dname FROM DeptTable d WHERE EXISTS( SELECT * FROM d.empls e WHERE e.job = 'SALESMAN') SELECT e.name FROM DeptTable d, d.empls e WHERE d.loc = 'Boston'

68 68 © Ellis Cohen 2002-2005 ODL Model class Employee (extent emps) { attribute int empno; attribute string name; attribute string job; attribute Address addr; relationship Dept dept inverse Dept::empls; } class Dept (extent depts) { attribute int deptno; attribute string dname; relationship Set empls inverse Employee::dept; The ODL model for Employee and Dept is essentially equivalent to the previous ORDB model emps and depts correspond to EmpTable and DeptTable Set empls corresponds to a nested tables of refs

69 69 © Ellis Cohen 2002-2005 Collections and Relationships depts emps dept1 dept2 dept3 emp1 emp3 emp5 emp4 emp2 empls dept

70 70 © Ellis Cohen 2002-2005 Nested Collections

71 71 © Ellis Cohen 2002-2005 Collection Types ORDB's may support other collection types SET OF Typ BAG OF Typ LIST OF Typ ARRAY[n] OF Typ DICTIONARY[ndxtyp] OF Typ They can –Be placed in cells These are useful because –there are specialized functions & operations to add/remove/get/set/test values Oracle supports VARRAYS, resizeable arrays with a fixed maximum size

72 72 © Ellis Cohen 2002-2005 Collections & Membership It may be possible to test collections for membership CREATE TYPE PersonObj AS OBJECT ( name varchar(30), kidnames SET OF varchar(30) ) CREATE TABLE PersonTable OF PersonObj List the names of the people who have a kid named 'Yael' SELECT name FROM PersonTable where ('Yael' IN kidnames)

73 73 © Ellis Cohen 2002-2005 Collection Operations It may be possible to use specialized collection operations CREATE TYPE PersonObj AS OBJECT ( name varchar(30), autos LIST OF AutoObj ) CREATE TABLE PersonTable OF PersonObj List each person and the model of their primary car SELECT name, autos[1].model FROM PersonTable

74 74 © Ellis Cohen 2002-2005 Querying Collections Generally, collections cannot be queried It may be possible to convert collections to tables in order to query them CREATE TYPE PersonObj AS OBJECT ( name varchar(30), autos LIST OF AutoObj ) CREATE TABLE PersonTable OF PersonObj List the model, year & owner of all autos made before 1950. Order by model and year SELECT a.model, a.year, p.name FROM PersonTable p, TABLE(p.autos) a WHERE a.year < 1950 ORDER BY a.model, a.year

75 75 © Ellis Cohen 2002-2005 Collection Conversions It may be possible to convert tables or collections to other collections so collection-specific operations may be used CREATE TYPE PersonObj AS OBJECT ( name varchar(30), autos TABLE OF AutoObj ) SELECT name, LIST(autos ORDER BY position DESC)[1].model FROM PersonTable List each person and the model of their primary car


Download ppt "1 Advanced Database Topics Copyright © Ellis Cohen 2002-2005 Objects and Relational Databases These slides are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike."

Similar presentations


Ads by Google