Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science...

40
Object-Relational DBMS, b y Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Dr. Awad Khalil Computer Science Department Computer Science Department AUC AUC

Transcript of Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science...

Page 1: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

1

Object-Relational DBMS

Dr. Awad KhalilDr. Awad Khalil

Computer Science DepartmentComputer Science Department

AUCAUC

Page 2: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

2

Content How the relational model has been extended to support advanced database How the relational model has been extended to support advanced database

applicationsapplications The object-oriented features proposed in the next SQL standard, SQL3, The object-oriented features proposed in the next SQL standard, SQL3,

including:including: Row typesRow types User-defined types and user-defined routinesUser-defined types and user-defined routines PolymorphismPolymorphism InheritanceInheritance Reference types and object identityReference types and object identity Collection types (ARRAYs, SETs, LISTs, and MULTISETs)Collection types (ARRAYs, SETs, LISTs, and MULTISETs) Extensions to the SQL to make it computationally completeExtensions to the SQL to make it computationally complete Support for large objects: Binary Large Objects (BLOBs)Support for large objects: Binary Large Objects (BLOBs) RecursionRecursion

Extensions required to relational query processing and query optimization to Extensions required to relational query processing and query optimization to support advanced queriessupport advanced queries

Some object-oriented extensions to OracleSome object-oriented extensions to Oracle How OODBMSs and ORDBMSs compare in terms of data modeling, data How OODBMSs and ORDBMSs compare in terms of data modeling, data

access, and data sharingaccess, and data sharing

Page 3: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

3

Object-Relational Database Systems Relational DBMSs are currently the dominant database technology with estimated sales of Relational DBMSs are currently the dominant database technology with estimated sales of

between US$30 billion and US$50 billion per year (US$100 billion with tools sales included), between US$30 billion and US$50 billion per year (US$100 billion with tools sales included), and growing at a rate of possibly 25% per year.and growing at a rate of possibly 25% per year.

The OODBMSs started in the engineering and design domains, and has also become the The OODBMSs started in the engineering and design domains, and has also become the favored system for financial and telecommunications applications.favored system for financial and telecommunications applications.

Although the OODBMSs market is still small, the OODBMSs continues to find new Although the OODBMSs market is still small, the OODBMSs continues to find new application areas, such as the World Wide Web.application areas, such as the World Wide Web.

An ORDBMS is a hybrid of the RDBMS and the OODBMS.An ORDBMS is a hybrid of the RDBMS and the OODBMS. The advanced database applications make extensive use of many object-oriented features The advanced database applications make extensive use of many object-oriented features

such as a user-extensible type system, encapsulation, inheritance, polymorphism, dynamic such as a user-extensible type system, encapsulation, inheritance, polymorphism, dynamic binding of methods, complex objects including non-first normal form objects, and object binding of methods, complex objects including non-first normal form objects, and object identity.identity.

The most obvious way to implement an ORDBMS is to extend the RDBMS with these object-The most obvious way to implement an ORDBMS is to extend the RDBMS with these object-oriented types of features.oriented types of features.

There is no single extended relational model; rather, there are a variety of these models.There is no single extended relational model; rather, there are a variety of these models. All the models share the same basic relational tables and query language, all incorporate some All the models 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 concept of ‘object’, and some have the ability to store methods (or procedures or triggers) as well as data in the database.well as data in the database.

Oracle, Informix, and IBM – have all extended their systems into ORDBMSs, although the Oracle, Informix, and IBM – have all extended their systems into ORDBMSs, although the functionality provided by each is slightly different.functionality provided by each is slightly different.

The standards activity in this area is based on extensions to the SQL standard. These The standards activity in this area is based on extensions to the SQL standard. These extensions have become part of the new SQL standard, commonly referred to as SQL3.extensions have become part of the new SQL standard, commonly referred to as SQL3.

Page 4: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

4

Stonebraker’s View (1996)

Page 5: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

5

ORDBMS

Advantages Reuse and Sharing: The ability to The ability to

extend DBMS server to perform extend DBMS server to perform standard functionality centrally, standard functionality centrally, rather than have it coded in each rather than have it coded in each application.application.

Preservation of the significant body of knowledge and experience that has gone into that has gone into developing relational applications. An developing relational applications. An ORDBMS could be introduced in an ORDBMS could be introduced in an integrative fashion, as proof-of-integrative fashion, as proof-of-concept projects. The new SQL3 concept projects. The new SQL3 standard is designed to be upwardly standard is designed to be upwardly compatible with the SQL2 standard. compatible with the SQL2 standard.

Disadvantages Complexity and associated increased Complexity and associated increased

cost.cost. Loss of the essential simplicity and Loss of the essential simplicity and

purity of the relational model with these purity of the relational model with these types of extension.types of extension.

Object-oriented purists are not attracted Object-oriented purists are not attracted by these extensions either. They argue by these extensions either. They argue the the terminology of object-relational the the terminology of object-relational systems is revealing. Object systems is revealing. Object applications are simply not as data-applications are simply not as data-centric as relational-based ones. Object-centric as relational-based ones. Object-oriented models and programs deeply oriented models and programs deeply combine relationships and encapsulated combine relationships and encapsulated objects to more closely mirror the “real objects to more closely mirror the “real world”. Objects are not extensions of world”. Objects are not extensions of data, but a completely different concept data, but a completely different concept with far greater power to express ‘real with far greater power to express ‘real world’ relationships and behaviors.world’ relationships and behaviors.

Page 6: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

6

SQL3 ANSI (X3H2) and ISO have added features to the SQL specification to support object-oriented ANSI (X3H2) and ISO have added features to the SQL specification to support object-oriented

data management. The SQL3 standard is extremely large and comprehensive, and is divided into data management. The SQL3 standard is extremely large and comprehensive, and is divided into the following parts:the following parts:

SQL/Framework,SQL/Framework, SQL/Foundation, which includes new data types, user-defined types, rules and triggers, SQL/Foundation, which includes new data types, user-defined types, rules and triggers,

