Vous êtes sur la page 1sur 48

Oracle8 Objects

24
C H A P T E R

he Objects option in Oracle8 has permitted a new era of database design using an Object-oriented approach.

In This Chapter
Introduction to Object technology Object types Collection types Object Tables Object views

This chapter delivers the reader the knowledge to understand the Object-relational aspects of Oracle8. With a practical approach, the reader can quickly grasp an evolutionary understanding of Object technology and how it can be applied to the design of a relational Oracle8 database.

Introduction to Oracle8 Object Technology


Like the thrust of a rocket, Object technology is becoming the infrastructure for all of todays application development efforts. The shift toward Object technology has mainly been in the development of front-end or client applications. Integrated application development environments (IDEs) such as PowerBuilder, Delphi, and Visual Basic have all cradled the Object technology momentum. The objective of injecting the Object paradigm into a systems development life cycle is to enable you to build components that mimic the real-life business processes. These Objects become manageable and reusable and enhance the development effort. Enterprises are developing applications that closely model their physical infrastructure, enabling their business systems to behave exactly as their physical business processes. The problem so far has been that the development of Objectoriented applications has mainly focused on the client side. The back-end Relational Database Management System (RDBMS) has been unable to support a business directly in terms of its respective business Objects. In other words, the client-side Object paradigm has been unable to map directly to their respective data Object counterparts.

600

Chapter 24 3 Oracle8 Objects

Figure 24-1 illustrates the relationship between business Objects on the client and Tables in a database.

Business objects in a client application

Relational tables in a database

Business objecl

Business objecl

Table Table

Table Table Table

Table Table Table Table Table

Business objecl

Business objecl

Business objecl

Table Table Table Table Table Table Table Table

Business objecl

Business objecl

Client

Oracle8 database

Figure 24-1: Business Objects and relational Tables do not map directly to one another.

Up to this release of Oracle, business Objects on the application side have had to interact with normalized relational Tables to retrieve and process information. Application developers could, however, encapsulate a number of related datacentric functions and Procedures together into a standalone Package Object. This Package Object could be directly related to an applications business Objects. Overall, Object-oriented analysis conducted for the application could

Chapter 24 3 Object-Relational Oracle8

601

not be cross-applied to the Oracle databases analysis, design, and implementation phases. The relational model stood as it had for many years. This model has now changed in Oracle8. Oracle8 models the complexity of todays businesses naturally by embracing Object technology without compromising the performance of the relational database system. Oracle8 has now become an Objectrelational database, enabling data architects to model the client-side business Objects as Object types in the database and keeping the data within a relational framework. Oracle8 takes advantage of both the Object and relational worlds. Oracle8 implements Object technology using the Objects option. The Objects option allows Oracle8 to store the business Objects in their most natural form, thus enabling efficient manipulation and retrieval of related business data. This allows business Objects in the client-side applications to be directly mapped to their respective Oracle8 relational Tables. Oracle8 implements Objects as User-defined datatypes. User-defined datatypes use the built-in data types and other User-defined datatypes as building blocks for Objects that model the data structure in the client business Objects. Object Tables use the created Objects as a storage Schema for the data, just like any other datatype. In addition to creating a natural structure to store business Object data, Oracle8 also enables you to encapsulate the behavior of business Objects into the Objects in the form of member methods.
Note

Remember, datatypes do not store data. They only define the data to be stored. Figure 24-2 illustrates the relationship between business Objects on the client and Object tables in a database.

Object-Relational Oracle8
The software development life cycle begins with defining the business. The developer splits the business into its many processes and the data attributes of each of these processes. A conceptual process map is created that supports the businesss infrastructure. The conceptual map supports the creation of front-end application processes on the clients. The entity-relationship diagram and a physical version of the conceptual process map support the creation of a physical data model of the relational database. The physical data model defines the structure of the business data to be stored in the form of Tables. Referential integrity Constraints define how the business data is related between different Tables. For a long time, the relational database has been the data repository for the enterprise. Developers have used Tables to store the enterprise data with Column datatypes representing the attributes of the stored data. You primarily use datatypes to model the structure of the business data. You can also use them in PL/SQL subprograms to define variables.

602

Chapter 24 3 Oracle8 Objects

Business objects in a client application

Object-relational tables in a database

Business objecl

Business objecl

Table
Objecl

Table
Objecl Objecl

Table Table

Business objecl

Business objecl

Business objecl

Table
Objecl Objecl Objecl Objecl Objecl

Table
Objecl Objecl

Business objecl

Business objecl

Table Table Table

Client

Oracle8 database

Figure 24-2: Business Objects and Object-relational Tables fit more naturally together.

As discussed in the introduction to this chapter, relational Tables themselves cannot always be mapped exactly to their counterpart business Object data. This condition may be due to the nature of the business data or to the normalization rules enforced in the design of the relational database. The normalization rules enable a data set to be architected efficiently and implemented into the database. Normalization rules are enforced to allow fast access and efficient storage for business data. As an Object-relational database, Oracle8 has the facility to create Object models as well as relational models in the same database. Data architects can take advantage of both technological representations of data. An applications business Objects can, therefore, be mapped directly to Object Tables in the Oracle8 database.

Chapter 24 3 An Object-Relational Case Study

603

Advantages of Object-relational Oracle8


Moving to a more Object-oriented representation of data and its behavior provides a more intuitive way to access a business Objects data. Object-relational Oracle8 provides the following benefits in database design: 3 Object reuse. Oracle8 Objects can be reused multiple times to form other Objects or be embedded into different Tables. This provides a more uniform approach to database development without reinventing the wheel each time data elements need to be defined. 3 Disciplined database design. Oracle8 Objects can be embedded into Table Columns or exist as row Objects. You can design and test each Object independently. Using Objects allows the database architecture to be created in a component-oriented fashion with Objects tied to their respective business Objects.

Disadvantages of Object-relational Oracle8


No real disadvantages occur in using the Objects option with Oracle8, as it makes the development effort on the front-end coherent with the back-end. Because the technology is new, a few near-term disadvantages exist, but these should fade as the technology matures. These immediate disadvantages are: 3 Increase in complexity. A small transition is required for a developer or DBA to migrate from a relational mindset to a more Object-oriented mindset. She needs a greater knowledge of the business domain and the database architecture. Objects can appear as black boxes if proper documentation and notes are available to support their existence and use. 3 Object portability. If a database is architected in Oracle8 and makes full use of its Object-oriented features, migrating the database to another vendors database requires a complete re-architecture of the database. An Objectoriented to relational migration needs to take place. Also, applications that interface with the Object-oriented data architecture require their respective SQL calls to be modified to be more relational.

An Object-Relational Case Study


This chapter uses a simple library system case study to explain the Objectrelational features of Oracle8. Figure 24-3 illustrates a simple library system data model.

604

Chapter 24 3 Oracle8 Objects

PERSON PERSON ID PERSON_FIRST_NAME PERSON_LAST_NAME PERSON_PHONE PERSON_STREET_ADDRESS PERSON_CITY PERSON_STATE PERSON_ZIP PERSON_FINE_TOTAL PERSON_BL_STATUS <pk> INTEGER VARCHAR2(25) VARCHAR2(25) VARCHAR2(20) VARCHAR2(50) VARCHAR2(25) VARCHAR2(2) NUMBER NUMBER(5,2) CHAR RESERVED ID RESERVED BOOK ID BOOKS_RESERVED <pk> <pk,fk> INTEGER INTEGER INTEGER INTEGER

RESERVED PERSON ID <pk,fk> RESERVED_WAIT_NO

CHAR PERSON_ID = RESERVED_PERSON_ID BOOK_ID = RESERVED_BOOK_ID PERSON_ID = BL_PERSON_ID BOOKS BOOK ID BOOK_PUBLISHER BOOK_AUTHOR_FIRST BOOKS_LOANED BL LOAN ID BL BOOK ID BL PERSON ID BL_LOAN_DATE BL_FINE <pk> <pk,fk> <pk,fk> INTEGER INTEGER INTEGER DATE NUMBER(5,2) BOOK_ID = BL_BOOK_ID BOOK_AUTHOR_LAST BOOK_TITLE BOOK_SUBJECT BOOK_LOAN_ID <pk> INTEGER VARCHAR2(50) VARCHAR2(25) VARCHAR2(25) VARCHAR2(100) VARCHAR2(50) INTEGER

Figure 24-3: Data model of a library system

Library system processes


The preceding data model can assume and support the following library system processes. 3 A person can borrow a book. 3 A person can reserve as many as ten books. 3 A person can return a book. 3 A person can be fined for books later than the due date. 3 A person can pay fines on the book on which they have been overdue.

Chapter 24 3 An Object-Relational Case Study

605

3 Up to ten people can reserve the same book. 3 Books in the Library can be viewed by the following categories: Alphabetically By Author By Publisher By Title By Subject

Library example Tables


The following Tables support the preceding library system processes: 3 PERSON 3 BOOKS 3 BOOKS_LOANED 3 BOOKS_RESERVED

Library example entities


