0% found this document useful (0 votes)
48 views46 pages

DDM 5

Uploaded by

Bhuvaneshwari M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views46 pages

DDM 5

Uploaded by

Bhuvaneshwari M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

UNIT-5

OBJECT RELATIONAL AND NOSQL DATABASES

5.1 Mapping EER to ODBs Schema


5.2 Object Identifier
5.3 Reference Types
5.4 Row Types
5.5 UDTs
5.6 Subtypes and Supertypes
5.7 User-defined Routines
5.8 Collection Types
5.9 Object Query Language.
1

INTRODUCTION TO OBJECT-RELATIONAL DBMSs

STORING OBJECTS IN A RELATIONAL DATABASE:


 One approach to achieving persistence with an object-oriented programming language,
such as C++ or Java, is to use an RDBMS as the underlying storage engine.
 This requires mapping class instances (that is, objects) to one or more tuples dis-tributed
over one or more relations.
 This can be problematic, as we discuss in this section. For the purposes of discussion,
consider the inheritance hierarchy shown in Figure 9.2, which has a Staff superclass and
three subclasses: Manager, SalesPersonnel, and Secretary.

To handle this type of class hierarchy, we have two basics tasks to perform:
• Design the relations to represent the class hierarchy.
• Design how objects will be accessed, which means:
– writing code to decompose the objects into tuples and store the decomposed objects in
relations;
– writing code to read tuples from the relations and reconstruct the objects.

MAPPING CLASSES TO RELATIONS:


There are a number of strategies for mapping classes to relations, although each results in a loss
of semantic information. The code to make objects persistent and to read the objects back from
the database is dependent on the strategy chosen. We consider three alternatives:
(1) Map each class or subclass to a relation.
2

(2) Map each subclass to a relation.


(3) Map the hierarchy to a single relation.

Map each class or subclass to a relation:


One approach is to map each class or subclass to a relation. (with the primary key underlined):
Staff (staffNo, fName, lName, position, sex, DOB, salary)
Manager (staffNo, bonus, mgrStartDate)
SalesPersonnel (staffNo, salesArea, carAllowance)
Secretary (staffNo, typingSpeed)

Map each subclass to a relation:


A second approach is to map each subclass to a relation.
Manager (staffNo, fName, lName, position, sex, DOB, salary, bonus, mgrStartDate)
SalesPersonnel (staffNo, fName, lName, position, sex, DOB, salary, salesArea,
carAllowance)
Secretary (staffNo, fName, lName, position, sex, DOB, salary, typingSpeed)

Map the hierarchy to a single relation:


A third approach is to map the entire inheritance hierarchy to a single relation, giving in this
case:
Staff (staffNo, fName, lName, position, sex, DOB, salary, bonus, mgrStartDate,
salesArea,
carAllowance, typingSpeed, typeFlag)

ACCESSING OBJECTS IN THE RELATIONAL DATABASE:


Having designed the structure of the relational database, we now need to insert objects into the
database and then provide a mechanism to read, update, and delete the objects.

Manager* pManager 5 new Manager; // create a new Manager object


. . . code to set up the object . . .
EXEC SQL INSERT INTO Staff VALUES (:pManager->staffNo, :pManager-> fName,
: pManager->lName: pManager->position, :pManager->sex,: pManager->DOB,
:pManager->salary);
EXEC SQL INSERT INTO Manager VALUES (:pManager->bonus,
:pManager->mgrStartDate);
On the other hand, if Manager had been declared as a persistent class, then the following
(indicative) statement would make the object persistent in an OODBMS:

Manager* pManager 5 new Manager;


3

Here we examine different approaches for declaring persistent classes. If we need to retrieve
some data from the relational database, the details for managers with a bonus in excess of £1000,
the code might look like the following:

Manager* pManager 5 new Manager; // create a new Manager object


EXEC SQL WHENEVER NOT FOUND GOTO done; // set up error handling
EXEC SQL DECLARE manager Cursor // create cursor for SELECT
CURSOR FOR
SELECT staffNo, fName, lName, salary, bonus
FROM Staff s, Manager m // Need to join Staff and Manager
WHERE s.staffNo 5 m.staffNo AND bonus > 1000;
EXEC SQL OPEN managerCursor;
for ( ; ; ) {
EXEC SQL FETCH managerCursor // fetch the next record in the result
INTO :staffNo, :fName, :lName, :salary, :bonus;
pManager->staffNo 5 :staffNo; // transfer the data to the Manager object
pManager->fName 5 :fName;
pManager->lName 5 :lName;
pManager->salary 5 :salary;
pManager->bonus 5 :bonus;
strcpy(pManager->position, “Manager”);
}
EXEC SQL CLOSE managerCursor; // close the cursor before completing.

On the other hand, to retrieve the same set of data in an OODBMS, we may write the following
code:
os_Set<Manager*> &highBonus
5 managerExtent->query(“Manager*”, “bonus > 1000”, db1);

INTRODUCTION TO OBJECT-RELATIONAL DATABASE SYSTEMS


 Relational DBMSs are currently the dominant database technology, with an estimated
total software revenue worldwide of US$24 billion in 2011 and estimated to grow to
about US$37 billion by 2016.

 Until recently, the choice of DBMS seemed to be between the relational DBMS and the
object-oriented DBMS. However, many vendors of RDBMS products are conscious of
the threat and promise of the OODBMS.

 They agree that traditional relational DBMSs are not suited to the advanced applications
However, they reject the claim that extended RDBMSs will not provide sufficient
functionality or will be too slow to cope adequately with the new complexity.
4

 If we examine the advanced database applications that are emerging, we find they make
extensive use of many object-oriented features such as a user-extensible type system,
encapsulation, inheritance, polymorphism, dynamic binding of methods, complex objects
including non-first normal form objects, and object identity.

 The most obvious way to remedy the shortcomings of the relational model is to extend
the model with these types of features. This is the approach that has been taken by many
extended relational DBMSs, although each has implemented different combinations of
features.

 Thus, there is no single extended relational model; rather, there are a variety of these
models, whose characteristics depend upon the way and the degree to which extensions
were made.

 However, all the models do share the same basic relational tables and query language, all
incorporate some concept of “object,” and some have the ability to store methods (or
procedures or triggers) as well as data in the database.

 Various terms have been used for systems that have extended the relational data model.
The original term that was used to describe such systems was the Extended Relational
DBMS (ERDBMS) and the term Universal Server or Universal DBMS (UDBMS) has
also been used.

 However, in recent years the more descriptive term Object-Relational DBMS has been
used to indicate that the system incorporates some notion of “object.”

 Here we use the term Object-Relational DBMS (ORDBMS). Three of the leading
RDBMS vendors—Oracle, Microsoft, and IBM—have all extended their systems into
ORDBMSs, although the functionality provided by each is slightly different.

 The concept of the ORDBMS, as a hybrid of the RDBMS and the OODBMS, is very
appealing, preserving the wealth of knowledge and experience that has been acquired
with the RDBMS—so much so that some analysts predict the ORDBMS will have a 50%
larger share of the market than the RDBMS.

 As might be expected, the standards activity in this area is based on extensions to the
SQL standard. The national standards bodies have been working on object extensions
to SQL since 1991.
 These extensions have become part of the SQL standard, with releases in 1999,
referred to as SQL:1999, 2003, (SQL:2003), 2006 with extensions for XML
5

(SQL:2006), 2008 (SQL:2008) and 2011 (SQL:2011). These releases of the SQL
standard are an ongoing attempt to standardize extensions to the relational model and
query language.

STONEBRAKER’S VIEW:
 Stonebraker (1996) proposed a four-quadrant view of the database world.

 In the lower-left quadrant are applications that process simple data and have no
requirements for querying the data. These types of applications—for example, standard
text processing packages such as Microsoft Word—can use the underlying operating
system to obtain the essential DBMS functionality of persistence.

 In the lower-right quadrant are applications that process complex data, but again have no
significant requirements for querying the data. For these types of applications—for
example, computer-aided design packages—an OODBMS may be an appropriate choice
of DBMS.

 In the top-left quadrant are applications that process simple data and also have
requirements for complex querying. Many traditional business applications fall into this
quadrant and an RDBMS may be the most appropriate DBMS.

 Finally, in the top-right quadrant are applications that process complex data and have
complex querying requirements. This represents many of the advanced database
applications and for these applications Stonebraker argues that an ORDBMS may be the
most appropriate choice of DBMS.
6

ADVANTAGES OF ORDBMSS:
1. Reusable and Sharable – able to reuse the hard-coded components. Through database
servers those components can be shared among available resources.
2. Ability of applying Objects with existing RDBMS models as it is – That is, RDBMS can
be extended with Object concepts without changing the underlying models. This leads the
organizations to switch over to ORDBMS concepts easily without performing bigger
migration or major changes.
3. It allows users and programmers to start using object-oriented systems in parallel.
4. Object Relational Database Management Systems ensures large storage capacity.
5. Supports rich data types by adding a new object-oriented layer.
6. Scalability
7. Relationships are represented explicitly, often supporting both navigational and
associative access to information.
8. Improved concurrency - concurrent users can safely query the same data.
9. Support for Composite data types - data is bundled with its metadata.
10. Improved integrity - ability to reject bad data before it is stored in an ORDBMS.
11. Database extensibility - easy addition of data types and operations.
12. Uniform treatment of data items - the SQL interface can perform complex queries
based on any of these data items, e.g., metadata as well as data; hence there is less need
for custom programming by users.
13. Custom data access methods - e.g., R-tree indexes.
14. Point-in-time recovery of data is possible.
7