transaction, and stored routines.transaction, and stored routines. SQL/CLI (Call-Level Interface), which specifies the provision of an API interface to the SQL/CLI (Call-Level Interface), which specifies the provision of an API interface to the

database based on Access Group and X/Open’s CLI definitions.database based on Access Group and X/Open’s CLI definitions. SQL/PSM (Persistent Stored Modules), which allows procedures and user-defined functions to 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 be written in a 3GL or in SQL and stored in the database, making SQL computationally complete.complete.

SQL/Binding, which provides dynamic invocation of SQL code embedded in a host language.SQL/Binding, which provides dynamic invocation of SQL code embedded in a host language. SQL/Transactions, to formalize the XA interface for use within SQL.SQL/Transactions, to formalize the XA interface for use within SQL. SQL/Temporal, to deal with historical data, time series data, versions, and other temporal SQL/Temporal, to deal with historical data, time series data, versions, and other temporal

extensions.extensions. SQL/Multimedia, to develop a set of multimedia library specifications that will include SQL/Multimedia, to develop a set of multimedia library specifications that will include

multimedia objects for spatial and full-text objects, still image, and general purpose user-multimedia objects for spatial and full-text objects, still image, and general purpose user-defined types (such as complex numbers, vectors, …), and generalized data types for defined types (such as complex numbers, vectors, …), and generalized data types for coordinates, geometry, and their operations.coordinates, geometry, and their operations.

SQL/Real-Time, to handle real-time concepts, such as the ability to place real-time constraints SQL/Real-Time, to handle real-time concepts, such as the ability to place real-time constraints on data processing requests and to model temporally consistent data.on data processing requests and to model temporally consistent data.

Page 7: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

7

Row Types A row type is a sequence of field name/data type pairs that provide a data type A row type is a sequence of field name/data type pairs that provide a data type

to represent the types of rows in tables, so that complete rows can be stored in 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 variables, passed as arguments to routines, and returned as return values from function calls.function calls.

A row type can also be used to allow a column of a table to contain row values.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.In essence, the row is a table nested within a table. Example:Example:

CREATE TABLE Branch (

branchNo CHAR(40),

address ROW(street VARCHAR(25)

city VARCHAR(15),

postcode ROW(cityidentifier VARCHAR(4),

subpart VARCHAR(4))));

INSERT INTO Branch

VALUES (‘B005’, ROW(’22 Deer Rd’, ‘London’, ROW(‘SW1’,’4EH’)));

Page 8: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

8

User-Defined Types SQL3 allows the definition of user-defined types (UDTs), which may be used SQL3 allows the definition of user-defined types (UDTs), which may be used

in the same way as the predefined types (for example, CHAR, INT, FLOAT).in the same way as the predefined types (for example, CHAR, INT, FLOAT). UDTs are subdivided into two categories: distinct types and structured types.UDTs are subdivided into two categories: distinct types and structured types. The simpler type of UDT in SQL is the The simpler type of UDT in SQL is the distinct type, which allows , which allows

differentiation between the same underlying base types. For example, we could differentiation between the same underlying base types. For example, we could create the following two distinct types:create the following two distinct types:CREATE TYPE OwnerNumberType AS VARCHAR(5) FINAL;CREATE TYPE StaffNumberType AS VARCHAR(5) FINAL;

In its more general case, a UDT definition consists of more attribute In its more general case, a UDT definition consists of more attribute definitions, zero or more definitions, zero or more routine declarations (methods) and (methods) and operator declarations..

In addition, we can also define the equality and ordering relationships for the In addition, we can also define the equality and ordering relationships for the UDT using the UDT using the CREATE ORDERING FOR statement. statement.

The value of an attribute can be accessed using the common dot notation (.). The value of an attribute can be accessed using the common dot notation (.). For example, assuming p is an instance of the UDT PersonType, which has an For 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:attribute fName of type VARCHAR, we can access the fName attribute as:

p.fNamep.fNamep.fName = ‘Tamer’p.fName = ‘Tamer’

Page 9: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

9

User-Defined Types (Cont’d)

Observer and Mutator Functions: For each attribute, an observer (get) and a mutator (set) function are automatically For each attribute, an observer (get) and a mutator (set) function are automatically

defined.defined. The observer function returns the current value of the attribute; the mutator 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.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.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 In this way, attribute values are encapsulated and are accessible to the user only by

invoking these functionsinvoking these functions For example, the observer function for the fName attribute of PersonType would be: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:and the corresponding mutator function to set the value to newValue would be:

FUNCTION fName(p PersonType RESULT, newValue VARCHAR(15))

BEGIN

p.fName = newValue;

RETURN p;

END;

Page 10: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

10

User-Defined Types (Cont’d)

Constructor functions: A (public) constructor function is automatically defined to create new instances of 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 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 zero arguments, and returns a New instance of the type with the attributes set to their default value.their default value.

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

CONSTRUCTOR FUNCTION PersonType (fN VARCHAR(15), IN VARCHAR(15), sx CHAR)

RETURN PersonType

DECLARE :p PersonType;

BEGIN

NEW :p;

SET :p.fName = fN;

SET :p.Iname = IN;

SET :p.sex = sx;

END;

Page 11: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

11

User-Defined Types (Cont’d)

Definition of a new UDT:CREATE TYPE PersonType AS (

dateOfBirth DATE CHECK (dateOfBirth > DATE ‘1900-01-01’),

fName VARCHAR(15),

IName VARCHAR(15),

sex CHAR,

FUNCTION age (p PersonType) RETURNS INTEGER

RETURN /* code to calculate age from dateOfBirth */

END,

FUNCTION age (p PersonType RESULT, DOB DATE)

RETURNS PersonType

RETURN /* set dateOfBirth */

END)

REF IS SYSTEM GENERATED

INSTANTIABLE

NOT FINAL;

Page 12: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

12

User-Defined Routines User-defined routines (UDRs) define methods for manipulating data and are User-defined routines (UDRs) define methods for manipulating data and are