The following main entities are defined from the library system data model: 3 PERSON 3 BOOKS The remaining sections of this chapter use the preceding case study to implement an Object-relational model of the library system. Oracle8 can implement an Object-relational model of the library system using two concepts: 3 Oracle8 Objects. This approach requires a re-architecture of the library system into its respective Object definitions. In addition, it requires new programs (called methods) to add, modify, or query data in the Objects. 3 Oracle8 Object Views. This approach uses the existing library system relational model as the data architecture of the system. Oracle8 Object views provide an Object-oriented perspective to manipulating and retrieving data from the underlying relational Tables. The library system illustrates both approaches. The Objects approach is shown first, followed by the Object views approach.

606

Chapter 24 3 Oracle8 Objects

Oracle8 Objects
Oracle8 implements Object technology by using the Objects option. The Objects option allows the creation of User-defined datatypes, known as Abstract Data Types (ADT), which are built upon existing Oracle8 datatypes provided by the Oracle8 server. Abstract Data Types enable the precise modeling of the structure and behavior of the data that exists in the business. Thus, a complex business Objects data structure can be created in the Oracle8 database by defining the related data elements and grouping them together into Abstract Data Types. This enables the data elements of the Abstract Data Type to be treated as a unit. The following two Abstract Data Types are currently supported: 3 Object types 3 Collection types You can further categorize collection types into VARRAYs and nested Tables, which in themselves are multiple instances of a certain datatype. You can use these new ADTs in Table definitions and PL/SQL. ADTs can also have methods in the form of PL/SQL code as part of their definition, which are known as members. Member functions or Procedures operate in the context of an instance of the ADT. The next sections describe Object types and collection types.

Object types
Object types are similar to Objects created in the application development effort, except they are created in the realm of the Oracle8 database. Object types are Userdefined types that enable the structure and behavior of business Objects to be captured into the databases schema. You can use Object types to decouple the data within the database into the same structure as the real-world business Objects. You can consider an Object type a template, as its creation does not involve storage allocation. Only when an Object type is instantiated by its constructor method does it actually get created. Each Object type has a default system generated constructor method that helps create an instance of that Object type. Object types are only created within the context of a schema Object (for example, a Table Column or row). Every Object type possesses the following characteristics: 3 A unique name. 3 Attributes that model the structure of the real-world business Object. An Objects attributes can be defined from the following:

Chapter 24 3 Oracle8 Objects

607

Built-in scalar datatype (VARCHAR2, NUMBER, CHAR, and so forth). Object types. Collection types (nested Tables or VARRAYs). Large Object (BLOB, NLOB, CLOB, or BFILE types). 3 Member methods can be defined for the Object type to enable the Object type to model the real-world business Objects behavior. You can write this method in PL/SQL and store it in the database or write it in C and store it outside the database. Figure 24-4 illustrates Object type components.
Figure 24-4: An Object types components
AN OBJECT TYPE

Object type name

Data attributes

Member functions

Constructor method

Creating Object types


Use the new CREATE Type command to create an Oracle8 Object type. The syntax for this command follows:
CREATE OR REPLACE Type [schema.]type_name AS OBJECT ( attribute_name datatype [, attribute_name datatype]. | [{MAP|ORDER} MEMBER function specification] | [MEMBER {procedure_specification |function_specification} [,MEMBER {procedure_specification |function_specification}]] | [PRAGMA RESTRICT_REFERENCES (method_name, constraints) [, Pragma RESTRICT_REFERENCES (method_name, constraints)].]

608

Chapter 24 3 Oracle8 Objects

);

The parameters for this command follow: 3 OR REPLACE. Recreates the Object type if it already exists. 3 Schema. Specifies the Schema where the Object type will be created. 3 Type_name. Specifies the name of the Object type. 3 AS Object. Specifies the type of abstract Data Type to create. 3 Attribute_Name. Specifies an attribute for the Object type. 3 Datatype. Identifies the datatype of the attribute. This can be a built-in Oracle8 datatype or another ADT. 3 MEMBER. Specifies a function or Procedure embedded into the Object type. 3 MAP MEMBER. Specifies a member function that uses the map method for Object comparison. 3 ORDER MEMBER. Specifies a member function that uses the ORDER method for Object comparison. The pragma RESTRICT_REFERENCES is a compiler directive that enables database access to be controlled for the member functions. The following data access options are available to member functions: 3 WNDS. Member function cannot modify Table data. 3 WNPS. Member function cannot change Package variables. 3 RNDS. Member function cannot query Table data. 3 RNPS. Member function cannot reference Package variables. Oracle8 requires the following privileges to create an Object type: 3 A User must have the CREATE Type system privilege to create an Object in their own Schema. 3 A User must have the CREATE ANY Type system privilege to create an Object in another Users schema.
Note

Oracle8 defines a constructor method for each Object type created. The name of the constructor method is the same name as the Object type.

Incomplete and complete Object types


In developing Object types, sometimes all the information is not available for a particular Object type to be created, but another Object type may depend on its existence before it can be created. This can cause cyclic problems in compiling Object types. You can resolve cyclic Object type dependencies using incomplete Object types.

Chapter 24 3 Oracle8 Objects

609

Incomplete Object types only specify the name of the Object type upon creation. The constituent data elements are unspecified. In this way, a dependent Object type can be created and compiled using a reference to the Object types name. All an Object type needs to reference another Object is a valid Object type name. The syntax for creating an incomplete Object type follows:
CREATE Type Type_name;
Example

For example, if two Object types are to be created STUDENT_t and DEPT_t, then the STUDENT_t Object type needs to reference the DEPT_t Object type. The STUDENT_t Object cannot be created if the DEPT_t Object type does not exist. The STUDENT_t Object type would then be referencing an Object type that does not exist. To get around this problem, Oracle8 allows Object types to be incomplete. This allows only the Object type to exist by name only. When more information is available, the Object types data elements can be defined and the Object type can become complete. The following statement creates an incomplete DEPT_t Object type:
CREATE Type DEPT_t;

The following statement creates the STUDENT Object type. Its STUDENT_DEPT_ID Column references the incomplete DEPT_t Object type:
CREATE OR REPLACE Type STUDENT_t AS OBJECT ( STUDENT_ID INTEGER, STUDENT_FIRST_NAME VARCHAR2(25), STUDENT_LAST_NAME VARCHAR2(25), STUDENT_DEPT_ID REF DEPT_t, STUDENT_ADDRESS VARCHAR2(50), STUDENT_CITY VARCHAR2(25), STUDENT_STATE VARCHAR2(15), STUDENT_ZIP VARCHAR2(10) );

In the previous example, the following attributes represent the Object types data elements:
STUDENT_ID STUDENT_FIRST_NAME STUDENT_LAST_NAME STUDENT_DEPT_ID REF STUDENT_ADDRESS STUDENT_CITY STUDENT_STATE STUDENT_ZIP INTEGER VARCHAR2(25) VARCHAR2(25) DEPT_t VARCHAR2(50) VARCHAR2(25) VARCHAR2(15) VARCHAR2(10)

610

Chapter 24 3 Oracle8 Objects

The following statement causes the STUDENT_DEPT_ID Column in the STUDENT_t Object type to reference the DEPT_t Object type:
STUDENT_DEPT_ID REF DEPT_t

In this example, only the STUDENT_t Object type references the DEPT_t Object type. If the STUDENT and DEPT Object types both referenced each other, both Object types would need to be created as incomplete Object types first to resolve their cyclic dependencies. The following statement creates incomplete STUDENT_t and DEPT_t Object types:
CREATE Type DEPT_t; CREATE Type STUDENT_t;

Once you create an Object type, you must use methods to compare the values of Object data. The next section describes Object type methods.

Object type methods (members)


An Object type method is a function or Procedure defined as part of the Object type. You can write the function or Procedure in either PL/SQL and store it within the database when the Object is instantiated or you can write them in C and store them outside the database. Object type methods are called members. You can encapsulate the behavior of the business into the Object type by using members. The syntax for defining a member in an Object type follows:
CREATE Type object_type_name AS OBJECT (Object Specification) [{MAP|ORDER} MEMBER function specification] |[MEMBER {procedure_specification|function_specification}

Two types of member methods can be created: 3 Function or Procedure methods. Function and Procedure member methods can take in values as arguments. Both methods process information as coded by the developer. Function methods always return a value, unlike Procedure methods. 3 Comparison methods. Comparison methods, on the other hand, have a purpose. They are specifically defined to deal with the comparison of Object types. Two kinds of Comparison methods exist: Map member methods. Map Member methods are defined using the Map keyword in the member function declaration. The Map member method is a function, so it must return a value. Whenever you must compare two Object types, Oracle8 implicitly invokes the Map member method for that Object if it is defined. The value that Oracle8 should return should be a unique value identifying the Object type.

Chapter 24 3 Oracle8 Objects

611

ORDER member methods. ORDER member methods are defined using the ORDER keyword in the member function declaration. ORDER member method is a function, so it must return a value. The ORDER member method can also be used to compare two Object types. The ORDER methods usually takes an Object type as an input argument and compares the Object type in which it exists with the input Object type. An Object types attribute is taken as an ordering comparison. If the two Object type attributes match in value, the ORDER method returns a value of zero. If the attribute values do not match each other, a value of -1 or 1 is returned, indicating a higher or lower ordering between the two Object types.

Creating member methods


Members are defined as part of the CREATE Type command to create an Object type. The body of a member method is defined and created using the CREATE Type BODY command. The syntax for the CREATE Type BODY command follows:
CREATE {OR REPLACE} Type BODY [schema.]type_name AS MEMBER {function_declaration|procedure_declaration}; [MEMBER {function_declaration|procedure_declaration}; ] . [{MAP|ORDER} MEMBER function_declaration};] END;