15. Built-in complex SQL functions can be provided for data operations - e.g., aggregating,
slicing, subsetting, reprojecting, etc.

DISADVANTAGES OF ORDBMSS:
1. Complexity
2. Increased cost
3. Unclear if the ORDBMS will actually combine relationships and encapsulated objects to
correctly and completely mirror the ‘real world’.
4. Optimal Performance

5.1 MAPPING EER TO ODB SCHEMA


Object database design:
 Object-Oriented Model is the process of representing real-world entities as objects in
computer programs.
 It is a fundamental aspect of Object Database Conceptual Design.
 Object-oriented modeling is more flexible and dynamic than traditional relational
models.
 It enables developers to model complex relationships between objects more
efficiently.
 Object-oriented modeling allows for inheritance, encapsulation, and polymorphism. It
is easier to maintain and modify code.

Object Database
An object database stores data in the form of objects. These objects can contain both data
and methods for accessing and manipulating that data. Object databases work with object-
oriented programming languages, like Java and Python.
8

ODB Design RDB Design

Relationships are handled by relationship Relationships among tuples (records) are


properties or reference attributes that include specified by attributes with matching values.
OID(s) of the related objects.

Relationships can be represented using single Relationships are limited to being single-
references or collections of references. valued in each record because multivalued
attributes are not permitted in the basic
relational model.

Mapping binary relationships that contain M: N relationships must be represented not


attributes is not straightforward, and it may be directly but as a separate relation (table).
preferable to create a separate class to
represent the relationship.

Inheritance is handled using the inheritance No built-in construct exists for inheritance in
constructs such as derived (:) and extends. the basic relational model. Several options are
available to choose from.

Operations are part of the class specifications Operations may be delayed until the
and need to be specified early on in the implementation phase.
design.

The object model mandates the predefinition The relational model does not mandate the
of a set of valid behaviors or operations. database designers to predefine a set of valid
behaviors or operations.

Supports ad hoc queries and transactions. Encapsulation is a fundamental principle, and


ad hoc queries and transactions are not
encouraged.

Mapping an EER schema to an ODB schema is a process of designing the type declarations of
object classes for an Object Database Management System (ODBMS) from an Entity-
Relationship (ER) diagram. Here are the stepwise instructions to perform this mapping.

The outline of the mapping from EER to ODB is as follows:


Step-1
Create an ODL class for each EER entity type or subclass. The ODL class should include all
the attributes of the EER class. Multivalued attributes are typically declared by using set, bag, or
list constructors. Declare an extent for each class and specify any key attributes as keys of the
extent.

Step-2
9

Add relationship properties or reference attributes for each binary relationship into the ODL
classes that participate in the relationship. Depending on the cardinality ratio of the binary
relationship, the relationship properties or reference attributes may be single-valued or collection
type.
Step-3
Include appropriate operations for each class. These are not available from the EER schema
and must be added to the database design by referring to the original requirements.

Step-4
An ODL class that corresponds to a subclass in the EER schema inherits the type and methods
of its superclass in the ODL schema. Its specific (non-inherited) attributes, relationship
references, and operations are specified.

Step-5
Weak entity types can be mapped in the same way as regular entity types. An alternative
mapping is possible for weak entity types that do not participate in any relationships except their
identifying relationship.

Step-6
Categories (union types) in an EER schema are difficult to map to ODL. One way is to create a
class to represent the category and define 1:1 relationship between the category and each of its
superclasses.

Step-7
An n-ary relationship with degree n > 2 can be mapped into a separate class, with appropriate
references to each participating class. An M: N binary relationship may also use this mapping
option if desired.

After completing the structural mapping, add operations for each class, including constructor
and destructor methods that check for constraints. The mapping can be applied to a subset of the
database schema in the context of the ODMG object database standard.

Challenges in Object Database Design:


 Object Database Conceptual Design has many benefits and challenges.
 It can be complex.
 It may require a significant amount of time and effort to create a robust and efficient
object model.
 Integration with existing systems can also be challenging.
 As object databases may need to work with other databases that use the relational model.
 Performance issues can arise due to the complex relationships between objects.
10

Conclusion:
 When designing a database, it is important to consider the needs of the applications.
 It is a unique way to database design that is more flexible and dynamic than traditional
relational models.
 The conceptual design of object databases involves object-oriented modeling. Which
allows for inheritance, encapsulation, and polymorphism.
 Mapping an EER schema to ODB schema involves several steps, including creating ODL
classes, adding relationship properties, and including appropriate operations for each
class.
 However, there are also challenges in object database design. These are complexity,
integration with existing systems, and performance issues due to the complex
relationships between objects.

SQL:2011
 An extensive tutorial on the features of the ISO SQL standard, concentrating mainly on
those features present in the 1992 version of the standard, commonly referred to as SQL2
or SQL-92.
 ANSI (X3H2) and ISO (ISO/IEC JTC1/SC21/WG3) SQL standardization have added
features to the SQL specification to support object-oriented data management, the latest
release of which is SQL:2011 (ISO, 2011a).

As we mentioned earlier, the SQL:2011 standard is extremely large and comprehensive, and is
divided into the following parts:
(1) ISO/IEC 9075–1: SQL/Framework.

(2) ISO/IEC 9075–2: SQL/Foundation, which includes new data types, user-defined
types, rules and triggers, transactions, stored routines, and binding methods (embedded
SQL, dynamic SQL, and direct invocation of SQL).

(3) ISO/IEC 9075–3: SQL/CLI (Call-Level Interface), which specifies the provision of an
API interface to the database, as we discuss in Appendix I, based on the SQL Access
Group and X/Open’s CLI definitions.

(4) ISO/IEC 9075–4: SQL/PSM (Persistent Stored Modules), which allows procedures
and user-defined functions to be written in a 3GL or in SQL and stored in the database,
making SQL computationally complete.
(5) ISO/IEC 9075–9: SQL/MED (Management of External Data), which defines
extensions to SQL to support management of external data through the use of foreign
tables and datalink data types.
11

(6) ISO/IEC 9075–10: SQL/OLB (Object Language Bindings), which defines facilities
for embedding SQL statements in Java programs.

(7) ISO/IEC 9075–11: SQL/Schemata (Information and Definition Schemas), which


defines two schemas INFORMATION_SCHEMA and DEFINITION_SCHEMA. The
Information Schema defines views about database objects such as tables, views, and
columns. These views are defined in terms of the base tables in the Definition Schema.

(8) ISO/IEC 9075–13: SQL/JRT (Java Routines and Types Using the Java Programming
Language), which defines extensions to SQL to allow the invocation of static methods
written in Java as SQL-invoked routines, and to use classes defined in Java as SQL
structured types.

(9) ISO/IEC 9075–14: SQL/XML (XML-Related Specifications), which defines


extensions to SQL to enable creation and manipulation of XML documents.

In this section we examine some of these features, and cover these topics:
1. Type constructors for row types and reference types;
2. User-defined types (distinct types and structured types) that can participate in
Supertype/subtype relationships;
3. User-defined procedures, functions, methods, and operators;
4. Type constructors for collection types (arrays, sets, lists, and multisets);
5. Support for large objects—Binary Large Objects (BLOBs) and Character Large Objects
(CLOBs);
6. recursion.

5.4 ROW TYPES:


 A row type is a sequence of field name/data type pairs that provides a data type to
represent the types of rows in tables, so that complete rows can be stored in variables,
passed as arguments to routines, and returned as return values from function calls.
 A row type can also be used to allow a column of a table to contain row values. In
essence, the row is a table nested within a table.

Example: Use of Row Type.


12

5.5 USER-DEFINED TYPES:


 SQL:2011 allows the definition of user-defined types (UDTs), referred to as abstract data
types (ADTs). They may be used in the same way as the predefined types (for example,
CHAR, INT, FLOAT).
 UDTs are subdivided into two categories: distinct types and structured types. The simpler
type of UDT is the distinct type, which allows differentiation between the same
underlying base types.

For example, we could create the following two distinct types:


CREATE TYPE OwnerNumberType AS VARCHAR (5) FINAL;
CREATE TYPE StaffNumberType AS VARCHAR (5) FINAL;

If we now attempt to treat an instance of one type as an instance of the other type, an error would
be generated. UDT definition consists of one or more attribute definitions, zero or more routine
declarations (methods) and, in a subsequent release, operator declarations. We refer to routines
and operators generically as routines. In addition, we can also define the equality and ordering
relationships for the UDT using the CREATE ORDERING FOR statement. The value of an
attribute can be accessed using the common dot notation (.).