important adjunct to UDTs. An ORDBMS should provide significant important adjunct to UDTs. An ORDBMS should provide significant flexibility in this area, such as allowing UDRs to return complex values that 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 can be further manipulated (such as tables), and support for overloading of function names to simplify application development.function names to simplify application development.

In SQL3, UDRs may be defined as part of a UDT or separately as part of a In SQL3, UDRs may be defined as part of a UDT or separately as part of a schema.schema.

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

An An SQL-invoked procedureSQL-invoked procedure is invoked from an SQL CALL statement with any is invoked from an SQL CALL statement with any number of parameters (IN and/or OUT).number of parameters (IN and/or OUT).

An An SQL-invoked functionSQL-invoked function returns a value; with any number of input parameters returns a value; with any number of input parameters (IN) with one designated as the result parameter (using the RESULT (IN) with one designated as the result parameter (using the RESULT keyword).keyword).

Page 13: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

13

User-Defined Routines (Cont’d) An An external routineexternal routine is defined by specifying an external clause is defined by specifying an external clause

that identifies the corresponding ‘compiled code’ in the operating that identifies the corresponding ‘compiled code’ in the operating system’s file storage. For example, we may wish to use a function system’s file storage. For example, we may wish to use a function that creates a thumbnail image for an object stored in the that creates a thumbnail image for an object stored in the database. The functionality cannot be provided in SQL and so we database. The functionality cannot be provided in SQL and so we have to use a function provided externally, using the following have to use a function provided externally, using the following CREATE FUNCTION statement with an statement with an EXTERNAL clause:clause:

CREATE FUNCTION thumbnail(IN myImage ImageType) RETURNS BOOLEAN

EXTERNAL NAME thumbnail

LANGUAGE C

PARAMETER STYLE SQL

DETERMINISTIC

NO SQL;

Page 14: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

14

Polymorphism Different routines may have the same name, that is, routine names may be 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 overloaded, for example to allow a UDT subtype to redefine a method inherited from a subtype, subject to the following costraints:inherited from a subtype, subject to the following costraints: No two functions in the same schema are allowed to have the same 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 signature, that is, the same number of arguments, the same data types for each each argument, and the same return type.each each argument, and the same return type.

No two procedures in the same schema are allowed to have the same name No two procedures in the same schema are allowed to have the same name and the same number of parameters.and the same number of parameters.

SQL3 uses a generalized object model, so that, the types of all arguments to a SQL3 uses a generalized object model, so that, the types of all arguments to a routine are taken into consideration when determining which routine to invoke, routine are taken into consideration when determining which routine to invoke, in order from left to right.in order from left to right.

Where there is not an exact match between the data type of an argument and Where there is not an exact match between the data type of an argument and the data type of the parameter specified, type precedence lists are used to the data type of the parameter specified, type precedence lists are used to determine the closest match.determine the closest match.

Page 15: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

15

Reference Types and Object Identity Object identity is that aspect of an object which never changes and that distinguishes the object from all Object identity is that aspect of an object which never changes and that distinguishes the object from all

other objects.other objects. Ideally, an object’s identity is independent of its name, structure, and location.Ideally, an object’s identity is independent of its name, structure, and location. The identity of an object persists even after the object has been deleted, so that it may never be confused The identity of an object persists even after the object has been deleted, so that it may never be confused

with the identity of any other object.with the identity of any other object. Other objects can use an object’s identity as a unique way of referencing it.Other objects can use an object’s identity as a unique way of referencing it. In SQL3, In SQL3, reference types can be used to define relationships between row types and uniquely identify a can be used to define relationships between row types and uniquely identify a

row within a table.row within a table. A reference type value can be stored in one table and used as a direct reference to a specific row in some A reference type value can be stored in one 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++).base table that has been defined to be of this type (similar to the notion of a pointer type in ‘C’ or C++). In this respect, a reference type provides a similar functionality as the object identifier (OID) of In this respect, a reference type provides a similar functionality as the object identifier (OID) of

OODBMSs.OODBMSs. Thus, references allow a row to be shared among multiple tables and enables users to replace complex Thus, references allow a row to be shared among multiple tables and enables users to replace complex

join definitions in queries with much simpler path expressions.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 join.References also give the optimizer an alternative way to navigate data instead of using value-based join. REF IS SYSTEM GENERATED in a in a CREATE TYPE statement indicates that the actual values of statement indicates that the actual values of

the associated the associated REF type are provided by the system. type are provided by the system. A base table can be created to be of some structured type. Other columns can be specified for the table A base table can be created to be of some structured type. Other columns can be specified for the table

but at least one column must be specified, namely a column of the associated REF type, using the clause but at least one column must be specified, namely a column of the associated REF type, using the clause REF IS <columnName> <columnName> SYSTEM GENERATED. This column is used to contain unique identifiers for This column is used to contain unique identifiers for the rows of the associated base table. The identifier for a given row is assigned when the row is inserted the rows of the associated base table. The identifier for a given row is assigned when the row is inserted into the table and remains associated with that row until it is deleted. into the table and remains associated with that row until it is deleted.

Page 16: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

16

Subtypes and Supertypes SQL3 allows UDTs to participate in a subtype/supertype hierarchy using the SQL3 allows UDTs to participate in a subtype/supertype hierarchy using the UNDER clause. clause. A type can have more than one subtype but currently only one supertype (that is, multiple A type can have more than one subtype but currently only one supertype (that is, multiple

inheritance is not supported).inheritance is not supported). A subtype inherits all the attributes and behavior of its supertype and it can define additional A subtype inherits all the attributes and behavior of its supertype and it can define additional

attributes and functions like any other UDT and it can override inherited functions.attributes and functions like any other UDT and it can override inherited functions. To create a subtype StaffType of the supertype PersonType we write: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),CREATE FUNCTION isManager (s StaffType) RETURNS BOOLEANBEGIN

IF s.position = ‘Manager’ THENRETURNS TRUE;

ELSERETURNS FALSE;

END)INSTANTIABLENOT FINAL;

Page 17: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

17

Subtypes and Supertypes (Cont’d)