Creating Map member method


Example

The following ADDRESS_t Object type has a Map function defined. When comparing two ADDRESS_t Object types, you can use the Address_id to return as an identifier of the Object type.
CREATE Type ADDRESS_t AS OBJECT ( Address_id INTEGER, Street VARCHAR2(50), City VARCHAR2(25), State VARCHAR2(2), Zip NUMBER, MAP MEMBER FUNCTION rtn_value RETURN INTEGER, PRAGMA RESTRICT_REFERENCES (rtn_value, WNDS, WNPS, RNPS, RNDS) );

612

Chapter 24 3 Oracle8 Objects

The following statement creates the body of the Map member method rtn_value:
CREATE OR REPLACE Type BODY ADDRESS_t AS MAP MEMBER FUNCTION rtn_value RETURN INTEGER IS BEGIN RETURN Address_id; END; END;

Creating ORDER member method


Example

The following SALES_t Object type has an ORDER function defined. The ORDER function takes another SALES_t Object type as an input argument.
CREATE OR REPLACE Type SALES_t AS OBJECT ( SALES_id INTEGER, SALES_TOTAL NUMBER(5,2), ORDER MEMBER FUNCTION total_sales(x IN SALES_t) RETURN INTEGER, PRAGMA RESTRICT_REFERENCES (total_sales, WNDS, WNPS, RNPS, RNDS) );

When comparing two SALES_t Object types, you can use the SALES_TOTAL attribute to identify which of the two Objects has a higher value by returning a 0, 1, or -1 value. The following statement creates the body of the ORDER member method sales_total:
CREATE OR REPLACE Type BODY SALES_t AS ORDER MEMBER FUNCTION total_sales(x IN SALES_t)RETURN INTEGER IS BEGIN RETURN sales_total - x.sales_total; END; END;

Creating Objects by example


You should use structured approach to create Oracle8 Object types. Not every Table or group of Table attributes can be considered as candidate Object types. The following steps define a methodical process identifying Object types using the library system data model as an example. 1. As a rule of thumb, all entities become Object types. The Library System has two entities: PERSON BOOKS

Chapter 24 3 Oracle8 Objects

613

Use these two entities as the initial Object types for the library system, forming the basis for this Object-relational exercise. Use these two entities to map to the following Object types: PERSON_t BOOKS_t At this time, you have only identified potential Object type candidates. Their respective data elements or methods have not been analyzed. A nice feature of the Oracle8 Objects option is incomplete Object types can be defined. This allows Object types to be defined in an incomplete fashion and then later defined completely when more information is at hand. Incomplete Object type declarations are similar to forward declaration in most programming languages, like C and Object Pascal. Incomplete types can be created using the CREATE Type command. The following statements create incomplete PERSON and BOOKS Object types:
CREATE Type PERSON_t; CREATE Type BOOKS_t;

The previous statements create two incomplete Object types in the executing Users schema. Object types cannot be currently created from the Oracle8 Schema Manager. Object types are best created using PL/SQL within SQL*Plus or SQL Worksheet. The Oracle8 Schema Manager will, however, display the types created under the Schema of the User. For example, the previous statement was executed by the User AMYC and, thus, will appear under the root of AMYCs Schema.
Tip

You must change Schema Manager to view by Schema rather than by Object type. To do this, select View By Schema from the menu in Schema Manager. Then select the Schema you wish to view. The example selects AMYC. Figure 24-5 illustrates Object types in the Oracle8 Schema Manager. Two reasons exist why Object types are only displayed in the root node of a Users Schema: Object types are not Schema Objects. You must treat Object types as templates to be used within other Object types and Object Tables. Currently, a node (like the Table Folder Icon) does not exist that displays any of the Object options in the Oracle8 Schema Manager.

614

Chapter 24 3 Oracle8 Objects

Figure 24-5: You can only see Object types when youre in the By Schema View in the Oracle8 Schema Manager.

2. Identify Object type candidates. The main purpose of this step is to identify data elements that are better served as Object types. This process is known as data abstraction. The following data elements form prime candidates for becoming Object types: Data elements common to many Tables and, thus, can be reused. Data elements that form a group and are accessed together. Analyzing the library system and applying the previous rules, the BOOKS and the PERSON Tables contain matching elements for defining the first and last name of an author (for BOOKS) and a person (for PERSON). Therefore, one Object type can be defined and shared by our new Object types (BOOKS_t and PERSON_t). I will call the Object type NamE_t. The following statement creates the NamE_t Object type:
CREATE Type NamE_t AS OBJECT( FIRST_NAME VARCHAR2(25), LAST_NAME VARCHAR2(25));

Another good candidate for an Object type appears in the PERSON Table. The following data elements in the PERSON Table are primarily used together in a unit: STREET VARCHAR2(50) CITY VARCHAR2(25) STATE VARCHAR2(2) ZIP NUMBER

Chapter 24 3 Oracle8 Objects

615

One Object type can be defined, therefore, that will handle the address elements as a unit: ADDRESS_t. The following statement creates the ADDRESS_t Object type:
CREATE Type ADDRESS_t AS OBJECT( STREET VARCHAR2(50), CITY VARCHAR2(25), STATE VARCHAR2(2) , ZIP NUMBER);

Youll find a third good candidate for creating an Object type in the BOOKS_LOANED Table. The following data elements in the BOOKS_LOANED Table can be conveniently used together to identify a book on loan: BOOK_ID LOAN_DATE FINE
INTEGER DATE NUMBER(5,2)

The BOOK_ID is a Foreign Key to the BOOKS Table. In Object terms, the BOOK_ID is a reference (REF) to the BOOKS_t Object. The new Object type (named BOOK_LOANED_t) will use this information to create an association between itself and the BOOKS_t Object previously created. The following statement creates the BOOKS_LOANED_t Object type:
CREATE Type BOOK_LOANED_t AS OBJECT (BOOK_ID REF BOOKS_t, LOAN_DATE DATE, FINE NUMBER(5,2) );

In the previous statement, the REF phrase forms an association between the BOOK_ID Column in the BOOKS_LOANED_t Object type and the BOOKS_t Object type. A final grouping of elements can be defined into another Object type. You can use the following data elements in the BOOKS_RESERVED Table together: PERSON_ID INTEGER WAIT_NO INTEGER Call the new Object type BOOKS_RESERVED_t. It will contain the two related elements and create an association between the new Object type (BOOKS_RESERVED_t) and the existing Object type called PERSON. The PERSON_ID is the referenced element in the two Object types. The following statement creates the BOOKS_RESERVED_t Object type:
CREATE Type BOOKS_RESERVED_t AS OBJECT (PERSON_ID REF PERSON_t, WAIT_NO INTEGER );

616
Note

Chapter 24 3 Oracle8 Objects

Adopting a naming standard is important when creating Object types. In the previous examples, the suffix _t has been added to the Object type names. This enables you to differentiate the Object types from other User-defined types and assists in understanding the data model and Table structures.

Getting Information about Object types


You can only use the Oracle8 Schema Manager to display the name of Object types and their type. Even this requires you view the Schema Manager in the By Schema mode rather than the Default By Object Mode. To view Objects in Schema Manager, select View By Schema from the menu in Schema Manager. Then select the Schema you wish to view. The example selects AMYC. Figure 24-6 illustrates the Oracle8 Schema Manager displaying Object type information for the library system so far.

Figure 24-6: Object types in the Oracle8 Schema Manager

To get in-depth knowledge of the Object types defined in the database, you need to use the Data Dictionary views. You can use the following views to provide information about Object types: 3 ALL_TYPES 3 ALL_TYPE_ATTRS 3 ALL_TYPE_METHODS 3 DBA_TYPES

Chapter 24 3 Oracle8 Objects

617

3 DBA_TYPE_ATTRS 3 DBA_TYPE_METHODS 3 USER_TYPES 3 USER_TYPE_ATTRS 3 USER_TYPE_METHODS The USER_TYPES view can be selected to describe the Object types created in the database for a specific User. For example:
SELECT TYPE_NAME, TYPE_OID, TYPECODE, ATTRIBUTES FROM USER_TYPES; TYPE_NAME TYPE_OID TYPECODE ATTRIBUTES --------------------------------------------------------------ADDRESS_T 18056D0890A411D187220000C08D02E4 OBJECT 4 BOOKS_RESERVED_T 18056D1390A411D187220000C08D02E4 OBJECT 2 BOOKS_T 18056D0290A411D187220000C08D02E4 OBJECT 0 BOOK_LOANED_T 18056D0E90A411D187220000C08D02E4 OBJECT 3 NAME_T 18056D0490A411D187220000C08D02E4 OBJECT 2 PERSON_T 18056D0090A411D187220000C08D02E4 OBJECT 0 6 rows selected.
Note

TYPE_OID is the Object identifier that Oracle8 uses to identify the Object type.