Example, assuming p is an instance of the UDT PersonType, which has an attribute fName of
type VARCHAR, we can access the fName attribute as:
p.fName
p.fName 5 ‘A. Smith’

Encapsulation and observer and mutator functions:


13

 SQL encapsulates each attribute of structured types by providing a pair of built-in


routines that are invoked whenever a user attempts to reference the attribute, an observer
(get) function and a mutator (set) function.
 The observer function returns the current value of the attribute; the mutator function sets
the value of the attribute to a value specified as a parameter.
 These functions can be redefined by the user in the definition of the UDT.
 In this way, attribute values are encapsulated and are accessible to the user only by
invoking these functions.

For example, the observer function for the fName attribute of PersonType would be:
FUNCTION fName (p PersonType) RETURNS VARCHAR (15)
RETURN p. fName;

and the corresponding mutator function to set the value to newValue would be:
FUNCTION fName (p PersonType RESULT, newValue VARCHAR (15))
RETURNS PersonType
BEGIN
p. fName 5 newValue;
RETURN p;
END;

Constructor functions and the NEW expression:


 A (public) constructor function is automatically defined to create new instances of the
type.
 The constructor function has the same name and type as the UDT, takes zero arguments,
and returns a new instance of the type with the attributes set to their default value.
 User-defined constructor methods can be provided by the user to initialize a newly
created instance of a structured type.
 Each method must have the same name as the structured type but the parameters must be
different from the system-supplied constructor.
 In addition, each user-defined constructor method must differ in the number of
parameters or in the data types of the parameters.

example, we could initialize a constructor for type PersonType as follows:


CREATE CONSTRUCTOR METHOD PersonType (fN VARCHAR (15),
lN VARCHAR (15), sx CHAR) RETURNS PersonType SELF AS RESULT
BEGIN
SET SELF.fName 5 fN;
SET SELF.lName 5 lN;
SET SELF.sex 5 sx;
RETURN SELF;
14

END;
The NEW expression can be used to invoke the system-supplied constructor function; for
example:
SET p 5 NEW PersonType ();

User-defined constructor methods must be invoked in the context of the NEW expression. For
example, we can create a new instance of PersonType and invoke the previous user-defined
constructor method as follows:

SET p 5 NEW PersonType (‘John’, ‘White’, ‘M’);


This is effectively translated into:
SET p 5 PersonType ().PersonType(‘John’, ‘White’, ‘M’);

Other UDT methods:


Instances of UDTs can be constrained to exhibit specified ordering properties. The EQUALS
ONLY BY and ORDER FULL BY clauses may be used to specify type specific functions for
comparing UDT instances. The ordering can be performed using methods that are qualified as:

 RELATIVE- The relative method is a function that returns a 0 for equals, a negative
value for less than, and a positive value for greater than.
 MAP- The map method uses a function that takes a single argument of the UDT type and
returns a predefined data type. Comparing two UDTs is achieved by comparing the two
map values associated with them.
 STATE- The state method compares the attributes of the operands to determine an order.

CAST functions can also be defined to provide user-specified conversion functions between
different UDTs. In a subsequent version of the standard, it may also be possible to override some
of the built-in operators.
15

5.6 SUBTYPES AND SUPERTYPES:


 SQL:2011 allows UDTs to participate in a subtype/supertype hierarchy using the
UNDER clause.
 A type can have more than one subtype but currently only one supertype (that is, multiple
inheritance is not supported).
 A subtype inherits all the attributes and behavior (methods) of its supertype and it can
define additional attributes and methods like any other UDT and it can override inherited
methods.

Example 9.3 Creation of a subtype using the UNDER clause


To create a subtype StaffType of the supertype PersonType, we write:
CREATE TYPE StaffType UNDER PersonType AS (
staffNo VARCHAR(5),
position VARCHAR(10) DEFAULT ‘Assistant’,
salary DECIMAL(7, 2),
branchNo CHAR(4))
INSTANTIABLE
NOT FINAL
INSTANCE METHOD isManager () RETURNS BOOLEAN;
16

CREATE INSTANCE METHOD isManager () RETURNS BOOLEAN


FOR StaffType
BEGIN
IF SELF.position 5 ‘Manager’ THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF
END)

An instance of a subtype is considered an instance of all its supertypes. SQL:2011 supports the
concept of substitutability: that is, whenever an instance of a supertype is expected an instance of
the subtype can be used in its place. The type of a UDT can be tested using the TYPE predicate.

For example, given a UDT, say Udt1, we can apply the following tests:
TYPE Udt1 IS OF (PersonType) // Check Udt1 is the PersonType or any of its subtypes
TYPE Udt1 IS OF (ONLY PersonType) // Check Udt1 is the PersonType

Privileges:
 To create a subtype, a user must have the UNDER privilege on the user-defined type
specified as a supertype in the subtype definition.
 In addition, a user must have USAGE privilege on any user-defined type referenced
within the new type.
 Prior to SQL:1999, the SELECT privilege applied only to columns of tables and views.
 From SQL:1999, the SELECT privilege also applies to structured types, but only when
instances of those types are stored in typed tables and only when the dereference operator
is used from a REF value to the referenced row and then invokes a method on that
referenced row.
 When invoking a method on a structured value that is stored in a column of any ordinary
SQL table, SELECT privilege is required on that column.
 If the method is a mutator function, UPDATE privilege is also required on the column. In
addition, EXECUTE privilege is required on all methods that are invoked.

5.7 USER-DEFINED ROUTINES:


 User-defined routines (UDRs) define methods for manipulating data and are an important
adjunct to UDTs providing the required behavior for the UDTs.

Example (a) Initial Student/Staff hierarchy;


(b) modified Student/Staff hierarchy
17

.
 An ORDBMS should provide significant flexibility in this area, such as allowing UDRs
to return complex values that can be further manipulated (such as tables), and support for
overloading of function names to simplify application development.

 In SQL:2011, UDRs may be defined as part of a UDT or separately as part of a schema.


An SQL-invoked routine may be a procedure, function, or method. It may be externally
provided in a standard programming language such as C, C++, or Java, or defined
completely in SQL using extensions that make the language computationally complete.

 An SQL-invoke procedure is invoked from an SQL CALL statement. It may have zero or
more parameters, each of which may be an input parameter (IN), an output parameter
(OUT), or both an input and output parameter (INOUT), and it has a body if it is defined
fully within SQL. An SQL-invoked function returns a value; any specified parameters
must be input parameters. One input parameter can be designated as the result (using the
18

RESULT keyword), in which case the parameter’s data type must match the type of the
RETURNS type. Such a function is called type-preserving, because it always returns a
value whose runtime type is the same as the most specific type of the RETURN
parameter (not some subtype of that type). Mutator functions are always type-preserving.

An SQL-invoked method is similar to a function but has some important differences:


 A method is associated with a single UDT;
 The signature of every method associated with a UDT must be specified in that UDT and
the definition of the method must specify that UDT (and must also appear in the same
schema as the UDT).

There are three types of methods:


 Constructor methods, which initialize a newly created instance of a UDT;
 Instance methods, which operate on specific instances of a UDT;
 Static methods, which are analogous to class methods in some object-oriented
programming languages and operate at the UDT level rather than at the instance level.

In the first two cases, the methods include an additional implicit first parameter called SELF
whose data type is that of the associated UDT.A method can be invoked in one of three ways:
 A constructor method is invoked using the NEW expression, as discussed previously;
 An instance method is invoked using the standard dot notation; for example, p. fName, or
using the generalized invocation format, for example, (p AS StaffType). fName ();
 A static method is invoked using: for example, if total Staff is a static method of
StaffType, we could invoke it as StaffType: total Staff ().

An external routine is defined by specifying an external clause that identifies the corresponding
“compiled code” in the operating system’s file storage.

For example, we need to use a function that creates a thumbnail image for an object stored in the
database. The functionality cannot be provided in SQL and so we have to use a function
provided externally, using the following CREATE FUNCTION statement with an EXTERNAL
clause:
CREATE FUNCTIONthumbnail(IN myImage ImageType) RETURNS BOOLEAN
EXTERNAL NAME ‘/usr/dreamhome/bin/images/thumbnail’
LANGUAGE C
PARAMETER STYLE GENERAL
DETERMINISTIC
NO SQL;

POLYMORPHISM:
19

The concepts of overriding, overloading, and more generally polymorphism. Different routines
may have the same name; that is, routine names may be overloaded, for example to allow a UDT
subtype to redefine a method inherited from a supertype, subject to the following constraints:
 No two functions in the same schema are allowed to have the same signature, that is, the
same number of arguments, the same data types for each argument, and the same return
type.
 No two procedures in the same schema are allowed to have the same name and the same
number of parameters.

Instance method invocation:


The mechanism for determining the appropriate invocation of an instance method is divided into
two phases representing static analysis and runtime execution. In this section we provide an
overview of these phases. The first phase proceeds as follows:
 All routines with the appropriate name are identified (all remaining routines are
eliminated).
 All procedures/functions and all methods for which the user does not have EXECUTE