An instance of a subtype is considered an instance of all its supertypes.An instance of a subtype is considered an instance of all its supertypes. SQL3 supports the concept of SQL3 supports the concept of substitutability; that is, whenever an instance of a ; that is, whenever an instance of a

supertype is expected an instance of the subtype can be used in its place.supertype is expected an instance of the subtype can be used in its place. The type of a UDT can be tested using the The type of a UDT can be tested using the TYPE predicate. For example, given a predicate. For example, given a

UDT, Udt1 say, we can apply the following tests:UDT, Udt1 say, we can apply the following tests:TYPE Udt1 IS OF (PersonType)TYPE Udt1 IS OF (PersonType) // Check Udt1 is the PersonType // Check Udt1 is the PersonType

or any of its subtypes or any of its subtypes

TYPE Udt1 IS OF (ONLY PersonType)TYPE Udt1 IS OF (ONLY PersonType) // Check Udt1 is the PersonType// Check Udt1 is the PersonType In SQL3, every instance of a UDT must be associated with exactly In SQL3, every instance of a UDT must be associated with exactly one most one most

specifier typespecifier type, which corresponds to the lowest subtype assigned to the instance., which corresponds to the lowest subtype assigned to the instance. Thus, if the UDT has more than one direct supertype, then there must be a single Thus, if the UDT has more than one direct supertype, then there must be a single

type to which the instance belongs, and that single type must be a subtype of all the type to which the instance belongs, and that single type must be a subtype of all the types to which the instance belongs.types to which the instance belongs.

Page 18: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

18

Creating Tables To maintain upwards compatibility with the SQL2 standard, it is still necessary to use the To maintain upwards compatibility with the SQL2 standard, it is still necessary to use the

CREATE TABLECREATE TABLE statement to create a table, even if the table consists of a single UDT. 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.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, for example, to create a table There are several variations of the CREATE TABLE statement, for example, to create a table

using the StaffType UDT, we could write:using the StaffType UDT, we could write:CREATE TABLE Staff (CREATE TABLE Staff (

infoinfo StaffType,StaffType,PRIMARY KEY (staffNo));PRIMARY KEY (staffNo));

OrOr

CREATE TABLE Staff OF StaffType (CREATE TABLE Staff OF StaffType (REF IS staffID SYSTEM GENERATED,REF IS staffID SYSTEM GENERATED,PRIMARY KEY (staffNo));PRIMARY KEY (staffNo));

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

Page 19: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

19

Creating Tables (Cont’d)Using a reference type to define a relationshipUsing a reference type to define a relationship In this example, we model the relationship between PropertyForRent and Staff using a In this example, we model the relationship between PropertyForRent and Staff using a

reference typereference type

CREATE TABLE PropertyForRent (CREATE TABLE PropertyForRent (

propertyNopropertyNo PropertyNumberPropertyNumber NOT NULL,NOT NULL,

streetstreet StreetStreet NOT NULL,NOT NULL,

citycity CityCity NOT NULL,NOT NULL,

postcodepostcode PostCode,PostCode,

typetype PropertyTypePropertyType NOT NULL DEFAULT ‘F’,NOT NULL DEFAULT ‘F’,

roomsrooms PropertyRoomsPropertyRooms NOT NULL DEFAULT 4,NOT NULL DEFAULT 4,

rentrent PropertyRentPropertyRent NOT NULL DEFAULT 600,NOT NULL DEFAULT 600,

staffIDstaffID REF(StaffType) REF(StaffType) SCOPE StaffSCOPE Staff

REFERENCES ARE CHECKED ON DELETE REFERENCES ARE CHECKED ON DELETE CASCADE,CASCADE,

PRIMARY KEY (propertyNo));PRIMARY KEY (propertyNo));

Page 20: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

20

Creating Tables (Cont’d) SQL3 does not provide a mechanism to store all instances of a given UDT unless the user SQL3 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.explicitly creates a single table in which all instances are stored. Thus, in SQL3 it may not be possible to apply an SQL query to all instances of a given UDT.Thus, in SQL3 it may not be possible to apply an SQL query to all instances of a given UDT. For example, if we created a second table such as:For example, if we created a second table such as:

CREATE TABLE Client (CREATE TABLE Client (info info PersonType,PersonType,prefTypeprefType CHAR,CHAR,maxRentmaxRent DECIMAL(6,2),DECIMAL(6,2),branchNobranchNo VARCHAR(4)VARCHAR(4) NOT NULL);NOT NULL);

Then the instances of PersonType are now distributed over two tables: Staff and Client.Then the instances of PersonType are now distributed over two tables: Staff and Client. This problem can be overcome in this particular case using the table inheritance mechanism, This problem can be overcome in this particular case using the table inheritance mechanism,

which allows a table to be created that inherits all the attributes of an existing table using the which allows a table to be created that inherits all the attributes of an existing table using the UNDER clause.UNDER clause.

The subtable/supertable facility is completely independent from the UDT inheritance facilty.The subtable/supertable facility is completely independent from the UDT inheritance facilty. As would be expected, a subtable inherits every column from its supertable and may also As would be expected, a subtable inherits every column from its supertable and may also

define additional columns of its own.define additional columns of its own.

Page 21: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

21

Creating Tables (Cont’d)Creation of a subtable using the UNDER clauseCreation of a subtable using the UNDER clause We can create a table for Managers using table inheritance:We can create a table for Managers using table inheritance:

CREATE TABLE Manager UNDER Staff (CREATE TABLE Manager UNDER Staff (bonus bonus DECIMAL(5,2),DECIMAL(5,2),mgrStartDatemgrStartDate DATE);DATE);

In this case, Manager contains all the columns of Staff as well as defining its own columns. In this case, Manager contains all the columns of Staff as well as defining its own columns. When we insert rows into the Manager table, the values of the inherited columns are inserted into the Staff When we insert rows into the Manager table, the values of the inherited columns are inserted into the Staff