The USER_TYPE_ATTRS view can be selected to describe Object type attributes. For example:
SELECT Type_NAME, ATTR_NAME, ATTR_TYPE_NAME, LENGTH,PRECISION FROM USER_TYPE_ATTRS; TYPE_NAME ATTR_NAME ATTR_TYPE_NAME LENGTH PRECISION -----------------------------------------------------------ADDRESS_T STREET VARCHAR2 50 ADDRESS_T CITY VARCHAR2 25 ADDRESS_T STATE VARCHAR2 2 ADDRESS_T ZIP NUMBER BOOKS_RESERVED_T PERSON_ID PERSON_T BOOKS_RESERVED_T WAIT_NO INTEGER BOOK_LOANED_T BOOK_ID BOOKS_T BOOK_LOANED_T LOAN_DATE VARCHAR2 25 BOOK_LOANED_T FINE NUMBER 5 NAME_T FIRST_NAME VARCHAR2 25 NAME_T LAST_NAME VARCHAR2 25 11 rows selected.

618

Chapter 24 3 Oracle8 Objects

This example concludes the section describing Object type. The next section describes the second kind of Object you can create: collection type.

Collection types
Collection types are Schema Objects you can use to define multiple instances of a data element efficiently. Collection types fall into two categories: 3 VAARAYS 3 Nested Tables The main difference between collections and Object types is collection types are made up of multiple instances of the same data element or Object type. Collection types provide a powerful way to organize data instead of normalizing the data into separate Tables. You can use collections as attributes for Object types allowing multiple values for a Column to be stored efficiently. For example, it is normal for any CONTACTS Table to have multiple phone number attributes: 3 Home phone number VARCHAR2(20) 3 Work phone number VARCHAR2(20) 3 Mobile phone number VARCHAR2(20) 3 Pager number VARCHAR2(20) The common denominator between the previous attributes is they are all of the same datatype VARCHAR2(20). Each one of the previous attributes would require a separate Column definition. What happens if a particular contact has two home phone numbers? Thats where the normalization rules come into play. The normalization rules would dictate a new PHONE NUMBER Table is created to store all the phone numbers for all the contacts. Each entry in the PHONE NUMBER Table has a link back to the CONTACTS Table. Collection types are an alternative solution to creating a new Table for phone numbers. Using the collection types, the multiple phone numbers can be stored in VARRAYs and nested Tables. This encapsulates the phone number attribute into the CONTACTS Table. This is only possible when each different phone number is of the same datatype, which is true in our example. Collection types can contain both Object types and built-in datatypes. The following section describes the first kind of collection type: VARRAY.

Chapter 24 3 Oracle8 Objects

619

VARRAY type
A VARRAY type is similar to an array except that it is stored in the Column of a Table. The VARRAY type consists of a fixed number of data elements that are all of the same datatype. Each data element is ordered in respect to its position in the array. You can use VARRAYs in the following ways: 3 A datatype of a Column. 3 An Attribute of an Object type. 3 A PL/SQL variable. You can use the VARRAY type as a datatype for a Column that contains repeating groups of data. The data is stored in-line with the rest of the Table data, except when the data size goes beyond 4000 bytes. At that point the VARRAY type is stored out-of-line and treated as an Oracle8 Large Object (LOB). Column VARRAY types are usually stored in the same Tablespace as their respective row. Each VARRAY is created with a fixed number of array elements, which can be null. Oracle8 gives all the data elements in the VARRAY type an Index, which is their position in the array. The following syntax creates VARRAY types:
CREATE TYPE Type_name AS [VARRAY| VARYING ARRAY](no_of Array_elements) OF datatype
Note

The VARRAY type is also known as a VARYING ARRAY.

Creating VARRAYs by example


Example

Leveraging this information, and applying it to the library system data model, the main VARRAY candidates for which to scan are those attributes that can have repeating groups. The library system process definition determines that a person can only reserve up to ten books. An Object type has already been defined (BOOK_RESERVED_t) that captures the book reservation information. A VARRAY type can be created that stores the book reservation information in an array of BOOK_RESERVED_t Object types. The following statement creates a VARRAY type called RESERVED_LIST_t that is an array of ten BOOK_RESERVED_t Object types:
CREATE Type RESERVED_LIST_t AS VARRAY(10) OF BOOKS_RESERVED_t;

620

Chapter 24 3 Oracle8 Objects

Figure 24-7 illustrates the relationship between the BOOKS_RESERVED Object type and the RESERVED_LIST_t VARRAY type.
Figure 24-7: The RESERVED_LIST_t is a VARRAY of ten instances of the BOOKS_RESERVED_t Object type.

RESERVED_LIST_t
BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER BOOKS RESERVED t PERSON_ID REF PERSON_t WAIT_NO INTEGER

Another data element you can represent as a VARRAY type is the PERSON_PHONE Column from the PERSON Table. The creation of a VARRAY type for this column requires an Object type to be defined that captures the respective phone number information.

Chapter 24 3 Oracle8 Objects

621

The following statement creates the PHONE_t Object type:


CREATE Type PHONE_t AS OBJECT ( PHONE_TYPE VARCHAR2(20), PHONE_NUMBER VARCHAR2(20) );

The PHONE_t Object type contains attributes to hold the type of phone number that is stored, as well as the number itself. The following statement creates the VARRAY type called PHONE_LIST_t using the newly created PHONE_t Object type:
CREATE Type PHONE_LIST_t AS VARRAY(10) OF PHONE_t;

You can use the PHONE_LIST_t VARRAY type to accommodate ten phone numbers for a person.
Note

Creating a VARRAY type does not allocate space because it is only a User-defined type definition (ADT). You can SELECT the User_TYPES view to identify the collection types from the Object types. For example:
SELECT Type_NAME, Type_OID, TYPECODE, ATTRIBUTES FROM USER_TYPES; TYPE_NAME Type_OID TYPECODE ATTRIBUTES --------------------------------------------------------------ADDRESS_T 18056D0890A411D187220000C08D02E4 OBJECT 4 BOOKS_RESERVED_T 18056D1390A411D187220000C08D02E4 OBJECT 2 BOOKS_T 18056D0290A411D187220000C08D02E4 OBJECT 0 BOOK_LOANED_T 18056D0E90A411D187220000C08D02E4 OBJECT 3 NAME_T 18056D0490A411D187220000C08D02E4 OBJECT 2 PERSON_T 18056D0090A411D187220000C08D02E4 OBJECT 0 PHONE_LIST_T 18056D2190A411D187220000C08D02E4 COLLECTION 0 PHONE_T 18056D1A90A411D187220000C08D02E4 OBJECT 2 RESERVED_LIST_T 18056D1790A411D187220000C08D02E4 COLLECTION 0 9 rows selected.

You can identify both the PHONE_LIST_t and RESERVED_LIST_t VARRAY types from the preceding results because they both have COLLECTION as their TYPECODE. VARRAY is one kind of collection type. The other kind of collection type is the nested Table, which is described in the next section.

622

Chapter 24 3 Oracle8 Objects

Nested Tables
A nested Table type is very similar to a VARRAY type in that it contains a set of data elements of the same datatype. The major differences arise from the fact that nested Table types contain an unbounded number of unordered data elements. Nested Tables can only contain one attribute, whose datatype can be from the following: 3 An Oracle8 built-in datatype 3 An Object type If the Column of a nested Table contains an Object type, you can consider the nested Table a multi-Column Table. The Object types attributes will be viewed as Table Columns. The following syntax creates a nested Table type:
CREATE TYPE Type_name AS TABLE OF datatype;

You can use a nested Table type in the following ways: 3 A datatype of a Table attribute 3 An Object type attribute 3 A PL/SQL variable

When to use nested Tables


You should use nested Table types instead of VARRAY types in the following scenarios: 3 When the order of the data elements is not important. 3 When Indexing is required on an attribute of the nested Table type. 3 When there is no set limit to the number of entries for the data elements. 3 When the data elements need to be queried. If you do not satisfy the following scenarios, you should use VARRAY types instead of nested Table types.

Creating a nested Table by example


Example

Using the information gained about nested Table types, the only attribute or Object type of the library system that is a candidate for being a nested Table is the BOOKS_LOANED_t Object type. An unlimited number of books can be loaned at any one time.

Chapter 24 3 Oracle8 Objects

623

The following statement creates a nested Table type called BOOKS_LOAN_LIST_t using the BOOKS_LOANED_t Object type as the only attribute:
CREATE TYPE BOOKS_LOAN_LIST_t AS TABLE OF BOOK_LOANED_t;

Each row of the BOOKS_LOAN_LIST_t nested Table type contains a BOOKS_LOANED_t Object type.
Note

Creating a nested Table type does not allocate space as it is only a User-defined type definition (ADT).

Oracle8 Object Tables


So far the discussion on the Oracle8 Objects option has mainly focused on the definition and creation of Abstract Data Types. The Abstract Data Types create an Object-oriented structure to model real-world data. But Abstract Data Types do not store data, they only model it. Abstract Data Types can be stored in the following contexts: 3 Relational Tables in the form of Column Objects. 3 Attributes of Object types in the form of Column Objects. 3 Object Tables in the form of Row Objects. When Abstract Data Types are stored as Column Objects, you can manipulate them in the same fashion as other built-in datatypes. This section focuses on Object Tables and row Objects. A Table that contains an Object for each of its rows is known as an Object Table. The row Objects are instantiated in the context of the Object Table. Each row Object that Oracle8 creates has a globally unique and immutable Object Identifier (OID). Oracle8 stores the system-generated OID in a hidden Column. This OID is an Indexed Column used when referencing Objects with one another using the REF parameter. The following syntax creates an Object Table:
CREATE TABLE table_name of type_name
Note