privileges are eliminated.
 All methods that are not associated with the declared type (or subtype) of the implicit
SELF argument are eliminated.
 All methods whose parameters are not equal to the number of arguments in the method
invocation is eliminated.
 For the methods that remain, the system checks that the data type of each parameter
matches the precedence list of the corresponding argument, eliminating those methods
that do not match.
 If there are no candidate methods remaining a syntax error occurs.

For the remaining candidate methods, the second (runtime) phase proceeds as follows:
 If the most specific type of the runtime value of the implicit argument to the method
invocation has a type definition that includes one of the candidate methods, then that
method is selected for execution.
 If the most specific type of the runtime value of the implicit argument to the method
invocation has a type definition that does not include one of the candidate methods, then
the method selected for execution is the candidate method whose associated type is the
nearest supertype of all supertypes having such a method.
 The argument values are converted to the parameter data types, if appropriate, and the
body of the method is executed.

5.2 – 5.3 REFERENCE TYPES AND OBJECT IDENTITY:


 Object identity is that aspect of an object that never changes and that distinguishes the
object from all other objects.
20

 Ideally, an object’s identity is independent of its name, structure, and location, and
persists even after the object has been deleted, so that it may never be confused with the
identity of any other object. Other objects can use an object’s identity as a unique way of
referencing it.

 Before SQL:1999, the only way to define relationships between tables was using the
primary key/foreign key mechanism, which in SQL2 could be expressed using the
referential table constraint clause REFERENCES.

 Since SQL:1999, reference types have been able to be used to define relationships
between row types and uniquely identify a row within a table. A reference type value can
be stored in one (typed) table and used as a direct reference to a specific row in some
base table that has been defined to be of this type (similar to the notion of a pointer type
in C or C++).

 Thus, references allow a row to be shared among multiple tables and enable users to
replace complex join definitions in queries with much simpler path expressions.
References also give the optimizer an alternative way to navigate data instead of using
value-based joins.

 REF IS SYSTEM GENERATED in a CREATE TYPE statement indicates that the actual
values of the associated REF type are provided by the system.

CREATING TABLES:
 To maintain upwards compatibility with the SQL2 standard, it is still necessary to use the
CREATE TABLE statement to create a table, even if the table consists of a single UDT.
 In other words, a UDT instance can persist only if it is stored as the column value in a
table. There are several variations of the CREATE TABLE statement.

Example- Creation of a table based on a UDT


To create a table using the PersonType UDT, we could write:
CREATE TABLE Person (
info PersonType
CONSTRAINT DOB_Check CHECK (dateOfBirth > DATE ‘1900-01-01’));
(or)
CREATE TABLE Person OF PersonType (
dateOfBirth WITH OPTIONS
CONSTRAINT DOB_Check CHECK (dateOfBirth > DATE ‘1900-01-01’)
REF IS PersonID SYSTEM GENERATED);
21

 In the first instance, we would access the columns of the Person table using a path
expression such as ‘Person.info.fName’; in the second version, we would access the
columns using a path expression such as ‘Person.fName’.

 More importantly, tables constructed using the second version (CREATE TABLE . . . OF
statement) are called typed tables. The rows of a typed table are considered to be objects,
and the rows in the first version are not, even though the same UDT has been used in
both cases. A typed table has a column for every attribute of the structured type on which
it is based. In addition, a typed table has a self-referencing column that contains a unique
OID (known as a reference) for each row of the table.

 Objects are inserted into a typed table using the normal INSERT statement as for any
relational table. Apart from the self-referencing column and the attributes of the
structured type, no additional columns can be added to the table definition.

 The OID is generated automatically when a new row is inserted into the typed table.
However, to gain access to the OIDs stored in the self-referencing column, we have to
give the column name explicitly using the REF IS clause (PersonID in our example).
Note that a typed table definition must also repeat a reference generation specification
that is consistent with the corresponding specification in the UDT: system-generated,
user-generated, or derived.

Example- Creation of a subtable using the UNDER clause


We can create a table for staff using table inheritance:
CREATE TABLE Staff OF StaffType UNDER Person;
When we insert rows into the Staff table, the values of the inherited columns are inserted into the
Person table. Similarly, when we delete rows from the Staff table, the rows disappear from both
the Staff and Person tables. As a result, when we access all rows of Person, this will also include
all Staff details.

There are restrictions on the population of a table hierarchy:


• Each row of the supertable Person can correspond to at most one row in Staff.
• Each row in Staff must have exactly one corresponding row in Person.

 The semantics maintained are those of containment: a row in a subtable is in effect


“contained” in its super tables. We would expect the SQL INSERT, UPDATE, and
DELETE statements to maintain this consistency when the rows of sub tables and super
tables are being modified.
 When a row is inserted into a subtable, then the values of any inherited columns of the
table are inserted into the corresponding super tables, cascading upwards in the table
hierarchy.
22

For example, referring to Figure(b), if we insert a row into PTStudentStaff, then the values of the
inherited columns are inserted into Student and Staff, and then the values of the inherited
columns of Student/Staff are inserted into Person.

 When a row is updated in a subtable, a procedure to the previous one is carried out to
update the values of inherited columns in the supertables.
 When a row is updated in a supertable, then the values of all inherited columns in all
corresponding rows of its direct and indirect subtables are also updated accordingly. As
the supertable may itself be a subtable, the previous condition will also have to be applied
to ensure consistency.
 When a row is deleted in a subtable/supertable, the corresponding rows in the table
hierarchy are deleted. For example, if we deleted a row of Student, the corresponding
rows of Person and Undergraduate/Postgraduate/PartTimeStudent/PTStudentStaffare
deleted.

SQL:2011 does not provide a mechanism to store all instances of a given UDT unless the user
explicitly creates a single table in which all instances are stored. Thus, in SQL:2011 it may not
be possible to apply an SQL query to all instances of a given UDT. For example, if we created
another table such as:
CREATE TABLE Client (
info PersonType,
prefType CHAR,
maxRent DECIMAL (6, 2),
branchNo VARCHAR (4) NOT NULL);

Example- Using a reference type to define a relationship


In this example, we model the relationship between PropertyForRent and Staff using a reference
type.

CREATE TABLE PropertyForRent (


propertyNo PropertyNumber NOT NULL,
street Street NOT NULL,
city City NOT NULL,
postcode PostCode,
type PropertyType NOT NULL DEFAULT ‘F’,
rooms PropertyRooms NOT NULL DEFAULT 4,
rent PropertyRent NOT NULL DEFAULT 600,
staffID REF(StaffType) SCOPE Staff
REFERENCES ARE CHECKED ON DELETE CASCADE,
PRIMARY KEY (propertyNo));
23

PRIVILEGES:
 As with the privileges required to create a new subtype, a user must have the UNDER
privilege on the referenced supertable.
 In addition, a user must have USAGE privilege on any user-defined type referenced
within the new table.

QUERYING DATA:
 SQL:2011 provides the same syntax as SQL2 for querying and updating tables, with
various extensions to handle objects.

1.Example- Retrieve a specific column, specific rows.


Find the names of all Managers.
SELECT s.lName
FROM Staff s
WHERE s. position 5 ‘Manager’;

This query invokes the implicitly defined observer function position in the WHERE clause to
access the position column.

2.Example- Invoking a user-defined function


Find the names and ages of all Managers.
SELECT s.lName, s.age
FROM Staff s
WHERE s. isManager;

This alternative method of finding Managers uses the user-defined method isManager as a
predicate of the WHERE clause. This method returns the boolean value TRUE if the member of
staff is a manager. In addition, this query also invokes the inherited virtual (observer) function
age as an element of the SELECT list.

3.Example- Use of ONLY to restrict selection


Find the names of all people in the database over 65 years of age.
SELECT p.lName, p.fName
FROM Person p
WHERE p.age > 65;

This query lists not only the details of rows that have been explicitly inserted into the Person
table, but also the names from any rows that have been inserted into any direct or indirect
subtables of Person, in this case, Staff and Client.
24

Suppose, however, that rather than wanting the details of all people, we want only the details
of the specific instances of the Person table, excluding any subtables. This can be achieved using
the ONLY keyword:
SELECT p.lName, p.fName
FROM ONLY (Person) p
WHERE p.age > 65;

4.Example- Use of the dereference operator:


Find the name of the member of staff who manages property ‘PG4’.
SELECT p.staffID–>fName AS fName, p.staffID–>lName AS lName
FROM PropertyForRent p
WHERE p. propertyNo 5 ‘PG4’;

To retrieve the member of staff for property PG4, rather than just the first and last names, we
would use the following query instead:
SELECT DEREF(p.staffID) AS Staff
FROM PropertyForRent p
WHERE p.propertyNo 5 ‘PG4’;

Although reference types are similar to foreign keys, there are significant differences. In
SQL:2011, referential integrity is maintained only by using a referential constraint definition
specified as part of the table definition. By themselves, reference types do not provide referential
integrity. Thus, the SQL reference type should not be confused with that provided in the ODMG
object model. In the ODMG model, OIDs are used to model relationships between types and
referential integrity is automatically defined.