table. Similarly, when we delete rows from the Manager table, the rows disappear from both the Manager table. Similarly, when we delete rows from the Manager table, the rows disappear from both the Manager and Staff tables. As a result, when we access all rows of Staff, this will also include all Manager details.and Staff tables. As a result, when we access all rows of Staff, this will also include all Manager details.

There are restrictions on the population of a table hierarchy:There are restrictions on the population of a table hierarchy: Each row of the supertable Staff can correspond to at most one row in Manager.Each row of the supertable Staff can correspond to at most one row in Manager. Each row in Manager must have exactly one corresponding row in Staff.Each row in Manager must have exactly one corresponding row in Staff. When a row is inserted into a subtable, then the values of any inherited columns of the table are When a row is inserted into a subtable, then the values of any inherited columns of the table are

inserted into the corresponding supertables, cascading upwards in the table hierarchy.inserted into the corresponding supertables, cascading upwards in the table hierarchy. When a row is updated in a subtable, a similar procedure to the above is carried out to update the When a row is updated in a subtable, a similar procedure to the above is carried out to update the

values of inherited columns in the supertypes.values of inherited columns in the supertypes. When a row is updated in a supertable, then the values of all inherited columns in all corresponding 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. rows of its direct and indirect subtables are also updated accordingly. When a row is deleted in subtable/supertable, the corresponding rows in the table hierarchy are When a row is deleted in subtable/supertable, the corresponding rows in the table hierarchy are

deleted.deleted.

Page 22: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

22

Querying Data SQL3 provides the same syntax as SQL2 for querying and updating tables, with various SQL3 provides the same syntax as SQL2 for querying and updating tables, with various

extensions to handle objects.extensions to handle objects.Retrieve a specific column, specific rows:Retrieve a specific column, specific rows: Find the names of all ManagersFind the names of all Managers

SELECT SELECT s.INames.INameFROM FROM Staff sStaff sWHEREWHERE s.position = ‘Manager’;s.position = ‘Manager’;

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

Invoking a user-defined function:Invoking a user-defined function: Find the names and ages of all ManagersFind the names and ages of all ManagersSELECT SELECT s.IName, s.ages.IName, s.ageFROM FROM Staff sStaff sWHEREWHERE s.isManager;s.isManager;

This alternative method of finding Managers uses the user-defined functionThis alternative method of finding Managers uses the user-defined function isManager isManager as a as a predicate of the WHERE clause. In addition, the query also invokes the inherited virtual predicate of the WHERE clause. In addition, the query also invokes the inherited virtual (observer) function (observer) function ageage as an element of the SELECT list. as an element of the SELECT list.

Page 23: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

23

Querying Data (Cont’d)Use of ONLY to restrict selection:Use of ONLY to restrict selection: Find the names of all people over 65 years of ageFind the names of all people over 65 years of age

SELECT SELECT p.IName, p.fName p.IName, p.fName FROM FROM Person pPerson pWHEREWHERE age > 65;age > 65;

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

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

Use of the dereference operator:Use of the dereference operator: Find the name of staff who manages property ‘PG4’Find the name of staff who manages property ‘PG4’SELECT SELECT p.staffID ->fName AS fName, p.staffID ->lName AS INamep.staffID ->fName AS fName, p.staffID ->lName AS INameFROM FROM PropertyForRent pPropertyForRent pWHEREWHERE p.propertyNo = ‘PG4’;p.propertyNo = ‘PG4’;

References can be used in path expressions that permit traversal of object references to navigate from one row to References can be used in path expressions that permit traversal of object references to navigate from one row to another. To traverse a reference, the dereference operator (another. To traverse a reference, the dereference operator (->->) is used. In the SELECT statement, ) is used. In the SELECT statement, p.staffIDp.staffID is the is the normal way to access a column of a table. In this particular case though, the column is a reference to a row of the normal way to access a column of a table. In this particular case though, the column is a reference to a row of the StaffStaff table, and so we must use the dereference operator to access the columns of the dereferenced table.. table, and so we must use the dereference operator to access the columns of the dereferenced table..

Page 24: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

24

Querying Data (Cont’d) To retrieve the member of staff for property PG4, rather than just the first and last names, we To retrieve the member of staff for property PG4, rather than just the first and last names, we

would use the following query instead:would use the following query instead:

SELECT SELECT DEREF(p.staffID)DEREF(p.staffID)FROM FROM PropertyForRent pPropertyForRent pWHEREWHERE p.propertyNo = ‘PG4’;p.propertyNo = ‘PG4’;

Although reference types are similar to foreign keys, there are significant differences.Although reference types are similar to foreign keys, there are significant differences.

In SQL3, referential integrity is maintained only by using a referential constraint definition In SQL3, 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 specified as part of the table definition. By themselves, reference types do not provide referential integrity.referential integrity.

Thus, the SQL3 reference type should not be confused with that provided in the ODMG Thus, the SQL3 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 object model. In the ODMG model, OIDs are used to model relationships between types and referential integrity is automatically defined.referential integrity is automatically defined.

Page 25: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

25

Collection Types Collections are type constructors that are used to define collections of other 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 result in nested tables Collections are used to store multiple values in a single column of a table and result in nested tables

where a column in one table actually contains another table.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 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.flexibility to the design of the physical database structure. SQL3 introduces a parameterized ARRAY collection type, SQL4 additionally will introduce SQL3 introduces a parameterized ARRAY collection type, SQL4 additionally will introduce

parameterized LIST, SET, and MULTISET collection types. The collection types have the following parameterized LIST, SET, and MULTISET collection types. The collection types have the following meaning:meaning:

ARRAY – one-dimensional array with a maximum number of elements;ARRAY – one-dimensional array with a maximum number of elements; LIST – ordered collection that allows duplicates;LIST – ordered collection that allows duplicates; SET – unordered collection that does not allow duplicates;SET – unordered collection that does not allow duplicates; MULTISET – unordered collection that does allow duplicates.MULTISET – unordered collection that does allow duplicates.