Once an Object type is embedded into an Object Table, the Object type cannot be dropped until the Object Table is dropped.

624

Chapter 24 3 Oracle8 Objects

You should understand the following structures before creating Object Tables: 3 Object Table REFs 3 Object Table nested Columns 3 Object Table Indexes 3 Object Table Constraints 3 Object Table Triggers 3 Object Table Defaults I describe each of these items in the sections below, starting with Object Table REFs.

Object Table REFs


Unlike a relational Table, an Object Table does not contain a Foreign Key that allows it to be related to other Tables explicitly. Instead of Foreign Keys, Oracle8 uses an Object Identifier. The Object Identifier is created for each row Object of the Object Table. This OID allows Object types and relational Tables to refer to the row Objects in the Object Table. This referencing mechanism is implemented by using an Oracle8 REF structure. The REF structure permits an Object type to directly refer to its respective row Objects in an Object Table. An Object Table does not store a row Objects data internally. Instead, the Object Table contains pointers or references to an external Table that contains the row Objects data.
Example

For example, as we discussed in the previous section, the following statement creates a reference from the PERSON_ID attribute in the BOOKS_RESERVED_t Object type to the PERSON_t Object type.
CREATE TYPE BOOKS_RESERVED_t AS OBJECT (PERSON_ID REF PERSON_t, WAIT_NO INTEGER );

Oracle8 creates the REF structure by executing the REF function on the created row Object. The contents of the REF structure depend on the type of REF Constraint. There are three types of REF Constraints: 3 Scoped REF. If you use a scoped REF, only references to a particular Object Table are allowed. This condition allows scoped REFs to be smaller in size than the other REFs as RowID information and Object Table metadata is not required to identify the Object Table referenced by the Column or Object type. Scoped REFs provide a faster access mechanism than unscoped REFs. The syntax for a scoped REF follows:
SCOPE FOR (attribute_name) IS Object_table_name

Chapter 24 3 Oracle8 Objects

625

3 REF WITH RowID. If a REF is declared with a RowID, the RowID is stored in the Column that includes the REF. A RowID is an internal address for a row in a Table. The syntax for a REF WITH RowID follows:
attribute_name REF WITH RowID Object_type_name

3 Unscoped REF. Unscoped REFs do not contain a reference to a specific Object Table. They need to contain Object Table metadata to enable referencing. The syntax for an unscoped REF follows:
attribute_name REF Object_type_name
Note

Dangling REFs exist when the Object identified by the REF becomes unavailable (for example, if the Referenced Object is deleted).

Object Table nested Columns


If you use a nested Table type as an attribute type for a Column in an Object Table, you need the following syntax:
CREATE TABLE Table_name OF datatype NESTED TABLE nested_col_name STORES AS storage_table_for_column;

The rows of the nested Table are stored in a separate storage Table identified by the following:
NESTED TABLE nested_col_name STORE AS storage_table_for_column;

The name of the storage Table must be defined when creating nested Tables. If a Table definition contains more than one nested Table type, a separate storage Table must be defined for each nested Table type. Nested Table data is stored outside the context of the parent Table or Object that contains the nested Table type. Oracle8 maintains a link between the parent Table or Object and the nested Table(s) internally.

Object Table Indexes


Indexes, including those on nested Table attributes, can be defined on Object Table attributes in the same manner as for relational Tables. The following syntax declares Object Table Indexes:
CREATE INDEX Index_name ON object_table_name (column_name.object_attribute_name)

626

Chapter 24 3 Oracle8 Objects

Example

For example, if an ADDRESS_t Object type has the following definition:


CREATE TYPE ADDRESS_t AS OBJECT ( Address_id INTEGER, Street VARCHAR2(50), City VARCHAR2(25), State VARCHAR2(2), Zip NUMBER );

The following statement creates a STUDENT Table that contains the ADDRESS_t as an attribute:
CREATE TABLE ADDRESS_TABLE_t OF ADDRESS_t

The following statement creates an Index on the ZIP attribute of the ADDRESS_t Object type in the ADDRESS_TABLE_t Object Table:
CREATE INDEX idx_address_zip ON ADDRESS_TABLE_t(ZIP);

Object Table Constraints


Constraints can be defined for Object Tables in the same manner as Constraints on relational Tables. For example, the following statement creates a Primary Key Constraint on the ADDRESS_TABLE_t when it is created:
CREATE TABLE ADDRESS_TABLE_t OF ADDRESS_t (constraint PK_ADDRESS_1 PRIMARY KEY (address_ID));
Note

You cannot declare Constraints for Columns that have unscoped REFs.

Object Table Triggers


Triggers can be created on Object Tables in the same manner as for relational Tables with the following restrictions: 3 Triggers cannot be defined for a nested Tables storage Table. 3 LOB values cannot be modified through Triggers. 3 Collection types (VARRAY and nested Tables) values cannot be modified in the Trigger body.

Chapter 24 3 Oracle8 Objects

627

For example, the ADDRESS_TABLE_t is an Object Table containing the ADDRESS_t Object type. The following statements create the ADDRESS_t Object type and the ADDRESS_TABLE_t Object Table:
CREATE TYPE ADDRESS_t AS OBJECT ( Address_id INTEGER, Street VARCHAR2(50), City VARCHAR2(25), State VARCHAR2(2), Zip NUMBER ); CREATE TABLE ADDRESS_TABLE_t OF ADDRESS_t

The following statement creates a simple Trigger on the ADDRESS_TABLE_t Object Table.
CREATE OR REPLACE TRIGGER triu_address_table BEFORE INSERT OR UPDATE OF STATE ON ADDRESS_TABLE_T FOR EACH ROW BEGIN IF :NEW.STATE=TX THEN :NEW.CITY:=AUSTIN; END IF; END;

Object Table defaults


Object Tables can have default Values specified for their respective Object type attributes. You can only declare defaults when the Object Table is created. You can not specify them when the Object type is created. For example, the following statement creates a default value for the CITY attribute of the ADDRESS_t Object type when the ADDRESS_TABLE_t is created:
CREATE TABLE ADDRESS_TABLE_t OF ADDRESS_t (CITY DEFAULT AUSTIN);

If a relational Table contains an Abstract Data Type attribute, the default clause must contain a literal invocation of the constructor method for the Object or collection type. For example, the following statement creates a relational STUDENT Table with the ADDRESS_t Object type as an attribute:

628

Chapter 24 3 Oracle8 Objects

CREATE TABLE STUDENT ( STUDENT _ID INTEGER not Null, STUDENT _FIRST_NAME VARCHAR2(25) null , STUDENT _LAST_NAME VARCHAR2(25) null , STUDENT_ADDRESS ADDRESS_t, constraint PK_PERSON_1 primary key (STUDENT_ID) );

To create default values for the STREET_ADDRESS Column, the constructor method of the ADDRESS_t Object type needs to be invoked with the default values. For example, the following statement creates a default value for the CITY attribute of the ADDRESS_t Object type when the ADDRESS_TABLE_t is created:
CREATE TABLE STUDENT ( STUDENT _ID INTEGER not null, STUDENT _FIRST_NAME VARCHAR2(25) null , STUDENT _LAST_NAME VARCHAR2(25) null , STUDENT_ADDRESS ADDRESS_t DEFAULT ADDRESS_t( null, null, AUSTIN, null, null), constraint PK_PERSON_1 primary key (STUDENT_ID) );

The following statement invokes the constructor method of the ADDRESS_t Object type to declare the default values for the STUDENT_ADDRESS Column.
ADDRESS_t( NULL,NULL, AUSTIN, NULL, NULL)

Finalizing the library system example


At this point, enough information is at hand to complete the Object study of the library system. The following output from the User_TYPES view identifies the Abstract Data Types created so far:
TYPE_NAME TYPE_OID TYPECODE ATTRIBUTES ---------------------------------------------------------------ADDRESS_T 18056DB990A411D187220000C08D02E4 OBJECT 4 BOOKS_LOAN_LIST_T 18056DD690A411D187220000C08D02E4 COLLECTION 0 BOOKS_RESERVED_T 18056DC890A411D187220000C08D02E4 OBJECT 2 BOOKS_T 18056DC190A411D187220000C08D02E4 OBJECT 0 BOOK_LOANED_T 18056DC390A411D187220000C08D02E4 OBJECT 3 NAME_T 18056DB590A411D187220000C08D02E4 OBJECT 2 PERSON_T 18056DBF90A411D187220000C08D02E4 OBJECT 0 PHONE_LIST_T 18056DCF90A411D187220000C08D02E4 COLLECTION 0 PHONE_T 18056DD190A411D187220000C08D02E4 OBJECT 2 RESERVED_LIST_T 18056DCC90A411D187220000C08D02E4 COLLECTION 0 10 rows selected.

Chapter 24 3 Oracle8 Objects

629

At the beginning of this case study, two incomplete Object types were created: 3 PERSON_t 3 BOOKS_t The following two sections show how to complete these two Object type definitions.
PERSON_t Object type The PERSON_t Object type derived from the PERSON Table, which had the following