5.8 COLLECTION TYPES:


 Collections are type constructors that are used to define collections of other types.
 Collections are used to store multiple values in a single column of a table and can result
in nested tables where a column in one table actually contains another table.
 The result can be a single table that represents multiple master-detail levels. Thus,
collections add flexibility to the design of the physical database structure.

 SQL:1999 introduced an ARRAY collection type and SQL:2003 added the MULTISET
collection type, and a subsequent version of the standard may introduce parameterized
LIST and SET collection types.
 In each case, the parameter, called the element type, may be a predefined type, a UDT, a
row type, or another collection, but cannot be a reference type or a UDT containing a
reference type. In addition, each collection must be homogeneous: all elements must be
of the same type, or at least from the same type hierarchy.
 The collection types have the following meaning:
25

• ARRAY—one-dimensional array with a maximum number of elements;


• MULTISET—unordered collection that does allow duplicates;
• LIST—ordered collection that allows duplicates;
• SET—unordered collection that does not allow duplicates.

ARRAY collection type:


 An array is an ordered collection of not necessarily distinct values, whose elements are
referenced by their ordinal position in the array.
 An array is declared by a data type and optionally a maximum cardinality; for example:
VARCHAR (25) ARRAY [5]
 The elements of this array can be accessed by an index ranging from 1 to the maximum
cardinality (the function CARDINALITY returns the number of current elements in the
array).
 Two arrays of comparable types are considered identical if and only if they have the same
cardinality and every ordinal pair of elements is identical.
 An array type is specified by an array type constructor, which can be defined by
enumerating the elements as a comma-separated list enclosed in square brackets or by
using a query expression with degree 1; for example:
ARRAY [‘Mary White’, ‘Peter Beech’, ‘Anne Ford’, ‘John Howe’, ‘Alan Brand’]
ARRAY (SELECT rooms FROM PropertyForRent)
 In these cases, the data type of the array is determined by the data types of the various
array elements.

Example - Use of a collection ARRAY


To model the requirement that a branch has up to three telephone numbers, we could implement
the column as an ARRAY collection type:
telNo VARCHAR (13) ARRAY [3]

We could now retrieve the first and last telephone numbers at branch B003 using the following
query:
SELECT telNo[1], telNo[CARDINALITY (telNo)]
FROM Branch
WHERE branchNo 5 ‘B003’;

MULTISET COLLECTION TYPE:


 A multiset is an unordered collection of elements, all of the same type, with duplicates
permitted. Because a multiset is unordered there is no ordinal position to reference
individual elements of a multiset.

 Unlike arrays, a multiset is an unbounded collection with no declared maximum


cardinality (although there will be an implementation-defined limit). Although multisets
26

are analogous to tables, they are not regarded as the same as tables, and operators are
provided to convert a multiset to a table (UNNEST) and a table to a multiset
(MULTISET).

 There is currently no separate type proposed for sets. Instead, a set is simply a special
kind of multiset: one that has no duplicate elements. A predicate is provided to check
whether a multiset is a set. Two multisets of comparable element types, A and B say, are
considered identical if and only if they have the same cardinality and for each element x
in A, the number of elements of A that are identical to x, including x itself, equals the
number of elements of B that are equal to x. Again, as with array types, a multiset type
constructor can be defined by enumerating their elements as a comma-separated list
enclosed in square brackets, or by using a query expression with degree 1, or by using a
table value constructor.

Operations on multisets include:


 The SET function, to remove duplicates from a multiset to produce a set.
 The CARDINALITY function, to return the number of current elements.
 The ELEMENT function, to return the element of a multiset if the multiset only has one
element (or null if the multiset has no elements). An exception is raised if the multiset has
more than one element.
 MULTISET UNION, which computes the union of two multisets; the keywords ALL or
DISTINCT can be specified to either retain duplicates or remove them.
 MULTISET INTERSECT, which computes the intersection of two multisets; the
keyword DISTINCT can be specified to remove duplicates; the keyword ALL can be
specified to place in the result as many instances of each value as the minimum number
of instances of that value in either operand.
 MULTISET EXCEPT, which computes the difference of two multisets; again, the
keyword DISTINCT can be specified to remove duplicates; the keyword ALL can be
specified to place in the result a number of instances of a value, equal to the number of
instances of the value in the first operand minus the number of instances of the second
operand.

There are three new aggregate functions for multisets:


 COLLECT, which creates a multiset from the value of the argument in each row of a
group;
 FUSION, which creates a multiset union of a multiset value in all rows of a group;
 INTERSECTION, which creates the multiset intersection of a multiset value in all rows
of a group.

In addition, a number of predicates exist for use with multisets:


 Comparison predicate (equality and inequality only);
27

 DISTINCT predicate;
 MEMBER predicate;
 SUBMULTISET predicate, which tests whether one multiset is a sub multiset of another;
 IS A SET/IS NOT A SET predicate, which checks whether a multiset is a set.

1.Example- Use of a collection MULTISET


 Extend the Staff table to contain the details of a number of next-of-kin and then find the
first and last names of John White’s next-of-kin.
 We include the definition of a nextOfKin column in Staff as follows (NameType contains
a fName and lName attribute)
nextOfKin NameType MULTISET

The query becomes:


SELECT n.fName, n.lName
FROM Staff s, UNNEST (s.nextOfKin) AS n(fName, lName)
WHERE s.lName 5 ‘White’ AND s.fName 5 ‘John’;
Note that in the FROM clause we may use the multiset-valued field s.nextOfKin as a table
reference.

2.Example- Use of the FUSION and INTERSECTION aggregate functions


Consider the following table, PropertyViewDates, giving the dates properties have been viewed
by potential renters:

The following query based on multiset aggregation:


SELECT FUSION(viewDates) AS viewDateFusion,
INTERSECTION (viewDates) AS viewDateIntersection
FROM PropertyViewDates;
produces the following result set:
28

TYPED VIEWS:
 SQL:2011 also supports typed views, sometimes called object views or referenceable
views. A typed view is created based on a particular structured type and a sub view can
be created based on this typed view.

Example- Creation of typed views


The following statements create two views based on the PersonType and StaffType structured
types:
CREATE VIEW FemaleView OF PersonType (REF IS personID DERIVED)
AS SELECT fName, lName
FROM ONLY (Person)
WHERE sex 5 ‘F’;

CREATE VIEW FemaleStaff3View OF StaffType UNDER FemaleView


AS SELECT fName, lName, staffNo, position
FROM ONLY (Staff)
WHERE branchNo 5 ‘B003’;

PERSISTENT STORED MODULES


 A number of new statement types have been added to SQL to make the language
computationally complete, so that object behavior (methods) can be stored and executed
from within the database as SQL statements.

TRIGGERS:
 A trigger is an SQL (compound) statement that is executed automatically by the DBMS
as a side effect of a modification to a named table.
 It is similar to an SQL routine, in that it is a named SQL block with declarative,
executable, and condition handling sections.
 However, unlike a routine, a trigger is executed implicitly whenever the triggering event
occurs, and a trigger does not have any arguments.
 The act of executing a trigger is sometimes known as firing the trigger.
29

Triggers can be used for a number of purposes including:


 Validating input data and maintaining complex integrity constraints that otherwise would
be difficult, if not impossible, through table constraints;
 Supporting alerts (for example, using electronic mail) that action needs to be taken when
a table is updated in some way;
 Maintaining audit information, by recording the changes made, and by whom;
 Supporting replication.

The basic format of the CREATE TRIGGER statement is as follows:


CREATE TRIGGER TriggerName
BEFORE | AFTER | INSTEAD OF <triggerEvent> ON <TableName>
[REFERENCING <oldOrNewValuesAliasList>]
[FOR EACH {ROW | STATEMENT
[WHEN (triggerCondition)]
<triggerBody>

Triggering events include insertion, deletion, and update of rows in a table. In the latter case
only, a triggering event can also be set to cover specific named columns of a table. A trigger has
an associated timing of either BEFORE, AFTER, or INSTEAD OF. A BEFORE trigger is fired
before the associated event occurs, an AFTER trigger is fired after the associated event occurs,
and an INSTEAD OF trigger is fired in place of the trigger event.

The triggered action is an SQL procedure Statement, which can be executed in one of two ways:
 For each row affected by the event (FOR EACH ROW). This is called a row-level
trigger;
 Only once for the entire event (FOR EACH STATEMENT), which is the default. This is
called a statement-level trigger.

The <oldOrNewValuesAliasList> can refer to:


 An old or new row (OLD/NEW or OLD ROW/NEW ROW), in the case of a row level
trigger;
 An old or new table (OLD TABLE/NEW TABLE), in the case of an AFTER trigger.

Clearly, old values are not applicable for insert events, and new values are not applicable for
delete events. The body of a trigger cannot contain any:
 SQL transaction statements, such as COMMIT or ROLLBACK;
 SQL connection statements, such as CONNECT or DISCONNECT;
 SQL schema definition or manipulation statements, such as the creation or deletion of
tables, user-defined types, or other triggers;
 SQL session statements, such as SET SESSION CHARACTERISTICS, SET ROLE,
SET TIME ZONE.
30

Furthermore, SQL does not allow mutating triggers, that is, triggers that cause a change resulting
in the same trigger to be invoked again, possibly in an endless loop. As more than one trigger can
be defined on a table, the order of firing of triggers are important. Triggers are fired as the trigger
event (INSERT, UPDATE, DELETE) is executed. The following order is observed:

(1) Execution of any BEFORE statement-level trigger on the table.


(2) For each row affected by the statement:
(a) execution of any BEFORE row-level trigger;
(b) execution of the statement itself;
(c) application of any referential constraints;
(d) execution of any AFTER row-level trigger.
(3) Execution of any AFTER statement-level trigger on the table.

Example- Use of an AFTER INSERT trigger


Create a set of mailshot records for each new PropertyForRent row. For the purposes of this
example, assume that there is a Mailshot table that records prospective renter details and
property details.
CREATE TRIGGER InsertMailshotTable
AFTER INSERT ON PropertyForRent
REFERENCING NEW ROW AS pfr
BEGIN ATOMIC
INSERT INTO Mailshot VALUES
(SELECT c. fName, c. lName, c. maxRent, pfr. propertyNo,
pfr. street, pfr. city, pfr. postcode, pfr. type, pfr. rooms,
pfr.rent
FROM Client c
WHERE c.branchNo 5 pfr.branchNo AND
(c.prefType 5 pfr.type AND c.maxRent <5 pfr.rent))
END;
This trigger is executed after the new row has been inserted. The FOR EACH clause has been
omitted, defaulting to FOR EACH STATEMENT, as an INSERT statement only inserts one row
at a time. The body of the trigger is an INSERT statement based on a subquery that finds all
matching client rows.

Example- Use of an AFTER INSERT trigger with condition


Create a trigger that modifies all current mailshot records if the rent for a property changes.
CREATE TRIGGER UpdateMailshotTable
AFTER UPDATE OF rent ON PropertyForRent
REFERENCING NEW ROW AS pfr
FOR EACH ROW
31

BEGIN ATOMIC
DELETE FROM Mailshot WHERE maxRent > pfr.rent;
UPDATE Mailshot SET rent 5 pfr.rent
WHERE propertyNo 5 pfr.propertyNo;
END;
This trigger is executed after the rent field of a PropertyForRent row has been updated. The FOR
EACH ROW clause is specified, as all property rents may have been increased in one UPDATE
statement, for example due to a cost of living rise. The body of the trigger has two SQL
statements: a DELETE statement to delete those mailshot records where the new rental price is
outside the client’s price range, and an UPDATE statement to record the new rental price in all
rows relating to that property.

Triggers can be a very powerful mechanism if used appropriately. The major advantage is that
standard functions can be stored within the database and enforced consistently with each update
to the database. This can dramatically reduce the complexity of applications.

However, there can be some disadvantages:


 Complexity- When functionality is moved from the application to the database, the
database design, implementation, and administration tasks become more complex.
 Hidden functionality- Moving functionality to the database and storing it as one or more
triggers can have the effect of hiding functionality from the user.
 Performance overhead- When the DBMS is about to execute a statement that modifies
the database, it now has to evaluate the trigger condition to check whether a trigger
should be fired by the statement.

PRIVILEGES:
 To create a trigger, a user must have TRIGGER privilege on the specified table, SELECT
privilege on any tables referenced in the triggerCondition of the WHEN clause, together
with any privileges required to execute the SQL statements in the trigger body.

LARGE OBJECTS
A large object is a data type that holds a large amount of data, such as a long text file or a
graphics file. Three different types of large object data types are defined in SQL:2011:
 Binary Large Object (BLOB), a binary string that does not have a character set or
collation association;
 Character Large Object (CLOB) and National Character Large Object (NCLOB), both
character strings.

The SQL large object is slightly different from the original type of BLOB that appears in some
database systems. In such systems, the BLOB is a noninterpreted byte stream, and the DBMS
does not have any knowledge concerning the content of the BLOB or its internal structure.
32

The standard string operators, which operate on characters strings and return character strings,
also operate on character large object strings.

such as:
1. The concatenation operator, (string1 i string2), which returns the character string formed
by joining the character string operands in the specified order.
2. The character substring function, SUBSTRING(string FROM startpos FOR length),
which returns a string extracted from a specified string from a start position for a given
length.
3. The character overlay function, OVERLAY (string1 PLACING string2 FROM startpos
FOR length), replaces a substring of string1, specified as a starting position and a length,
with string2. This is equivalent to: SUBSTRING (string1 FROM 1 FOR length − 1) i
string2 i SUBSTRING (string1 FROM startpos + length).
4. The fold functions, UPPER (string) and LOWER (string), which convert all characters in
a string to upper/lower case.
5. The trim function, TRIM([LEADING | TRAILING | BOTH string1 FROM] string2),
which returns string2 with leading and/or trailing string1 characters removed. If the
FROM clause is not specified, all leading and trailing spaces are removed from string2.
6. The length function, CHAR_LENGTH(string), which returns the length of the specified
string.
7. The position function, POSITION(string1 IN string2), which returns the start position of
string1 within string2.

A binary large object (BLOB) string is defined as a sequence of octets. All BLOB strings are
comparable by comparing octets with the same ordinal position. The following operators operate
on BLOB strings and return BLOB strings, and have similar functionality as those defined
previously:
• The BLOB concatenation operator (i);
• The BLOB substring function (SUBSTRING);
• The BLOB overlay function (OVERLAY);
• The BLOB trim function (TRIM).
In addition, the BLOB_LENGTH and POSITION functions and the LIKE predicate can also be
used with BLOB strings.

Example - Use of Character and Binary Large Objects


Extend the Staff table to hold a resumé and picture for the staff member.
ALTER TABLE Staff
ADD COLUMN resume CLOB (50K);
ALTER TABLE Staff
ADD COLUMN picture BLOB (12M);
33

RECURSION:
 A major new operation in SQL for specifying such queries is linear recursion.
 A relationship between two entities of a similar entity type is called a recursive
relationship.
 Atomicity of data means that repeating groups are not allowed in the relational model. As
a result, it is extremely difficult to handle recursive queries, that is, queries about
relationships that a relation has with itself (directly or indirectly).
WITH RECURSIVE
AllManagers (staffNo, managerStaffNo) AS
(SELECT staffNo, managerStaffNo
FROM Staff
UNION
SELECT in. staffNo, out. managerStaffNo
FROM AllManagers in, Staff out
WHERE in. managerStaffNo 5 out. StaffNo);
SELECT * FROM AllManagers
ORDER BY staffNo, managerStaffNo;

The recursion statement allows the specification of two orderings:


 Depth-first, where each ‘parent’ or ‘containing’ item appears in the result before the
items that it contains, as well as before its ‘siblings’ (items with the same parent or
container);
 Breadth-first, where items follow their ‘siblings’ without following the siblings’
children.

For example, at the end of the WITH RECURSIVE statement we could add the following clause:
SEARCH BREADTH FIRST BY staffNo, managerStaffNo
SET order Column

OBJECT-ORIENTED EXTENSIONS IN ORACLE:


 We examine some of the standard facilities of Oracle, including the base data types
supported by Oracle, the procedural programming language PL/SQL, stored procedures
and functions, and triggers.
 Many of the object-oriented features that appear in the new SQL:2011 standard appear in
Oracle in one form or another.

5.5 USER-DEFINED DATA TYPES:


 Oracle supports two user-defined data types: object types and collection types.

Object types
34

 An object type is a schema object that has a name, a set of attributes based on the built-in
data types or possibly other object types, and a set of methods. similar to what we
discussed for an SQL:2011 object type.

For example, we could create Address, Staff, and Branch types as follows:
CREATE TYPE AddressType AS OBJECT (
street VARCHAR2(25),
city VARCHAR2(15),
postcode VARCHAR2(8));

CREATE TYPE StaffType AS OBJECT (


staffNo VARCHAR2(5),
fName VARCHAR2(15),
lName VARCHAR2(15),
position VARCHAR2(10),
sex CHAR,
DOB DATE,
salary DECIMAL(7, 2),
MAP MEMBER FUNCTION age RETURN INTEGER,
PRAGMA RESTRICT_REFERENCES(age, WNDS, WNPS, RNPS))
NOT FINAL;
CREATE TYPE BranchType AS OBJECT (
branchNo VARCHAR2(4),
address AddressType,
MAP MEMBER FUNCTION getbranchNo RETURN VARCHAR2(4),
PRAGMA RESTRICT_REFERENCES(getbranchNo, WNDS, WNPS,RNDS, RNPS));

We can then create a Branch (object) table using the following statement:
CREATE TABLE Branch OF BranchType (branchNo PRIMARY KEY);

METHODS:
 The methods of an object type are classified as member, static, or explicit comparison. A
member method is a function or a procedure that always has an implicit or explicit SELF
parameter as its first parameter, whose type is the containing object type. Such methods
are useful as observer and mutator functions and are invoked in the selfish style.

 A static method is a function or a procedure that does not have an implicit SELF
parameter. Such methods are useful for specifying user-defined constructors or cast
methods and may be invoked by qualifying the method with the type name, as in
typename.method().
35

A comparison method is used for comparing instances of object types. Oracle provides two ways
to define an order relationship among objects of a given type:
1. A map method uses Oracle’s ability to compare built-in types. In our example, we have
defined a map method for the new type BranchType, which compares two branch objects
based on the values in the branchNo attribute. We show an implementation of this
method shortly.
2. An order method uses its own internal logic to compare two objects of a given object
type. It returns a value that encodes the order relationship. For example, it may return −1
if the first is smaller, 0 if they are equal, and 1 if the first is larger.

For an object type, either a map method or an order method can be defined, but not both. If an
object type has no comparison method, Oracle cannot determine a greater than or less than
relationship between two objects of that type. However, it can attempt to determine whether two
objects of the type are equal using the following rules:

 If all the attributes are nonnull and equal, the objects are considered equal;
 If there is an attribute for which the two objects have unequal nonnull values, the objects
are considered unequal;
 Otherwise, Oracle reports that the comparison is not available (null). Methods can be
implemented in PL/SQL, Java, and C, and overloading is supported provided their formal
parameters differ in number, order, or data type.

Example:
CREATE OR REPLACE TYPE BODY BranchType AS
MAP MEMBER FUNCTION getbranchNo RETURN VARCHAR2(4) IS
BEGIN
RETURN branchNo;
END;
END;

CREATE OR REPLACE TYPE BODY StaffType AS


MAP MEMBER FUNCTION age RETURN INTEGER IS
var NUMBER;
BEGIN
var :5 TRUNC (MONTHS_BETWEEN (SYSDATE, DOB)/12);
RETURN var;
END;
END;

In general, user-defined functions can be used in:


 The select list of a SELECT statement;
36

 A condition in the WHERE clause;


 The ORDER BY or GROUP BY clauses;
 The VALUES clause of an INSERT statement;
 The SET clause of an UPDATE statement.

Oracle also allows user-defined operators to be created using the CREATE OPERATOR
statement. Like built-in operators, a user-defined operator takes a set of operands as input and
return a result. Once a new operator has been defined, it can be used in SQL statements like any
other built-in operator.

Constructor methods Every object type has a system-defined constructor method that makes a
new object according to the object type’s specification. The constructor method has the same
name as the object type and has parameters that have the same names and types as the object
type’s attributes. For example, to create a new instance of BranchType, we could use the
following expression:
BranchType (‘B003’, AddressType (‘163 Main St’, ‘Glasgow’, ‘G11 9QX’));

5.2 OBJECT IDENTIFIERS:


 Every row object in an object table has an associated logical object identifier (OID),
which by default is a unique system-generated identifier assigned for each row object.
 The purpose of the OID is to uniquely identify each row object in an object table. To do
this, Oracle implicitly creates and maintains an index on the OID column of the object
table.
 The OID column is hidden from users and there is no access to its internal structure.
Although OID values in themselves are not very meaningful, the OIDs can be used to
fetch and navigate objects. (Note, objects that appear in object tables are called row
objects and objects that occupy columns of relational tables or as attributes of other
objects are called column objects.)
 Oracle requires every row object to have a unique OID. The unique OID value may be
specified to come from the row object’s primary key or to be system generated, using
either the clause OBJECT IDENTIFIER IS PRIMARY KEY or OBJECT IDENTIFIER
IS SYSTEM GENERATED (the default) in the CREATE TABLE statement.

For example, we could restate the creation of the Branch table as:
CREATE TABLE Branch OF BranchType (branchNo PRIMARY KEY)
OBJECT IDENTIFIER IS PRIMARY KEY;

REF DATA TYPE:


 Oracle provides a built-in data type called REF to encapsulate references to row objects
of a specified object type. In effect, a REF is used to model an association between two
row objects.
37

 A REF can be used to examine or update the object it refers to and to obtain a copy of the
object it refers to. The only changes that can be made to a REF are to replace its contents
with a reference to a different object of the same object type or to assign it a null value.
At an implementation level, Oracle uses object identifiers to construct REFs.

 As in SQL:2011, a REF can be constrained to contain only references to a specified


object table, using a SCOPE clause. As it is possible for the object identified by a REF to
become unavailable.

Example:
CREATE TYPE BranchType AS OBJECT (
branchNo VARCHAR2(4),
address AddressType,
manager REF StaffType,
MAP MEMBER FUNCTION getbranchNo RETURN VARCHAR2(4),
PRAGMA RESTRICT_REFERENCES (getbranchNo, WNDS, WNPS,RNDS, RNPS));

TYPE INHERITANCE:
 Oracle supports single inheritance allowing a subtype to be derived from a single parent
type.
 The subtype inherits all the attributes and methods of the supertype and additionally can
add new attributes and methods, and it can override any of the inherited methods. As with
SQL:2011, the UNDER clause is used to specify the supertype.

5.8 COLLECTION TYPES:


 For modeling multi-valued attributes and many-to-many relationships, Oracle currently
supports two collection types: array types and nested tables.
 Array types, an array is an ordered set of data elements that are all of the same data type.
Each element has an index, which is a number corresponding to the element’s position in
the array. An array can have a fixed or variable size, although in the latter case a
maximum size must be specified when the array type is declared.

For example, a branch office can have up to three telephone numbers, which we could model in
Oracle by declaring the following new type:
CREATE TYPE TelNoArrayType AS VARRAY (3) OF VARCHAR2(13);

The creation of an array type does not allocate space but instead defines a data type that can be
used as:
1. The data type of a column of a relational table;
2. An object type attribute;
38

3. A PL/SQL variable, parameter, or function return type.

For example, we could modify the type BranchType to include an attribute of this new type:
phoneList TelNoArrayType,

An array is normally stored inline, that is, in the same tablespace as the other data in its row. If it
is sufficiently large, however, Oracle stores it as a BLOB.

Nested tables A nested table is an unordered set of data elements that are all of the same data
type. It has a single column of a built-in type or an object type. If the column is an object type,
the table can also be viewed as a multicolumn table, with a column for each attribute of the
object type. For example, to model next-of-kin for members of staff, we may define a new type
as follows:

CREATE TYPE NextOfKinType AS OBJECT (


fName VARCHAR2(15),
lName VARCHAR2(15),
telNo VARCHAR2(13));
CREATE TYPE NextOfKinNestedType AS TABLE OF NextOfKinType;

We can now modify the type StaffType to include this new type as a nested table:
nextOfKin NextOfKinNestedType,

and create a table for staff using the following statement:


CREATE TABLE Staff OF StaffType (
PRIMARY KEY staffNo)
OBJECT IDENTIFIER IS PRIMARY KEY
NESTED TABLE nextOfKin STORE AS NextOfKinStorageTable (
(PRIMARY KEY(Nested_Table_Id, lName, telNo))
ORGANIZATION INDEX COMPRESS)
RETURN AS LOCATOR;

Nested tables differ from arrays in the following ways:


1. Arrays have a maximum size, but nested tables do not.
2. Arrays are always dense, but nested tables can be sparse, and so individual elements can
be deleted from a nested table but not from an array.
3. Oracle stores array data inline (in the same tablespace) but stores nested table data out of
line in a store table, which is a system-generated database table associated with the nested
table.
4. When stored in the database, arrays retain their ordering and subscripts, but nested tables
do not.
39

MANIPULATING OBJECT TABLES:


Manipulate object tables using the sample objects.
For example, we can insert objects into the Staff table as follows:

INSERT INTO Staff VALUES (‘SG37’, ‘Ann’, ‘Beech’, ‘Assistant’, ‘F’, ‘10-Nov-
1960’, 12000, NextOfKinNestedType ());
INSERT INTO Staff VALUES (‘SG5’, ‘Susan’, ‘Brand’, ‘Manager’, ‘F’, ‘3-Jun-
1940’, 24000, NextOfKinNestedType ());

The expression NextOfKinNestedType () invokes the constructor method for this type to create
an empty nextOfKin attribute. We can insert data into the nested table using the following
statement:

INSERT INTO TABLE (SELECT s.nextOfKin


FROM Staff s
WHERE s. staffNo 5 ‘SG5’)
VALUES (‘John’, ‘Brand’, ‘0141-848-2000’);

This statement uses a TABLE expression to identify the nested table as the target for the
insertion, namely the nested table in the nextOfKin column of the row object in the Staff table
that has a staffNo of ‘SG5’. Finally, we can insert an object into the Branch table:

INSERT INTO Branch


SELECT ‘B003’, AddressType (‘163 Main St’, ‘Glasgow’, ‘G11 9QX’), REF(s),
TelNoArrayType (‘0141-339-2178’, ‘0141-339-4439’)
FROM Staff s
WHERE s. staffNo 5 ‘SG5’;
or alternatively:
INSERT INTO Branch VALUES (‘B003’, AddressType (‘163 Main St’, ‘Glasgow’,
‘G11 9QX’), (SELECT REF(s) FROM Staff s WHERE s. staffNo 5 ‘SG5’),
TelNoArrayType (‘0141-339-2178’, ‘0141-339-4439’));

Querying object tables In Oracle, we can return an ordered list of branch numbers using the
following query:

SELECT b. branchNo
FROM Branch b
ORDER BY VALUE(b);
40

This query implicitly invokes the comparison method getbranchNo that we defined as a map
method for the type BranchType to order the data in ascending order of branchNo. We can return
all the data for each branch using the following query:

SELECT b. branchNo, b. address, DEREF (b. manager), b. phoneList


FROM Branch b
WHERE b.address. City 5 ‘Glasgow’
ORDER BY VALUE(b);

Note the use of the DEREF operator to access the manager object. This query writes out the
values for the branchNo column, all columns of an address, all columns of the manager object
(of type StaffType), and all relevant telephone numbers. We can retrieve next of kin data for all
staff at a specified branch using the following query:

SELECT b. branchNo, b. manager. StaffNo, n.*


FROM Branch b, TABLE (b. manager. NextOfKin) n
WHERE b. branchNo 5 ‘B003’;

Many applications are unable to handle collection types and instead require a flattened view of
the data. In this example, we have flattened (or unnested) the nested set using the TABLE
keyword.

OBJECT VIEWS
 The way that a view is a virtual table, an object view is a virtual object table.
 Object views allow the data to be customized for different users.

For example, assume that we have created the object types defined and assume that we have
created and populated the following relational schema for DreamHome with associated
structured types BranchType and StaffType:

Branch (branchNo, street, city, postcode, mgrStaffNo)


Telephone (telNo, branchNo)
Staff (staffNo, fName, lName, position, sex, DOB, salary, branchNo)
NextOfKin (staffNo, fName, lName, telNo)

We could create an object-relational schema using the object view mechanism as follows:
CREATE VIEW Staff View OF StaffType WITH OBJECT IDENTIFIER (staffNo) AS
SELECT s. staffNo, s. fName, s. lName, s.sex, s. position, s.DOB, s. salary,
CAST (MULTISET (SELECT n. fName, n. lName, n. telNo
FROM NextOfKin n WHERE n. staffNo 5 s. staffNo)
AS NextOfKinNestedType) AS nextOfKin
41

FROM Staff s;

CREATE VIEW Branch View OF BranchType WITH OBJECT IDENTIFIER


(branchNo) AS
SELECT b. branchNo, AddressType (b. street, b. city, b. postcode) AS address,
MAKE_REF (StaffView, b. mgrStaffNo) AS manager,
CAST (MULTISET (SELECT telNo FROM Telephone t
WHERE t. branchNo 5 b. branchNo) AS TelNoArrayType) AS phoneList
FROM Branch b;

Privileges:
Oracle defines the following system privileges for user-defined types:
1. CREATE TYPE – to create user-defined types in the user’s schema;
2. CREATE ANY TYPE – to create user-defined types in any schema;
3. ALTER ANY TYPE – to alter user-defined types in any schema;
4. DROP ANY TYPE – to drop named types in any schema;
5. EXECUTE ANY TYPE – to use and reference named types in any schema;
6. UNDER ANY TYPE – to create subtypes under any non-final object types;
7. UNDER ANY VIEW – to create sub views under any object view.

In addition, the EXECUTE schema object privilege allows a user to use the type to define a
table, define a column in a relational table, declare a variable or parameter of the named type,
and to invoke the type’s methods.

5.9 OBJECT QUERY LANGUAGE:


 Object Query Language (OQL) is a query language used in object-oriented databases
(OODBs) to manipulate and retrieve objects stored in the database.
 It provides a standardized syntax for expressing queries, similar to SQL in relational
databases.
 OQL allows users to perform operations such as selecting, inserting, updating, and
deleting objects, as well as navigating through object relationships.
 It's designed to work seamlessly with the complex data structures and relationships
inherent in object-oriented databases.

Use OQL to create new databases or insert data into existing databases (to configure the
operation of Network Manager components) by amending the component schema files. You can
also issue OQL statements using the OQL Service Provider, for example, to create or modify
databases, insert data into databases and retrieve data.

Example:
SELECT c. address
42

FROM Persons p,
p. children c
WHERE p. address. street="Main Street" AND
COUNT (p. children) >= 2 AND
c.address. City! = p. address. City;

SELECT=> can construct new objects and arbitrary structures.


FROM=> tuple variables can range over any collection; may have subqueries.
WHERE=> the same as in SQL.

– Conventions and sample databases


To illustrate the OQL keywords in use, a sample database has been used, the staff database,
which contains three tables: managers, employees, and contractors.
– Features of OQL
The following topics describe the features of Object Query Language (OQL).
– Database and table creation
You can create databases and tables with the create command.
create database staff_db;
create table managers (id int, name varchar (50), department varchar (50));
create table employees (id int, name varchar (50), department varchar (50), salary
decimal (10, 2));
create table contractors (id int, name varchar (50), project varchar (50), hourly_rate
decimal (10, 2));

– Inserting data into a table


Use the insert keyword to insert data into a table.
insert into managers values (1, 'John Doe', 'Finance');
insert into employees values (101, 'Alice Smith', 'HR', 50000.00);
insert into contractors values (201, 'Bob Johnson', 'Software Development', 25.00);

– Selecting data from a table


You can query the data in a table using the select keyword. Use these examples to help you use
the select keyword.
select * from managers;
select name, department from employees;
select id, project from contractors where hourly_rate > 20.00;

– Counting rows in a table


You can count the number of rows in a table using the select keyword.
select count(*) from employees;
43

– Conditional tests in OQL


Use comparison operators in OQL, for example in a select where statement, to perform
conditional tests.
select * from employees where salary > 60000.00;

– Use of select to perform subqueries


Subqueries are queries that are embedded within queries using double brackets [[]]. Any valid
query can be embedded within the double brackets.
select name from employees where department in (select department from managers
where department = 'Finance');

– Selection of data into another table


The select into statement retrieves data from one table and inserts it into another. The select into
command does not delete the existing record.
select * into employees_backup from employees;

– Updates to records in tables


Use the update keyword to update an existing record in a table.
update employees set salary = 55000.00 where id = 101;

– Database and table listings


Use the show keyword to list the databases, columns, or tables or the current service.
show databases;
show tables in staff_db;
show columns in employees;

– Deletion of a record from a database table


You can delete a record from a table using the delete command.
delete from contractors where id = 201;

– Deletion of a database or table


You can delete a database or table using the drop command.
drop table contractors;

– The eval statement


The eval statement is used to evaluate the value of a variable or a column within a record, and if
necessary, convert it into another data type.
select eval (salary * 12) as annual_income from employees;

Difference between OODBMS and ORDBMS:


44

OODBMS ORDBMS

It stands for Object Oriented Database It stands for Object Relational Database
Management System. Management System.

Object-oriented databases, like Object An object-relational database is one that is


Oriented Programming, represent data in the based on both the relational and object-
form of objects and classes. oriented database models.

OODBMSs support ODL/OQL. ORDBMS adds object-oriented functionalities


to SQL.

Every object-oriented system has a different Keys, entity integrity, and referential integrity
set of constraints that it can accommodate. are constraints of an object-oriented database.

The efficiency of query processing is low. Processing of queries is quite effective.

FEATURES OF ODBMS:
 Object-oriented data model: ODBMS uses an object-oriented data model to store and
manage data. This allows developers to work with data in a more natural way, as objects
are similar to the objects in the programming language they are using.

 Complex data types: ODBMS supports complex data types such as arrays, lists, sets,
and graphs, allowing developers to store and manage complex data structures in the
database.

 Automatic schema management: ODBMS automatically manages the schema of the


database, as the schema is defined by the classes and objects in the application code. This
eliminates the need for a separate schema definition language and simplifies the
development process.

 High performance: ODBMS can provide high performance, especially for applications
that require complex data access patterns, as objects can be retrieved with a single query.

 Data integrity: ODBMS provides strong data integrity, as the relationships between
objects are maintained by the database. This ensures that data remains consistent and
correct, even in complex applications.

 Concurrency control: ODBMS provides concurrency control mechanisms that ensure


that multiple users can access and modify the same data without conflicts.

 Scalability: ODBMS can scale horizontally by adding more servers to the database
cluster, allowing it to handle large volumes of data.
45

 Support for transactions: ODBMS supports transactions, which ensure that multiple
operations on the database are atomic and consistent.

ADVANTAGES:
 Supports Complex Data Structures
 Improved Performance
 Reduced Development Time
 Supports Rich Data Types
 Scalability

DISADVANTAGES:
 Limited Adoption
 Lack of Standardization
 Cost
 Integration with Other Systems
 Scalability Challenges

*************************

You might also like