Operations are provided that take:Operations are provided that take: Two SETs as operands, and returns a result of type SET;Two SETs as operands, and returns a result of type SET; Two MULTISETs as operands, and returns a result of type MULTISET;Two MULTISETs as operands, and returns a result of type MULTISET; Two MULTISETs as operands, and returns a result of type MULTISET;Two MULTISETs as operands, and returns a result of type MULTISET; Any collection as operand, and returns the cardinality of the collection;Any collection as operand, and returns the cardinality of the collection; Two LISTs as operands, and returns a result of type LIST;Two LISTs as operands, and returns a result of type LIST; Two LISTs as operands, and returns a result of type INTEGER;Two LISTs as operands, and returns a result of type INTEGER; A LIST and either one or two integers as operands, and returns a result of type LIST;A LIST and either one or two integers as operands, and returns a result of type LIST; An ARRAY and one INTEGER as operands, and returns an element of the ARRAY;An ARRAY and one INTEGER as operands, and returns an element of the ARRAY; Two ARRAYs as operands, and concatenate the two arrays ARRAYs in the order given;Two ARRAYs as operands, and concatenate the two arrays ARRAYs in the order given;

Page 26: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

26

Collection Types (Cont’d)Use of a collection SET:Use of a collection SET: Extend the Staff table to contain the details of a number of 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 Whiye’s next-of-kin.next-of-kin and then find the first and last names of John Whiye’s next-of-kin. Although SQL3 goes not support the SET type, we show this type could be used. Although SQL3 goes not support the SET type, we show this type could be used.

With such a collection type, we could include the definition of a nextOfKin column With such a collection type, we could include the definition of a nextOfKin column in Staff as follows:in Staff as follows:

nextOfKinnextOfKin SET(PersonType)SET(PersonType) The query becomes:The query becomes:

SELECT SELECT n.fName, n.lNamen.fName, n.lName

FROM FROM Staff s, Table(s.nextOfKin) nStaff s, Table(s.nextOfKin) n

WHEREWHERE s.lName = ‘White’ AND s.fName = ‘John’;s.lName = ‘White’ AND s.fName = ‘John’;

Use of COUNT with a collection SET:Use of COUNT with a collection SET: Find how many next of kin each member of Find how many next of kin each member of staff has.staff has.

SELECT SELECT staffNo, fName, lName, COUNT(NEXToFkIN)staffNo, fName, lName, COUNT(NEXToFkIN)

FROM FROM Staff;Staff;

Page 27: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

27

Collection Types (Cont’d)Use of a collection ARRAY:Use of a collection ARRAY: If we had a constraint that restricted the next-of-kin details to a maximum of three, If we had a constraint that restricted the next-of-kin details to a maximum of three,

we could also implement the column as an ARRAY data type:we could also implement the column as an ARRAY data type:

nextOfKinnextOfKin PersonType ARRAY(3)PersonType ARRAY(3) And a restricted form of the previous query that lists the details of the first And a restricted form of the previous query that lists the details of the first

nextOfKin would be:nextOfKin would be:

SELECT SELECT s.nextOfKin[1].fName, s.nextOfKin[1].lNames.nextOfKin[1].fName, s.nextOfKin[1].lName

FROM FROM Staff sStaff s

WHEREWHERE s.lName = ‘White’ AND s.fName = ‘John’;s.lName = ‘White’ AND s.fName = ‘John’;

Note in this case, that an ARRAY cannot be used as a table reference, and we have Note in this case, that an ARRAY cannot be used as a table reference, and we have to use the full form in the SELECT list.to use the full form in the SELECT list.

Page 28: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

28

Persistent Stored Modules A number of new statement types have been added in SQL3 to make the language A number of new statement types have been added in SQL3 to make the language

computationally complete, so that object behavior (methods) can be stored and executed from computationally complete, so that object behavior (methods) can be stored and executed from within the database as SQL statements (ISO, 1999b).within the database as SQL statements (ISO, 1999b).

Statements can be grouped together into a compound statement (block), with its own local Statements can be grouped together into a compound statement (block), with its own local variables.variables.

Some of the additional statements provided in SQL3 are:Some of the additional statements provided in SQL3 are: An assignment statement that allows the result of an SQL value expression to be assigned to a An assignment statement that allows the result of an SQL value expression to be assigned to a

local variable, a column, or an attribute of of a UDT. For example:local variable, a column, or an attribute of of a UDT. For example:DECLARE b BOOLEAN;DECLARE b BOOLEAN;DECLARE staffMember StaffType;DECLARE staffMember StaffType;B = staffMember.isManager;B = staffMember.isManager;

An IF … THEN … ELSE … END statement that allows conditional processing. For An IF … THEN … ELSE … END statement that allows conditional processing. For example:example:

CREATE FUNCTION isManager (s StaffType) RETURNS BOOLEANBEGIN

IF s.position = ‘Manager’ THENRETURNS TRUE;

ELSERETURNS FALSE;

END)INSTANTIABLENOT FINAL;

Page 29: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

29

Persistent Stored Modules (Cont’d) A CASE statement that allows the selection of an execution path based on a set of alternatives. For A CASE statement that allows the selection of an execution path based on a set of alternatives. For

example:example:CASE lowercase(x)CASE lowercase(x)WHEN ‘a’WHEN ‘a’ THEN SET x = 1;THEN SET x = 1;WHEN ‘b’WHEN ‘b’ THEN SET x = 2;THEN SET x = 2;

SET y = 0;SET y = 0;WHEN ‘defaultWHEN ‘default THEN SET x = 3;THEN SET x = 3;END CASE;END CASE;

A set of statements that allows repeated execution of a block of SQL statements. The iterative A set of statements that allows repeated execution of a block of SQL statements. The iterative statements are FOR, WHILE, and REPEAT, examples of which are:statements are FOR, WHILE, and REPEAT, examples of which are:

FOR x, y AS SELECT a, b FROM Tables WHERE searchCondition DO …END FOR;

WHILE b <> TRUE DO …END WHILE;

REPEAT …UNTIL b <> TRUEEND REPEAT;

A CALL statement that allows procedures to be invoked and a RETURN statement that allows an A CALL statement that allows procedures to be invoked and a RETURN statement that allows an SQL value expression to be used as the return value from an SQL function.SQL value expression to be used as the return value from an SQL function.