attributes:
PERSON_ID PERSON_FIRST_NAME PERSON_LAST_NAME PERSON_PHONE PERSON_ADDRESS PERSON_CITY PERSON_STATE PERSON_ZIP PERSON_FINE_TOTAL PERSON_BL_STATUS INTEGER VARCHAR2(25) VARCHAR2(25) VARCHAR2(20) VARCHAR2(50) VARCHAR2(25) VARCHAR2(15) VARCHAR2(10) NUMBER(5,2) CHAR

I encapsulated the following attributes into the NAME_t Object type:


PERSON_FIRST_NAME PERSON_LAST_NAME VARCHAR2(25) VARCHAR2(25)

I encapsulated the following attributes into the PHONE_LIST_t collection type:


PERSON_PHONE VARCHAR2(20)

I encapsulated the following attributes into the ADDRESS_t Object type:


PERSON_ADDRESS PERSON_CITY PERSON_STATE PERSON_ZIP VARCHAR2(50) VARCHAR2(25) VARCHAR2(15) VARCHAR2(10)

The BOOKS_LOANED Table is tightly coupled with the PERSON Table as it contains the books that people loan. The BOOK_LOANED Table was decomposed down into the BOOK_LOANED_t Object type with the following attributes:
BOOK_ID LOAN_DATE FINE REF BOOKS_t, VARCHAR2(25) NUMBER(5,2)

Because multiple people could borrow a book, a nested Table type was created named BOOKS_LOAN_LIST_t. This nested Table type can be embedded as part of

630

Chapter 24 3 Oracle8 Objects

the PERSON Object type, indicating the book that each person has on loan. At the same time, all the book fines for a person can be monitored. Using the preceding information, the following statement creates the PERSON_t Object type:
CREATE OR REPLACE TYPE PERSON_t AS OBJECT ( PERSON_ID INTEGER, PERSON_NAME NAME_t, PERSON_ADDRESS ADDRESS_t, PERSON_PHONE PHONE_LIST_t, PERSON_BK_LOANED BOOKS_LOAN_LIST_t, PERSON_BL_STATUS CHAR );

The PERSON_t Object type cannot store data as it is an Abstract Data Type; it has to exist in the context of an Object Table. The following statement creates an Object Table name PERSON_TABLE_t using the PERSON_t Object type.
CREATE TABLE PERSON_TABLE_t OF PERSON_t (PRIMARY KEY(PERSON_ID)) NESTED TABLE PERSON_BK_LOANED STORE AS BOOK_LOANS_TABLE;

The preceding statement creates the PERSON_TABLE_t Object Table with a Primary Key. I needed to add a nested Table statement to the CREATE statement. This allocated a storage Table for the PERSON_BK_LOANED nested Column.
BOOK_t Object type The BOOK_t Object type derived from the BOOKS Table, which had the following

attributes:
BOOK_ID INTEGER BOOK_PUBLISHER VARCHAR2(50) BOOK_AUTHOR_FIRST VARCHAR2(25) BOOK_AUTHOR_LAST VARCHAR2(25) BOOK_TITLE VARCHAR2(100) BOOK_SUBJECT VARCHAR2(50) BOOK_LOAN_ID INTEGER

I encapsulated the following attributes into the NAME_t Object type:


BOOK_AUTHOR_FIRST BOOK_AUTHOR_LAST VARCHAR2(25) VARCHAR2(25)

Chapter 24 3 Oracle8 Objects

631

The BOOKS_RESERVED Table is tightly coupled with the BOOKS Table because it contains a list of books reserved by people. The BOOKS_RESERVED Table was decomposed down into the BOOKS_RESERVED_t Object type with the following attributes:
PERSON_ID REF PERSON_t, WAIT_NO INTEGER

Because a book can only be reserved by ten people, a VARRAY type was created from the BOOK_RESERVED_t Object type named RESERVED_LIST_t. Using the preceding information, the following statement creates the BOOKS_t Object type:
CREATE OR REPLACE TYPE BOOKS_t AS OBJECT ( BOOK_ID INTEGER, BOOK_PUBLISHER VARCHAR2(50), BOOK_AUTHOR_NAME NAME_t, BOOK_TITLE VARCHAR2(100), BOOK_SUBJECT VARCHAR2(50), BOOK_RESERVED_LIST RESERVED_LIST_t );

The following statement creates an Object Table using the BOOKS_t Object type:
CREATE TABLE BOOK_TABLE_t OF BOOKS_t (PRIMARY KEY(BOOK_ID))

The BOOK_ID attribute of the BOOKS_t Object type is defined as the Primary Key. Figure 24-8 illustrates the Schema Manager describing the ADTs and Object Tables created for the library system.
Note

The Oracle8 Schema Manager does not display Object Tables under the Table node of a Users Schema.

Getting information about Object Tables


You can use the User_TAB_COLUMNS view to describe the Column definitions of the Tables in a Users Schema.

632

Chapter 24 3 Oracle8 Objects

Figure 24-8: Oracle8 Schema Manager displays Objects

For example, the following query describes the Column definitions in the PERSON_TABLE_t Object Table:
SELECT column_name, data_type From user_tab_columns where table_name = PERSON_TABLE_T COLUMN_NAME DATA_TYPE -------------------------PERSON_BL_STATUS CHAR PERSON_ID NUMBER PERSON_NAME NAME_T PERSON_ADDRESS ADDRESS_T PERSON_PHONE PHONE_LIST_T PERSON_BK_LOANED BOOKS_LOAN_LIST_T 6 rows selected.

The preceding output results identify the Object and collection types used in the PERSON_TABLE_t Object Table.
Note

This query does not indicate that the PERSON_TABLE_t Object Table attributes are of the PERSON_t Object type. The following query describes the Column definitions in the BOOK_TABLE_t Object Table:
SELECT column_name, data_type From user_tab_columns where table_name = BOOK_TABLE_T COLUMN_NAME DATA_TYPE ---------------------------BOOK_ID NUMBER

Chapter 24 3 Oracle8 Objects

633

BOOK_PUBLISHER BOOK_AUTHOR_NAME BOOK_TITLE BOOK_SUBJECT BOOK_RESERVED_LIST 6 rows selected.

VARCHAR2 NAME_T VARCHAR2 VARCHAR2 RESERVED_LIST_T

The preceding output results identify the Object and collection types used in the BOOK_TABLE_t Object Table.

Manipulating Object Tables


Even though the data within the business can be stored in a more natural fashion in the Oracle8 database, the data does require more skill to manipulate. This section of the chapter describes how data can be inserted, selected, updated, and deleted from an Object Table using the library system Object Tables as examples.

Inserting rows into Object Tables


Before rows can be inserted into Object Tables, you must understand the structure of the Object Table. The Object Table can contain additional Object type definitions for its attributes.
Example

The structure of the BOOK_TABLE_t follows:


BOOK_ID BOOK_PUBLISHER BOOK_AUTHOR_NAME BOOK_TITLE BOOK_SUBJECT BOOK_RESERVED_LIST NUMBER VARCHAR2 NAME_T VARCHAR2 VARCHAR2 RESERVED_LIST_T

The BOOK_TABLE_t contains the following ADTs:


NAME_t RESERVED_LIST_t

To insert a row into the BOOK_TABLE_t, you must know the structure of the NAME_t and RESERVED_LIST_t. The NAME_t Object type has the following structure:
First_Name Last_Name VARCHAR2(25) VARCHAR2(25)

The RESERVED_LIST_t is a VARRAY with the following structure:


PERSON_ID REF WAIT_NO PERSON_t INTEGER

634

Chapter 24 3 Oracle8 Objects

To insert values into the BOOK_TABLE_t, the respective Object types constructor method needs to be invoked with the values that need to be inserted for that row. This process creates an instance of the Object. The name of the constructor method is the same name as the Object or collection type. This process is known as typecasting the data. For example, the following statement inserts a row into the BOOK_TABLE_t Table:
INSERT INTO BOOK_TABLE_T VALUES (1,IDG, NAME_t(Amy, Chandi), Rough Guide to Vancouver, Travel, RESERVED_LIST_t() );

Analyzing the INSERT command, the following data is inserted for the respective Columns: 3 BOOK_ID: 1 3 BOOK_PUBLISHER: IDG 3 BOOK_AUTHOR_NAME: Amy Chandi 3 BOOK_TITLE: Rough Guide to Vancouver 3 BOOK_SUBJECT: Travel 3 BOOK_RESERVED_LIST: Empty RESERVED_LIST_t The following phrase invokes the constructor method for the NamE_t Object type and typecasts the data into the BOOK_TABLE_t Object Table.
NAME_t(Amy, Chandi)

The following phrase creates an empty RESERVED_LIST_t Object in the row Object of the BOOK_TABLE_t Object Table.
RESERVED_LIST_t()
Note

An empty collection type does not imply it contains null values. The following statement inserts a row into the PERSON_TABLE_t Object Table:
INSERT INTO PERSON_TABLE_t VALUES (1, NAME_t(Tony, Prem), ADDRESS_t(11316 Jollyville,Austin, TX, 78759), PHONE_LIST_T(PHONE_t(Home, 512-555-1212)), BOOKS_LOAN_LIST_T(), Y );

Chapter 24 3 Oracle8 Objects

635

Looking at the preceding INSERT command, the following values were inserted into the PERSON_TABLE_t Object Table: 3 PERSON_ID: 1 3 PERSON_FIRST_NAME: Tony 3 PERSON_LAST_NAME: Prem 3 PERSON_PHONE: 512-555-1212 3 PERSON_ADDRESS: 11316 Jollyville 3 PERSON_CITY: Austin 3 PERSON_STATE: TX 3 PERSON_ZIP: 78759 3 PERSON_BK_LOANED: Empty BOOK_LOAN_LIST_t 3 PERSON_BL_STATUS: Y It is important to note that the Object or collection types constructor methods need to be invoked for values to be stored within that Object. For example, the following data is inserted into the PERSON_TABLE_t Object Table using the ADDRESS_t constructor method:
ADDRESS_t(11316 Jollyville,Austin, TX, 78759),

In situations with Object types within Object types, the constructor method of the most embedded Object type is used. For example, in the following statement, the data is typecast to the PHONE_t Object type before it is typecast to the PHONE_LIST_t Object type:
PHONE_LIST_T(PHONE_t(Home, 512-555-1212)),

Inserting rows into nested Tables


If a row needs to be inserted into a nested Table, use the INSERT INTO THE statement to identify the Column, which contains the nested Table. You insert records into a nested Table by using the constructor method for its datatype.
Example

If a person wants to loan a book, a row needs to be inserted into the nested Table
BOOKS_LOAN_LIST_t in the Column PERSON_BK_LOANED, which is an attribute of the PERSON_TABLE_t Object Table.

636

Chapter 24 3 Oracle8 Objects

The following statement inserts a row into the BOOK_LOAN_LIST nested Table:
SELECT A.PERSON_BK_LOANED FROM PERSON_TABLE_t A WHERE A.PERSON_ID = 1 ) SELECT REF(C), SYSDATE, 0 FROM BOOK_TABLE_t C WHERE C.BOOK_ID = 1

The following information is typecast and stored in the BOOK_LOANS_TABLE: 3 BOOK_ID: REF to book_id 1 3 LOAN_DATE: SYSDATE 3 FINE: 0 The REF structure associates the inserted row with a row Object in BOOK_TABLE_t Object Table that has a BOOK_ID value of one.
Note

The BOOK_LOANS_TABLE is the storage Table for the nested Table BOOK_LOAN_LIST_t. All rows in the nested Table are stored externally to the parent Object Table.

Selecting data from Object Tables


If an Object Table only contains one Object type, and there are no embedded Object or collection types in its attribute definitions, the attributes of the Object type can be treated as Columns in a SELECT statement. For example, the following statement selects the PERSON_ID information from the Object Table PERSON_TABLE_t:
SELECT PERSON_ID FROM PERSON_TABLE_T;

The PERSON_ID is an attribute of the PERSON_TABLE_t Object Table. The datatype defining the PERSON_ID is an INTEGER. The following Output is produced, which gives the appearance that the Object Table is relational:
PERSON_ID ---------1 2 3 4 4 rows selected.

Chapter 24 3 Oracle8 Objects

637

If you need to select data from an embedded Object type, you must specify the extended attribute. For example, the following query retrieves data from the NamE_t embedded Object type in the PERSON_TABLE_t Object Table:
select A.PERSON_NAME.FIRST_NAME, A.PERSON_NAME.LAST_NAME from person_table_t A; PERSON_NAME.FIRST_NAME PERSON_NAME.LAST_NAME ----------------------------------------------Tony Prem Amy Chandi Cortney Dumas Patrick Mohyde 4 rows selected.

Selecting data from a VARRAY


You cannot retrieve data directly from a VARRAY using a SQL SELECT statement. The only approach to retrieving the data is to use PL/SQL subprograms. The following example retrieves the data from the PERSON_TABLE_t Object Tables phone number list.
SET SERVEROUTPUT ON DECLARE phone phone_t; phone_count integer; i integer; CURSOR PERSON_CURSOR IS SELECT * FROM PERSON_TABLE_T; PERSON_REC PERSON_CURSOR%ROWTYPE; BEGIN FOR PERSON_REC IN PERSON_CURSOR LOOP DBMS_OUTPUT.PUT_LINE(Person Name = ||PERSON_REC.person_name.First_Name |||| PERSON_REC.person_name.Last_Name); phone_count := person_rec.person_phone.count; if phone_count > 0 then for i in 1..phone_count loop begin phone := (person_rec.person_phone(i)); DBMS_OUTPUT.PUT_LINE(phone.phone_type); DBMS_OUTPUT.PUT_LINE(phone.phone_number); end; end loop; end if; END LOOP; END;

638
Note

Chapter 24 3 Oracle8 Objects

If the VARRAY to be manipulated contains an ADT, that ADT needs to be defined as a PL/SQL variable. For example: the phone_t Object was defined to structure the phone information. Once you have assigned this ADT to the VARRAY Index, you can manipulate it.

Updating Object Table rows


You can use the following SQL UPDATE statement to update the BOOK_TABLE_t Object Table:
UPDATE BOOK_TABLE_T A SET A = BOOKS_T( 1, IDG, NAME_t(Amy, Chandi), Rough Guide to British Columbia, Travel, RESERVED_LIST_t() ) where a.book_id = 1;
Note

Use the BOOKS_t Object type to typecast the data into the structure of the row Objects of the Object Table BOOK_TABLE_t.

Deleting Object Table rows


Use the relational DELETE command to delete rows in Object Tables. The following example deletes a row from the PERSON_TABLE_t Object Table with a PERSON_ID of four:
DELETE FROM PERSON_TABLE_t WHERE PERSON_ID=4;

Remember that as a row Object contains REFs from other Object types or relational attributes, the references will become invalid. The REFs from the associated Object types or relational attributes are known as dangling REFs.

Oracle8 Object Views


Oracle8 Object views are an extension of the relational view, except they are Objectoriented. Just like a relational view abstracts data from the underlying relational Tables, you can use Object views to abstract data from relational or Object Tables. You can use Object views to provide the User with a more defined Object-oriented perspective of the underlying data. Object views can be very advantageous in migrating from a relational database to an Object-relational database for the following reasons:

Chapter 24 3 Oracle8 Object Views

639

3 Object views enable data architects and developers to get a feel for the effort required to formulate Objects from the data model or entity relationship diagrams. 3 Users can get a feel for how the data is inserted into an Object-relational database using INSTEAD OF Triggers. 3 Users can get a feel for how data can be manipulated in an Object-relational database. 3 Object views can coexist with relational and Object-relational database Objects. Overall, if a relational database exists, Oracle8 Object views provide a good transition to the Object-relational world of Oracle8 without totally changing the underlying architecture of the data. Object views can be the first step into the Object-relational world of Oracle8.

Creating Object view concepts


The process of defining and creating Object views is very similar to the steps involved in creating Object Tables. The only exception in the end result is an Object view not an Object Table. Use the following steps to define and create Objects views: 1. Analyze the relational model or entity relationship model and formulate Abstract Data Types that represent the data structure of business Objects. 2. Select the data that the Object view will represent. 3. Formulate a SELECT statement that will retrieve the required data from the underlying Tables. 4. Create an Object view using the SELECT statement, assigning each row an Object Identifier. All Object views can have the following attributes: 3 A valid Schema Object name. 3 The name of the Object type upon which the Object view is based. 3 An Object Identifier based on a unique identifier for the underlying data. 3 A SELECT statement to retrieve the data from the underlying Object Tables or relational Tables.
Note

All Object views require an Object type to define the structure of the data to be retrieved; otherwise, the view would be relational.

640

Chapter 24 3 Oracle8 Objects

The following syntax creates an Object view:


CREATE OR REPLACE VIEW object_view_name OF object_type_name WITH OBJECT OID(unique_object_column) AS SELECT Statement

Creating Object views by example


The following example defines the steps to create Object views from a STUDENT and DEPARTMENT relational Table. The relationship between the two relational Tables is illustrated in Figure 24-9.

STUDENT PERSON ID STUDENT_DEPT_ID PERSON_FIRST_NAME PERSON_LAST_NAME PERSON_PHONE PERSON_STREET PERSON_CITY PERSON_STATE PERSON_ZIP INTEGER INTEGER VARCHAR2(25) VARCHAR2(25) VARCHAR2(20) VARCHAR2(50) VARCHAR2(25) VARCHAR2(2) NUMBER DEPT_ID = STUDENT_DEPT_ID DEPT ID DEPT_NAME DEPARTMENT INTEGER VARCHAR2(20)

Figure 24-9: The STUDENT and DEPARTMENT Tables are related.

Creating an Object view of the DEPARTMENT Table


The first step in creating an Object view for the DEPARTMENT Table is to understand the underlying attributes that make up the Table. This command defines the DEPARTMENT Table:
CREATE TABLE DEPARTMENT ( DEPT_ID INTEGER DEPT_NAME VARCHAR2(20) constraint PK_DEPT primary key (DEPT_ID) );

not null, not null,

From this definition, create a DEPT_t Object type with the following attributes:
DEPT_ID DEPT_NAME INTEGER VARCHAR2(20)

Chapter 24 3 Oracle8 Object Views

641