Page 30: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

30

Triggers

A trigger is an SQL (compound) statement that is executed automatically by the 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 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 routine, in that it is a named SQL block with declarative, executable, and condition-handling sections.condition-handling sections.

However, unlike a routine, a trigger is executed implicitly whenever the However, unlike a routine, a trigger is executed implicitly whenever the triggering eventtriggering event occurs, and a trigger does not have any arguments. occurs, and a trigger does not have any arguments.

The act of executing a trigger is sometimes known as The act of executing a trigger is sometimes known as firing firing the trigger.the trigger. Triggers can be used for a number of purposes include:Triggers can be used for a number of purposes include:

Validating input data and maintaining complex integrity constraints that Validating input data and maintaining complex integrity constraints that otherwise would be difficult, if not impossible, through table constraints;otherwise would be difficult, if not impossible, through table constraints;

Supporting alerts (for example, using electronic mail) that action needs to be Supporting alerts (for example, using electronic mail) that action needs to be taken when a table is updated in some way;taken when a table is updated in some way;

Maintaining audit information, by recording the changes made, and by Maintaining audit information, by recording the changes made, and by whom;whom;

Supporting replication.Supporting replication.

Page 31: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

31

Triggers (Cont’d) The basic format of the CREATE TRIGGER statement is as follows:The basic format of the CREATE TRIGGER statement is as follows:

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

Triggering events include insertion, deletion, and update of rows in a table. In the latter 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.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 or AFTER.A trigger has an associated timing of either BEFORE or AFTER. A BEFORE trigger is fired before the associated event occurs, and an AFTER trigger is A BEFORE trigger is fired before the associated event occurs, and an AFTER trigger is

fired after the associated event occurs.fired after the associated event occurs. The triggered action is an SQL procedure statement, which can be executed in one of two The triggered action is an SQL procedure statement, which can be executed in one of two

ways:ways: For each row affected by the event (FOR EACH ROW). This is called a row-level For each row affected by the event (FOR EACH ROW). This is called a row-level

trigger.trigger. Only once for the entire event (FOR EACH STATEMENT), which is the default. Only once for the entire event (FOR EACH STATEMENT), which is the default.

This is called statement-level trigger.This is called statement-level trigger.

Page 32: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

32

Triggers (Cont’d)

The <oldOrNewValuesAliasList> can refer to:The <oldOrNewValuesAliasList> can refer to: An old or new row (OLD/NEW or OLD ROW/NEW ROW), in the case of An old or new row (OLD/NEW or OLD ROW/NEW ROW), in the case of

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

trigger.trigger. Clearly, old values are not applicable for insert events, and new values are not 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:applicable for delete events. The body of a trigger cannot contain any: SQL transaction statements, such as COMMIT or ROLLBACK;SQL transaction statements, such as COMMIT or ROLLBACK; SQL connection statements, such as CONNECT or DISCONNECT;SQL connection statements, such as CONNECT or DISCONNECT; SQL schema definition or manipulation statements, such as the creation or SQL schema definition or manipulation statements, such as the creation or

deletion of tables, user-defined types, or other triggers;deletion of tables, user-defined types, or other triggers; SQL session statement statements, such as SET SESSION SQL session statement statements, such as SET SESSION

CHARACTERISTICS, SET ROLE, SET TIME ZONE.CHARACTERISTICS, SET ROLE, SET TIME ZONE.

Page 33: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

33

Triggers (Cont’d)

Furthermore, SQL3 does not allow mutating triggers, that is triggers that cause a Furthermore, SQL3 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 change resulting in the same trigger to be invoked again, possibly in an endless loop.loop.

As more than one trigger can be defined on a table, the order of firing of triggers As more than one trigger can be defined on a table, the order of firing of triggers is important. Triggers are fired as the trigger event (INSERT, UPDATE, is important. Triggers are fired as the trigger event (INSERT, UPDATE, DELETE) is executed. The following order is observed:DELETE) is executed. The following order is observed: Execution of any BEFORE statement-level trigger on the tableExecution of any BEFORE statement-level trigger on the table For each row affected by the statement:For each row affected by the statement:

Execute any BEFORE row-level trigger;Execute any BEFORE row-level trigger; Execute the statement itself;Execute the statement itself; Apply referential constraints;Apply referential constraints; Execute any AFTER row-level triggerExecute any AFTER row-level trigger

Execute any AFTER statement-level trigger on the table.Execute any AFTER statement-level trigger on the table.

Page 34: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

34

Triggers - Examples

Use of an AFTER INSERT trigger:Use of an AFTER INSERT trigger: Create a set of mailshot records for each new PropertyForRent row. For the purposes of 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 this example, assume that there is a Mailshot table that records prospective renter details and property details.and property details.

CREATE TRIGGER InsertMailshotTableCREATE TRIGGER InsertMailshotTableAFTER INSERT ON PropertyForRentAFTER INSERT ON PropertyForRentREFERENCING NEW ROW AS pfrREFERENCING NEW ROW AS pfrBEGINBEGIN

INSERT INTO Mailshot VALUESINSERT INTO Mailshot VALUES(SELECT c.fName, c.lName, c.maxRent, pfr.propertyNo,(SELECT c.fName, c.lName, c.maxRent, pfr.propertyNo,

pfr.street, pfr.city, pfr.postcode, pfr.type, pfr.rooms,pfr.street, pfr.city, pfr.postcode, pfr.type, pfr.rooms, pfr.rentpfr.rent FROM Client cFROM Client c WHERE c.branchNo = pfr.branchNo ANDWHERE c.branchNo = pfr.branchNo AND (c.prefType = pfr.type AND c.maxRent <= pfr.rent))(c.prefType = pfr.type AND c.maxRent <= pfr.rent)) END;END;

This trigger is executed after the new row has been inserted. The FOR EACH clause has 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 been omitted, defaulting to FOR EACH STATEMENT, as an INSERT statement only inserts one row at a time. The body of the trigger in an INSERT statement based on a inserts one row at a time. The body of the trigger in an INSERT statement based on a subquery that finds all matching client rows.subquery that finds all matching client rows.

Page 35: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

35

Triggers - Examples

Use of an AFTER UPDATE trigger with condition:Use of an AFTER UPDATE trigger with condition: Create a trigger that modifies all current mailshot records if the rent for a property Create a trigger that modifies all current mailshot records if the rent for a property

changes.changes.CREATE TRIGGER UpdateMailshotTableCREATE TRIGGER UpdateMailshotTable

AFTER UPDATE OF rent ON PropertyForRentAFTER UPDATE OF rent ON PropertyForRent

REFERENCING NEW ROW AS pfrREFERENCING NEW ROW AS pfr

FOR EACH ROWFOR EACH ROW

BEGINBEGIN

DELETE FROM Mailshot WHERE maxRent > pfr.rent;DELETE FROM Mailshot WHERE maxRent > pfr.rent;

UPDATE mailshot SET rent = pfr.rentUPDATE mailshot SET rent = pfr.rent

WHERE propertyNo = pfr.propertyNo;WHERE propertyNo = pfr.propertyNo;

END;END;

This trigger is executed after the rent field of a PropertyForRent row has been updated. This trigger is executed after the rent field of a PropertyForRent row has been updated. The FOR EACH clause is specified, as all property rents may have been increased in one The FOR EACH 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 UPDATE statement. For example due to a cost of living rise. The body of the trigger has two SQL statement: a DELETE statement to delete those mailshot records where the new two SQL statement: 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 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.new rental price in all rows relating to that property.

Page 36: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

36

Triggers – Pros & Cons Triggers can be a very powerful mechanism if used appropriately. The major advantage is 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 that standard functions can be stored within the database and enforced consistently with each update to the database.each update to the database.

This can dramatically reduce the complexity of applications.This can dramatically reduce the complexity of applications. However, there can be some disadvantages:However, there can be some disadvantages:

Complexity: when functionality is moved from the application to the database, the Complexity: when functionality is moved from the application to the database, the database design, implementation, and administration tasks become more complex.database design, implementation, and administration tasks become more complex.

Hidden functionality: Moving functionality to the database and storing it as one or 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. While this can more triggers can have the effect of hiding functionality from the user. While this can simplify things for the user, unfortunately it can also have side effects that may be simplify things for the user, unfortunately it can also have side effects that may be unplanned, and potentially unwanted and erroneous. The user no longer has control unplanned, and potentially unwanted and erroneous. The user no longer has control over what happens to the database.over what happens to the database.

Performance overhead: When the DBMS is about to execute a statement that modify Performance overhead: When the DBMS is about to execute a statement that modify the database, it now has to evaluate the trigger condition to check whether a trigger the database, it now has to evaluate the trigger condition to check whether a trigger should be fired by the statement. This has a performance implication on the DBMS. should be fired by the statement. This has a performance implication on the DBMS. Clearly, as the number of triggers increases, this overhead also increases. At peak Clearly, as the number of triggers increases, this overhead also increases. At peak times, this overhead may create performance problems.times, this overhead may create performance problems.

Page 37: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

37

Large Objects

A large object is a table field that holds a large amount of data, such as a long A large object is a table field that holds a large amount of data, such as a long text file or a graphics file.text file or a graphics file.

There are three different types of large object data types defined in SQL3:There are three different types of large object data types defined in SQL3: Binary Large Object (BLOB), a binary string that does not have a character Binary Large Object (BLOB), a binary string that does not have a character

set or collation association;set or collation association; Character Large Object (CLOB) and National Character Large Object Character Large Object (CLOB) and National Character Large Object

(NCLOB), both character strings.(NCLOB), both character strings. The SQL3 BLOB does allow some operations to be carried out in the DBMS The SQL3 BLOB does allow some operations to be carried out in the DBMS

server. A binary large object (BLOB) string is defined as a sequence of octets. server. A binary large object (BLOB) string is defined as a sequence of octets. The following operators operate on BLOB strings:The following operators operate on BLOB strings: The BLOB concatenation operator;The BLOB concatenation operator; The BLOB substring function;The BLOB substring function; The BLOB overlay function;The BLOB overlay function; The BLOB trim function. The BLOB trim function.

Page 38: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

38

Large Objects - Example

Use of Character and Binary Large ObjectsUse of Character and Binary Large Objects Extend the table Staff to hold a resume and picture for the staff member.Extend the table Staff to hold a resume and picture for the staff member.

ALTER TABLE StaffALTER TABLE Staff

ADD COLUMN resume CLOB(50K);ADD COLUMN resume CLOB(50K);

ALTER TABLE StaffALTER TABLE Staff

ADD COLUMN picture BLOB(12M);ADD COLUMN picture BLOB(12M);

Page 39: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

39

Object-Oriented Extensions in Oracle

Use of Character and Binary Large ObjectsUse of Character and Binary Large Objects Many of the object-oriented features that appear in SQL3 standard appear in Many of the object-oriented features that appear in SQL3 standard appear in

Oracle in one form or another.Oracle in one form or another.

Reference:Reference:

1- FUNDAMENTALS OF DATABASE SYSTEMS. 1- FUNDAMENTALS OF DATABASE SYSTEMS. El MasryEl Masry, Third Edition. , Third Edition. Chapter 13, Oracle 8 Object-Relational features, Pages 448-457Chapter 13, Oracle 8 Object-Relational features, Pages 448-457

2- DATABASE SYSTEMS, A Practical Approach to Design, Implementation, 2- DATABASE SYSTEMS, A Practical Approach to Design, Implementation, and Management. and Management. Thomas ConnaollyThomas Connaolly, Third Edition. Chapter 27, Pages 929-937, Third Edition. Chapter 27, Pages 929-937

Page 40: Object-Relational DBMS, by Dr. Khalil 1 Object-Relational DBMS Dr. Awad Khalil Computer Science Department AUC.

Object-Relational DBMS, by Dr. Khalil

40

Thank you