The following statement creates the DEPT_t Object type:


CREATE TYPE DEPT_t AS OBJECT( DEPT_ID INTEGER, DEPT_NAME VARCHAR(20));

From this information, create the DEPT_VIEW Object view with the following statement:
CREATE OR REPLACE VIEW DEPT_VIEW OF DEPT_t WITH OBJECT OID (DEPT_ID) AS SELECT A.DEPT_ID, A.DEPT_NAME FROM DEPARTMENT A

Looking at the command, the following phrase creates an Object Identifier for each row of the view:
WITH OBJECT OID (DEPT_ID) AS

Remember, the view will contain rows of Objects. You can select the DEPT_VIEW in the same manner as a relational view. For example:
select * from dept_view DEPT_ID DEPT_NAME --------------------------1 Computer Science 2 Travel 3 Biology 4 Physics 5 Chemistry 6 History

Creating an Object view of the STUDENT Table


The first step in creating an Object view for the STUDENT Table is to understand the underlying attributes that make up the Table. The following command defines the STUDENT Table:
CREATE TABLE STUDENT ( STU_ID INTEGER not null, STU_DEPT_ID INTEGER References department(dept_id), STU_FIRST_NAME VARCHAR2(25) null , STU_LAST_NAME VARCHAR2(25) null , STU_PHONE VARCHAR2(20) null , STU_STREET VARCHAR2(50) null , STU_CITY VARCHAR2(25) null , STU_STATE VARCHAR2(2) null , STU_ZIP NUMBER null , constraint PK_STU_1 primary key (STU_ID) );

642

Chapter 24 3 Oracle8 Objects

From the preceding Schema definition of the Table, the following Object types can be created: 3 NAME_t 3 ADDRESS_t The NAME_t Object type contains the following attributes:
FIRST_NAME LAST_NAME VARCHAR2(25) VARCHAR2(25)

The ADDRESS_t Object type contains the following attributes:


STREET CITY STATE ZIP VARCHAR2(50) VARCHAR2(25) VARCHAR2(2) NUMBER

The following statements create the NAME_t and ADDRESS_t Object types respectively:
CREATE TYPE NAME_t AS OBJECT( FIRST_NAME VARCHAR2(25), LAST_NAME VARCHAR2(25)); CREATE TYPE ADDRESS_t AS OBJECT( STREET VARCHAR2(50), CITY VARCHAR2(25), STATE VARCHAR2(2) , ZIP NUMBER);

You can now use these Object types to create a STUDENT_t Object type with the following attributes:
STU_ID STU_DEPT_ID STU_NAME STU_ADDRESS STU_PHONE INTEGER REF DEPT_t NAME_t ADDRESS_t VARCHAR2(20)

Use the REF phrase to create an Object Foreign Key relationship between the STUDENT_t Object type and the DEPT_t Object type:
STU_DEPT_ID REF DEPT_t

Putting all these components together, the following statement creates the STUDENT_t Object type:
CREATE TYPE STUDENT_T AS OBJECT( STU_ID INTEGER,

Chapter 24 3 Oracle8 Object Views

643

STU_DEPT_ID STU_NAME STU_ADDRESS STU_PHONE

REF DEPT_t , NAME_t , ADDRESS_t, VARCHAR2(20)

);

The following STUDENT_VIEW Object view can be created based on the STUDENT_t Object type:
CREATE OR REPLACE VIEW STUDENT_VIEW OF STUDENT_t WITH OBJECT OID(STU_ID) AS SELECT S.STU_ID, MAKE_REF(DEPT_VIEW, S.STU_DEPT_ID) DEPT_ID, NAME_t(S.STU_FIRST_NAME,S.STU_LAST_NAME), ADDRESS_t(S.STU_STREET, S.STU_CITY, S.STU_STATE, S.STU_ZIP), S.STU_PHONE FROM STUDENT S

The MAKE_REF operator is an important operator in this statement. This operator needs to be used to convert any Foreign Key Columns in the Object type to REF Columns in the Object view. The following phrase in the CREATE VIEW command creates a REF to the DEPT_VIEW Object view using the STU_DEPT_ID Column. The Object view Column is given an alias of DEPT_ID.
MAKE_REF(DEPT_VIEW, S.STU_DEPT_ID) DEPT_ID,

The following statement queries the STUDENT_VIEW to determine the department to which a student belongs:
declare dept dept_t; begin select DEREF(s.STU_DEPT_ID) into dept from student_view s where stu_id = 1; DBMS_OUTPUT.PUT_LINE(DEPT.DEPT_NAME); end;

Updating Object views


Object views can be updated using INSTEAD OF Triggers. INSTEAD OF Triggers are created for Object views in the same manner as Triggers are created for relational Tables. The only differing factor is INSTEAD OF Triggers get invoked instead of the DML statements executing INSERT, UPDATE, and DELETE operations.

644

Chapter 24 3 Oracle8 Objects

When creating INSTEAD OF Triggers on Object views, make sure the underlying Object view structure is known. In this case, even though the underlying STUDENT Table is being inserted into, the structure of the Object view is passing the data into the Trigger. To get information on the structure of the Object view, use the following statement:
DESC STUDENT_VIEW

This statement yields the following information on the STUDENT_VIEW:


Column Name Null? Type -----------------------------------------------------STU_ID NOT NULL NUMBER(38) STU_DEPT_ID UNDEFINED(111) STU_NAME ADT(96) STU_ADDRESS ADT(156) STU_PHONE VARCHAR2(20)

These results confirm the following Columns of the STUDENT_VIEW are Abstract Data Types: 3 STU_NAME 3 STU_ADDRESS To get further information about the STUDENT_VIEW, the following SELECT statement against the User_TAB_COLUMNS view yields a more detailed description of the Column types:
SELECT COLUMN_NAME, DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = STUDENT_VIEW COLUMN_NAME DATA_TYPE ---------------------------------------STU_ID NUMBER STU_DEPT_ID DEPT_T STU_NAME NAME_T STU_ADDRESS ADDRESS_T STU_PHONE VARCHAR2

Using the preceding structure of the STUDENT_VIEW, the following INSTEAD OF Trigger will be invoked every time an INSERT operation is executed on the STUDENT_VIEW:
CREATE OR REPLACE TRIGGER stu_view_insert_tr INSTEAD OF INSERT ON STUDENT_VIEW DECLARE DEPT DEPT_T; BEGIN

Chapter 24 3 Oracle8 Object Views

645

SELECT DEREF(:NEW.STU_DEPT_ID) INTO DEPT FROM DUAL; INSERT INTO STUDENT VALUES( :NEW.STU_ID, DEPT.DEPT_ID, :NEW.STU_NAME.FIRST_NAME, :NEW.STU_NAME.LAST_NAME, :NEW.STU_PHONE, :NEW.STU_ADDRESS.STREET, :NEW.STU_ADDRESS.CITY, :NEW.STU_ADDRESS.STATE, :NEW.STU_ADDRESS.ZIP); END;

The following INSERT statement invokes the preceding Trigger by executing an INSERT operation on the STUDENT_VIEW:
INSERT INTO STUDENT_VIEW SELECT 11, REF(D), NAME_t(Sid, Steele), ADDRESS_t(26 Lancaster Ave, Austin, TX, 78759), 512-555-1356 FROM DEPT_VIEW D WHERE D.DEPT_ID = 1;

The following SELECT statement confirms this record was inserted into the STUDENT Table:
SELECT STU_ID STUDENT_ID, STU_FIRST_NAME || ||STU_LAST_NAME STUDENT_NAME, STU_STREET|| ||STU_CITY|| ||STU_STATE STUDENT_ADDRESS FROM STUDENT; STUDENT STUDENT_NAME STUDENT_ADDRESS --------------------------------------------------------1 Amy Chandi 505 Burrard Street Vancouver BC 2 Tony Smith 1111 Southall Broadway Southall TX 3 Courtney Dumas 1245 Negril Ave Austin TX 4 Patrick Mohyde 458 Manhattan Drive Austin TX 5 Peter Smith 447 Ellen Way Vancouver TX 6 Mike Magner 69 SMART Ave Austin TX 7 Todd Enright 8578 Guadalupe Austin TX 8 Bidi Singh 1099 Lancaster Road Southall TX 9 Peter Jardin 5 Alexander Ave Talor Draper TX 10 John Britton 56 Pitter Drive Austin TX 11 Sid Steele 26 Lancaster Ave Austin TX 11 Rows selected.

This example concludes the section on Object views.

646

Chapter 24 3 Oracle8 Objects

Summary
New to Oracle8, Objects make Oracle8 an entirely new form of database: an Objectrelational database. Objects are useful in translating business rules into workable and reusable modules. Objects are reusable and you can test Objects as independent units prior to implementation. Objects are more complex to design than relational Tables and Objects are a new technology to Oracle, however, currently making it less portable than the older relational model. To use Objects, you must set up Object types, which define the structure of data. In addition to built-in methods for certain tasks, you can build any number of methods you call to operate on the data into an Object type. The data itself can be stored either in Object or relational Tables. If data is stored in relational Tables, you can create Object views that provide an Object-oriented look at the data. You can use Object views to add data to the underlying relational Table using Triggers that break out the appropriate fields and place them in the appropriate Tables.

Vous aimerez peut-être aussi