0% found this document useful (0 votes)
2 views88 pages

Chapter 3

Chapter 3 discusses the Extended Relational Model, focusing on the Object-Relational Database Management Systems (ORDBMSs) that integrate relational and object-oriented features. It covers concepts such as Abstract Data Types (ADT), Object Tables, and collections like VARRAY and Nested Tables, highlighting their definitions, usage, and syntax. The chapter emphasizes the advantages of combining relational robustness with object-oriented capabilities for managing complex data types.

Uploaded by

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

Chapter 3

Chapter 3 discusses the Extended Relational Model, focusing on the Object-Relational Database Management Systems (ORDBMSs) that integrate relational and object-oriented features. It covers concepts such as Abstract Data Types (ADT), Object Tables, and collections like VARRAY and Nested Tables, highlighting their definitions, usage, and syntax. The chapter emphasizes the advantages of combining relational robustness with object-oriented capabilities for managing complex data types.

Uploaded by

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

Chapter 3: Extended Relational

Model
Advanced databases

A. Chikhaoui
Faculty of Computer Science
USTHB
Tabel of Contents

1 Intoduction Collections
2 Abstract Data Types (ADT) 3 Object Identification (OID)
Definition 4 User-Defined Functions (UDFs)
Object table 5 Inheritance
data dictionary views 6 Large Object-LOB
Data Definition Language 7 Views
Data Manipulation Language 8 TRIGGERS
Index 9 Association in SQL3

A. Chikhaoui 2 / 88
Intoduction
Why the Object-Relational Model?

Why the relational model? Why the object model?


Simplicity of concepts and schema Supports complex data types (e.g.,
Good theoretical support multimedia, spatial, etc).
Declarative query language Encapsulation: Data and behavior are
combined in objects
High degree of data independence
Supports inheritance and polymorphism
Optimization of access to the DB
No need for excessive joins to reconstruct
Good performance
hierarchical data.
Management of integrity constraints

Object-Relational Model Combines the best of both worlds!


Keeps the robustness & efficiency of relational databases
Adds rich data types & object-oriented features

A. Chikhaoui Intoduction 4 / 88
Conceptual view of object-relational model

Object-Relational DBMSs (ORDBMSs) keep the relation as the


fundamental building block and SQL as the core DDL/DML, but with
the following OO extensions:
▶ User-Defined Types (UDTs)
▶ User-Defined Functions (UDFs)
▶ Inheritance
▶ Identifiers for tuples

A. Chikhaoui Intoduction 5 / 88
Support from vendors

Several major software companies including IBM, Informix, Microsoft,


Oracle, and Sybase have all released object-relational versions of their
products
Extended SQL standards called SQL-99 or SQL3

A. Chikhaoui Intoduction 6 / 88
Abstract Data Types (ADT)
Data Types

Standard SQL Types: CHAR, VARCHAR, INT, FLOAT, DOUBLE,


DATE, TIME, BOOLEAN, etc.
Abstract Data Types (ADT): called also User-Defined Types
(UDT) define customized data types with specific properties. UDT
replace the concept of classes.

A. Chikhaoui Abstract Data Types (ADT) Definition 8 / 88


ADT I
An ADT is a composite type that groups multiple attributes together.
It can contain methods (functions and procedures).
An ADT can be used to define the type of a table (similar to a class in OO).
Syntax:
CREATE OR REPLACE TYPE TABLE NAME AS OBJECT (
ELEMENT1,
ELEMENT2
....
);
where an element is
▶ an attribute defined with its name and type:
attribute name attribute type
▶ a method: which can be
◦ a member method: operates on the attributes of an instance of the object.
◦ a static method: belongs to the type itself rather than a specific instance.
◦ a constuctor method: defines how an object is initialized.

A. Chikhaoui Abstract Data Types (ADT) Definition 9 / 88


ADT II

Note: We can use CREATE TYPE instead of CREATE OR REPLACE


TYPE
▶ CREATE TYPE is used to define a new type. If the type already exists,
an error occurs.
▶ CREATE OR REPLACE TYPE :
◦ If the type already exists, it replaces the definition.
◦ If the type does not exist, it creates it.

A. Chikhaoui Abstract Data Types (ADT) Definition 10 / 88


Object table I

PERSON
ID NAME SALARY ADDRESS
NUM STREET CITY ZIPCODE

We can create a type for address It is then possible to use this ADT:
CREATE TYPE TADDRESS AS OBJECT ( CREATE TABLE PERSON (
NUM NUMBER, ID NUMBER,
STREET VARCHAR2(50), NAME VARCHAR2(25),
CITY VARCHAR2(25), SALARY NUMBER,
ZIPCODE NUMBER ADDRESS TADRESS
);/ );

Person is not an object table. There is no OID mechanism.

Person is NF2 (Not First Normal Form) table

A. Chikhaoui Abstract Data Types (ADT) Object table 11 / 88


Object table II

To create an object table:


CREATE TABLE TABLE NAME OF GIVEN TYPE;
Example:
CREATE TYPE TADDRESS AS OBJECT (
NUM NUMBER,
STREET VARCHAR2(50),
CITY VARCHAR2(25),
ZIPCODE NUMBER
);/

CREATE TABLE ADDRESSES OF TADDRESS;

ADDRESSES is then a table of objects with management of associated OIDs.

A. Chikhaoui Abstract Data Types (ADT) Object table 12 / 88


Object table III
To define another complex ADT:
CREATE TYPE TADDRESS AS OBJECT (
NUM NUMBER,
STREET VARCHAR2(50),
CITY VARCHAR2(25),
ZIPCODE NUMBER
);/

CREATE TYPE TPERSON AS OBJECT (


ID NUMBER,
NAME VARCHAR2(8),
SALARY NUMBER,
ADDRESS TADDRESS
);/

CREATE TABLE PEOPLE OF TPERSON;

In this example, PEOPLE is an Object Table of Type TPERSON

A. Chikhaoui Abstract Data Types (ADT) Object table 13 / 88


Data Dictionary Views
When we create an ADT, it gets stored in the database’s system
catalog. To retrieve details about it, we can query system views like:
1. USER TYPES → Information about types (names, methods, etc.). Each
row of this view represents an UDT owned by the user.
TYPE NAME TYPE OID ATTRIBUTES METHODS FINAL INSTANTIABLE ...
2. USER TYPE ATTRS → Information about attributes (columns of the
object type). It provides details about the fields inside an UDT owned by
the user.
ATTR NAME ATTR TYPE NAME LENGTH PRECISION scale ...
3. ALL TYPES → Information about types accessible to the user.
4. ALL TYPE ATTRS → Information about attributes of types accessible
to the user.
5. ...
Note: If a user is not the owner of a ADT, he must have the following
permission to use it:
GRANT EXECUTE ON ADT NAME TO USER NAME

A. Chikhaoui Abstract Data Types (ADT) data dictionary views 14 / 88


Table types

In the extended relational model, we distinguish three types of data


tables:
▶ Relational table: a classic table that contains simple data (without
ADT).
▶ NF2 Table: A NF2 (Not First Normal Form) table containing complex
attributes.
▶ Object table: is a table created from OBJECT type.

A. Chikhaoui Abstract Data Types (ADT) Data Definition Language 15 / 88


ALTER TYPE
A type cannot be dropped or re-created if it is being used by a table.
The ALTER TYPE statement allows to change a type without dropping it
making modifications like adding new attributes or new methods, deleting
attributes or methods, or modifying attributes or methods.
When a type is used in other objects (e.g., other types, tables, or collections),
the CASCADE option propagates the changes automatically.
Example:
CREATE OR REPLACE TYPE TPERSON AS OBJECT ( ID NUMBER,
PNAME VARCHAR2(100)
);
/
CREATE TABLE PEOPLE OF TPERSON;
DROP TYPE TPERSON; Error: Type is used by the ”PEOPLE” table
ALTER TYPE Person ADD ATTRIBUTE (BIRTHDATE DATE) CASCADE;

CASCADE ensures that all dependent tables (like PEOPLE) automatically


inherit the new BIRTHDATE attribute.

A. Chikhaoui Abstract Data Types (ADT) Data Definition Language 16 / 88


Insert I

Similar to classes, a constructor with the same name as the ADT is


automatically provided.
In a table that includes an ADT, a constructor is used to create
instances of the defined subtype.
Example:
INSERT INTO PEOPLE VALUES (10, ’Ahmed Yacine’,
TADDRESS(10, ’STREET AHMED KATIB’,’ALGIERS’,16140)
);

A. Chikhaoui Abstract Data Types (ADT) Data Manipulation Language 17 / 88


Insert II

In a table associated with an ADT, the use of a constructor function is


not always mandatory. It depends on the structure of the table.
1. Inserting Data into a Table Without an ADT:
INSERT INTO ADDRESSES VALUES (10, ’STREET AHMED KATIB’,’ALGIERS’,16140);

2. Inserting into a Table That Uses an ADT:


INSERT INTO PEOPLE VALUES (
TPERSON(10, ’Ahmed’, TADDRESS(10, ‘STREET AHMED KATIB’, ’ALGIERS’, 16140)
);

OR
INSERT INTO PEOPLE VALUES (
(10, ’Ahmed’, TADDRESS(10, ‘STREET AHMED KATIB’, ’ALGIERS’, 16140)
);

If the TPERSON constructor is not required, the TADDRESS


constructor is mandatory.

A. Chikhaoui Abstract Data Types (ADT) Data Manipulation Language 18 / 88


Insert III

Note: If the ADT belongs to another user, you must prefix it with the
owner’s name when using the constructor.
Example:
INSERT INTO PEOPLE VALUES (
(10, ’Ahmed’, OTHER USER.TADDRESS(10, ‘STREET AHMED KATIB’, ’ALGIERS’, 16140)
);

A. Chikhaoui Abstract Data Types (ADT) Data Manipulation Language 19 / 88


Select

Basic syntax:
SELECT column1, column2, ...
FROM table name
WHERE condition;

Example: SELECT * FROM PEOPLE;


However, the next syntax is false:
SELECT NAME, CITY FROM PEOPLE;

To access the value of the city, the attributes of the ADT must be
specified using their full path with dot notation.
We use a correlation variable to access the attributes of the ADTs.
Examples:
SELECT NAME, P.ADDRESS.CITY FROM PEOPLE P;

A. Chikhaoui Abstract Data Types (ADT) Data Manipulation Language 20 / 88


Update & Delete

UPDATE PEOPLE P
SET P.ADDRESS.CITY = ’ALGIERS’
WHERE P.ADDRESS.ZIPCODE LIKE ’16%’;

The same syntax applies to deletions.


When an object table in Oracle is based on a non-nested ADT, the
UPDATE and DELETE statements follow the same syntax as they do
for regular relational tables.

A. Chikhaoui Abstract Data Types (ADT) Data Manipulation Language 21 / 88


Index

An index is a database object that improves the performance of queries


by allowing faster data retrieval. It works like an index in a book,
helping to locate rows more efficiently without scanning the entire table.
There are many types of indexes. B-tree Index is the default index in
oracle.
It is possible to create indexes on attributes belonging to an ADT. The
full path must always be specified. There is no need for a correlation
variable.
CREATE INDEX IND CITY PEOPLE
ON PEOPLE(ADRESS.CITY);

A. Chikhaoui Abstract Data Types (ADT) Index 22 / 88


Collections

Collections allow to create multi-valued attributes of the same data type.


Multiple categories:
1. VARRAY
2. NESTED TABLE
A collection can contain:
▶ Elementary data types.
▶ Abstract data types.
▶ References to abstract data types.
▶ Collections (VARRAY or NESTED TABLE).

A. Chikhaoui Abstract Data Types (ADT) Collections 23 / 88


VARRAY I

VARRAY: (Variable-Size Array) is a collection with a fixed maximum


size but can store a variable number of elements up to that limit.
▶ Fixed-size limit: must be defined during declaration.
▶ Dense: no gaps in elements; all indexes are contiguous.
▶ Stored as a single unit inside the database: better for small
collections.
▶ Elements retain their order: first element inserted is at index 1.
Syntax:
CREATE OR REPLACE TYPE TTABVAR AS
VARRAY(NB MAX ELTS) OF TYPE ELT;
/

Example
CREATE OR REPLACE TYPE TLIST FNAMES AS
VARRAY(4) OF VARCHAR2(15);
/

A. Chikhaoui Abstract Data Types (ADT) Collections 24 / 88


VARRAY II

Collections can be used to build complex types.


CREATE OR REPLACE TYPE TPERSON AS OBJECT (
FNAME TLIST FNAMES,
LNAME VARCHAR2(15),
DATE BIRTH DATE,
ADRESS TADRESS
);/

CREATE TABLE PEOPLE OF TPERSON;

A. Chikhaoui Abstract Data Types (ADT) Collections 25 / 88


VARRAY III

a VARRAY is stored as a single unit inside a table column. It means the


VARRAY is kept inside the same row as a single value.
INSERT INTO PEOPLE VALUES
(’ADLI’, TLIST FNAMES(’AHMED’,’AKRAM’,’FADI’),
’18-03-1997’, TADRESS(’10’, ‘STREET AHMED KATIB’,’ALGIERS’, 16140)));

When executing the query:


SELECT LNAME, FNAMES FROM PEOPLE;

the VARRAY will be returned as a single unit:


lname fnames (VARRAY)
ADLI (’AHMED’, ’AKRAM’, ’FADI’)

A. Chikhaoui Abstract Data Types (ADT) Collections 26 / 88


VARRAY IV

To access the contents of the VARRAY, we can:


▶ use the following query: SELECT * FROM PEOPLE;
▶ use a PL/SQL program with COUNT and and index-based access to
access the ith element of the VARRAY.
PL/SQL (Procedural Language/Structured Query Language)
is Oracle’s procedural extension of SQL, allowing to write pro-
grams with loops, conditions, variables, and exception handling
inside the database. It combines SQL (for data manipulation)
with procedural features (like in traditional programming lan-
guages).
▶ use the TABLE() clause to extract elements. TABLE() allows us to
flatten a VARRAY into rows, making it easy to query individual elements.

A. Chikhaoui Abstract Data Types (ADT) Collections 27 / 88


VARRAY V

▶ Example:
SELECT NOM, Q.*
FROM PEOPLE P, TABLE (P.FNAMES) Q;

The system expands the VARRAY into multiple rows, displaying each
element of the VARRAY separately.
LNAME COLUMN VALUE
ADLI AHMED
ADLI AKRAM
ADLI FADI

A. Chikhaoui Abstract Data Types (ADT) Collections 28 / 88


NESTED TABLE I

NESTED TABLE: is a collection type similar to a table but stored as a


separate table in the database. It can be unbounded and can have gaps
(sparse).
▶ Unbounded: can grow dynamically.
▶ Initially dense, but can become sparse: i.e., elements can be deleted,
leaving gaps.

A. Chikhaoui Abstract Data Types (ADT) Collections 29 / 88


NESTED TABLE II

To define a nested table, we follow these three steps:


1. Create an ADT Representing a Row of the Nested Table;
2. Create an ADT Representing the Nested Table;
3. Define a Table Using an Attribute of the Nested Table Type;

A. Chikhaoui Abstract Data Types (ADT) Collections 30 / 88


NESTED TABLE III

Example: nested table (logical view)


DEPARTEMENT
Numdpt Budget PROJECTS
NUMP TITLE DURATION
D1 40500 n1 A1 2
n2 A2 2
D2 50600 n3 A3 3
n4 A4 2

A. Chikhaoui Abstract Data Types (ADT) Collections 31 / 88


NESTED TABLE IV
Steps to create the previous table:
1. Step 1:
CREATE TYPE TPROJECT AS OBJECT
(NUMP VARCHAR2(50),
TITLE VARCHAR2(25),
DURATION NUMBER);/

2. Step 2:
CREATE TYPE NT PROJECTS AS TABLE OF TPROJECT; /

3. Step 3:
CREATE TABLE DEPARTEMENT (
NUMDP VARCHAR2(25) PRIMARY KEY,
BUDGET NUMBER,
PROJECTS NT PROJECTS
)
NESTED TABLE PROJECTS STORE AS TABLE PROJECTS ;

Note: the clause NESTED tells that the column PROJECTS (which is a NT PROJECTS
nested table) should store its data in a separate physical table called TABLE PROJETS.
The column PROJECTS in DEPARTEMENT is not stored as a single field. Instead, its data
is stores in a separate table (TABLE PROJECTS), which is linked to DEPARTEMENT using
pointers.
A. Chikhaoui Abstract Data Types (ADT) Collections 32 / 88
NESTED TABLE V
DEPARTMENT
Numdpt Budget PROJECTS
D1 40500 id1
D2 50600 id2

NUMP TITLE DURATION


id1 n1 A1 2
id1 n2 A2 2
id2 n3 A3 3
id2 n4 A4 2

TABLE PROJECTS: Store of the nested table PROJECTS.

A. Chikhaoui Abstract Data Types (ADT) Collections 33 / 88


NESTED TABLE VI

Example 2: Nested table Address


CREATE TYPE TADDRESS AS OBJECT (
NUM NUMBER,
STREET VARCHAR2(50),
CITY VARCHAR2(25),
ZIPCODE NUMBER);
/

CREATE TYPE NT ADDRESS AS TABLE OF TADDRESS;


/

CREATE TABLE PEOPLE


(
NOMP VARCHAR2(25),
ADDRESSES NT ADDRESS
)
NESTED TABLE ADDRESSES STORE AS TABLE ADDRESSES;

Note: A Nested Table is not an object table; it does not associate an OID reference with a
collection item.

A. Chikhaoui Abstract Data Types (ADT) Collections 34 / 88


NESTED TABLE: Insertion I

Tuples can be inserted into a nested table using Constructors.


Example:
INSERT INTO PEOPLE VALUES
(‘Ahmed’,
NT ADDRESS(
TADDRESS(10, ’STREET AHMED KATIB’,’ALGIERS’, 16140),
TADDRESS(12, ’BORDJ EL KIFFAN’,’ALGIERS’, 16130)
)
);

A. Chikhaoui Abstract Data Types (ADT) Collections 35 / 88


NESTED TABLE: Insertion II
It is also possible to insert new values into the nested table using the TABLE()
function.
The TABLE() function allows to directly manipulate nested tables as if they
were regular tables. This is useful for inserting, updating, or deleting specific
elements inside a nested table without modifying the entire row.
Example:
INSERT INTO TABLE (SELECT ADDRESSES FROM PEOPLE WHERE PNAME = ’Ahmed’)
VALUES (
TADDRESS(25, ’1st of May Square’, ’ALGIERS’, 16450)
);
▶ SELECT ADDRESSES FROM PEOPLE WHERE PNAME = ’Ahmed’
→ Retrieves the nested table ADRESSES for the person named ’Ahmed’.
▶ TABLE(...)
→ Converts the nested table into a queryable table format in order to allow direct
INSERT INTO operations on the nested table.
▶ VALUES (...)
→ Inserts a new row into the nested table without affecting other data of other
attributes.

A. Chikhaoui Abstract Data Types (ADT) Collections 36 / 88


NESTED TABLE: Insertion III

To perform group inserts (e.g. two people with the same addresses), CAST
and MULTISET are used.
▶ MULTISET(...): Creates a set (collection) of rows from a SELECT query.
▶ CAST(... AS TYPE): Converts the result into the correct nested table type.

Example:
INSERT INTO PEOPLE VALUES (
’Anes’,
CAST( MULTISET(
SELECT *
FROM TABLE (
SELECT ADDRESSES FROM PEOPLE WHERE PNAME = ’Ahmed’
)
) AS NT ADDRESS
)
);

This query:
▶ inserts a new person (Anes).
▶ copies all addresses from Ahmed and assigns them to Anes.

A. Chikhaoui Abstract Data Types (ADT) Collections 37 / 88


NESTED TABLE: Update & Deletion

UPDATE TABLE can also be used to modify and delete tuples in the
nested table.
Example:
UPDATE TABLE
(SELECT ADDRESSES FROM PEOPLE WHERE PNAME = ’Ahmed’) adr
SET adr.CITY = ’ORAN’
WHERE adr.CITY = ’ALGIERS’;

Deleting an entire collection is possible


Example:
UPDATE PEOPLE SET ADDRESSES = NULL WHERE PNAME = ’Ahmed’;

A. Chikhaoui Abstract Data Types (ADT) Collections 38 / 88


NESTED TABLE: Select

Querying a nested table is possible using TABLE()


Example:
SELECT nt.CITY
FROM PEOPLE P, TABLE (P.ADDRESSES) nt
WHERE PNAME=’Ahmed’
AND nt.STREET LIKE ’% AHMED K%’;

A. Chikhaoui Abstract Data Types (ADT) Collections 39 / 88


Varray VS Nested table

Feature VARRAY Nested Table


Size Fixed upper limit Unlimited size
Storage Stored as a single value in- Stored as a separate table
side a column
Modification Difficult: Using PL/SQL Can update/insert/delete
individual elements
Ordering Preserves order of elements No guaranteed order
When to Use? Fixed number of elements Varying number of ele-
ments

A. Chikhaoui Abstract Data Types (ADT) Collections 40 / 88


Object Identification (OID)
OID

In an object table, each tuple has an object identifier (OID).


OID is unique, independent of value and immutable
The OID is assigned by the system, it allows:
▶ to uniquely identify this tuple,
▶ to reference this object explicitly.
Reference: Pointer to an instance of an object table.
Recall: An object table is created as being associated with a UDT.
▶ CREATE TABLE PEOPLE OF TPERSON;
▶ CREATE TABLE ADDRESSES OF TADDRESS;

A. Chikhaoui Object Identification (OID) 42 / 88


Ref

The REF function allows to access the OID of the objects concerned.
REF(object) → the OID of the object
Example:
SELECT REF(P)
FROM PEOPLE P
WHERE P.NAME=’Ahmed’;

Note: REF only works on object tables, not on columns containing


structured types.

A. Chikhaoui Object Identification (OID) 43 / 88


Explicit referencing
We specify for the attribute type that it points to an object whose
structure is the ADT specified in an object table.
Syntax: ATTRIBUTE NAME REF OBJECT TYPE;
Example:
CREATE TYPE TCAR AS OBJECT
(MODEL VARCHAR2(15),
REGISTRATION VARCHAR2(10)
);
/
CREATE TABLE CAR OF TCAR;

CREATE OR REPLACE TYPE TPERSON AS OBJECT


(FNAME TLIST FNAME,
LNAME VARCHAR2(15),
CAR REF TCAR
);
/
CREATE TABLE PEOPLE OF TPERSON;

A. Chikhaoui Object Identification (OID) 44 / 88


Relational Model VS Object Relational Model I

Relational Model
PERSON
NUMP ADDRESS SALARY NUMCAR NUMPROJECT

CAR
NUMCAR MODEL BRAND

PROJECT
NUMPROJECT AMOUNT DURATION

A. Chikhaoui Object Identification (OID) 45 / 88


Relational Model VS Object Relational Model II

Object Relational Model


EMPLOYEES
NUMP SALARY @CAR ADDRESS @PROJECT
STREET CITY Country

CAR
NUMCAR MODEL BRAND

PROJECT
NUMPROJECT AMOUNT DURATION

A. Chikhaoui Object Identification (OID) 46 / 88


Relational Model VS Object Relational Model III

CREATE TYPE TADDRESS AS OBJECT CREATE TYPE TPROJECT AS OBJECT


(NUM NUMBER, (NUMP VARCHAR2(50),
STREET VARCHAR2(50), AMOUNT NUMBER,
CITY VARCHAR2(25), DURATION NUMBER
ZIPCODE NUMBER );
); /
/ CREATE TABLE PROJECTS OF TPROJECT;

CREATE TYPE TCAR AS OBJECT CREATE TYPE TEMPLOYEE AS OBJECT


(NUMCAR VARCHAR2(8), (NUMP VARCHAR2 (5),
MODEL VARCHAR2(7), SALARY NUMBER,
BRAND VARCHAR2(15) CAR REF TCAR,
); ADDRESSE TADDRESS
/ PROJECT REF TPROJECT)
CREATE TABLE CARS of TCAR; CREATE TABLE EMPLOYEES OF TEMPLOYEE

A. Chikhaoui Object Identification (OID) 47 / 88


Insert

The insertion is performed using the REF function, which returns the
OID of a specified tuple (object).
Example:
INSERT INTO PEOPLE VALUES
(’ARKAM’, TLIST FNAME(’AHMED’,’FADI’),
(SELECT REF(C) FROM CARS C WHERE C.NUMCAR = ’1234567890’ ));

A. Chikhaoui Object Identification (OID) 48 / 88


DEREF

The DEREF function is the inverse of REF and is used to access the
associated object from an OID.
Example:
SELECT P.FNAME, P.LNAME, P.BIRTH DATE, DEREF(P.CAR)
FROM PEOPLE P
WHERE P.LNAME = ’YACINE’;
Output
FNAME LNAME BIRTH DATE @ CAR
FNAME type
Ahmed
Akram Yacine 16-05-1963 TCAR(12584, FIAT, 2025)
Anes

A. Chikhaoui Object Identification (OID) 49 / 88


Invalid references

When the referenced object is deleted, the reference becomes invalid.


This is called a DANGLING REF.
IS DANGLING is a function used to check whether a reference (REF)
is invalid.
Example:
UPDATE PEOPLE
SET CAR = NULL
WHERE CAR IS DANGLING;

A. Chikhaoui Object Identification (OID) 50 / 88


SCOPE

The SCOPE IS clause restricts a REF column to reference only rows


from a specific table.
Example:
CAR REF TCAR SCOPE IS TABLECAR
This expression indicates that CAR will reference a row in TABLECAR
and not a row in another table created from the TCAR type.

A. Chikhaoui Object Identification (OID) 51 / 88


Forward Type (Incomplete Type) I

When we have two interdependent ADTs, such as:


▶ TCar which uses TPerson
▶ TPerson which uses TCar
It becomes impossible to fully define one type before the other exists.
To solve this, we can define an incomplete type (also called a
forward-declared type). This means we first declare the type without
attributes or methods, and then we complete it later.
Syntax: CREATE [OR REPLACE] TYPE ADT NAME;

A. Chikhaoui Object Identification (OID) 52 / 88


Forward Type (Incomplete Type) II
Example:
We first declare TPerson without defining its attributes:
CREATE TYPE TPerson;/ -- Forward declaration

Now we can create TCar, which references TPerson:


CREATE TYPE TCar AS OBJECT (
model VARCHAR2(50),
year NUMBER,
owner REF TPerson -- Reference to TPerson (Owner)
);
/

Now that TCar exists, we can fully define TPerson, which contains a
REF to TCar (the car the person owns).
CREATE TYPE TPerson AS OBJECT (
name VARCHAR2(50),
age NUMBER,
car REF TCar -- Reference to TCar (Owned car)
);
/

A. Chikhaoui Object Identification (OID) 53 / 88


Value function
The VALUE function works with object tables and object views. It
takes a table alias as a parameter.
It returns an instance of the object type that the table or view is based
on instead of returning individual columns.
Example:
CREATE TYPE TCAR AS OBJECT ( SELECT VALUE(p)
NUMCAR NUMBER, FROM People p;
MODEL VARCHAR2(50),
BRAND VARCHAR2(50)
Output:
); /
TPerson(101, ’Ahlem Kamel’, REF(TCar))
CREATE TABLE TableCar OF TCAR;
TPerson(102, ’Sami Ibrahim’, REF(TCar))
CREATE TYPE TPerson AS OBJECT (
name VARCHAR2(50),
age NUMBER,
car REF TCAR
);/
/
CREATE TABLE People OF TPerson;

A. Chikhaoui Object Identification (OID) 54 / 88


User-Defined Functions (UDFs)
User-Defined Functions (UDFs) I

Every RDBMS includes a collection of built-in functions, such as MIN(),


MAX(), and AVG().
User-Defined Functions (UDFs) enable users to expand this
functionality by creating custom functions.
In addition to the default CONSTRUCTOR: constructor having all the
fields of the type as parameter, the user can define his own constructors.
A method is defined in an object type specification and implemented
in the object type body.
The keyword MEMBER precedes each instance method
The keyword STATIC precedes each class method.
UDFs can be overloaded: multiple functions can have the same name
but different parameter lists (types or number of arguments).

A. Chikhaoui User-Defined Functions (UDFs) 56 / 88


User-Defined Functions (UDFs) II

Every UDF consists of:


▶ name
▶ Parameters: Specifies input data (IN), output results (OUT), both input
and output (IN OUT).
by default a parameter in a method is an IN parameter.
▶ Exception Handling: Defines how errors and exceptions are managed.
▶ Method Type Indicators (for object types): Specifies whether the
method is a MAP MEMBER, ORDER MEMBER, MEMBER, or STATIC.
by default a method in an object type is a MEMBER method.
▶ Implementation: The actual method logic, written inside the object type
body. The code may contain:
◦ PL/SQL statements (loops, conditions, exception handling).
◦ SQL statements (SELECT, UPDATE, etc.).
◦ method calls (calling another method)

A. Chikhaoui User-Defined Functions (UDFs) 57 / 88


User-Defined Functions (UDFs) III
MAP MEMBER: is used in object types to define a sorting order. It is
used to map an object instance to a scalar value.
CREATE OR REPLACE TYPE Person AS OBJECT (
id NUMBER,
name VARCHAR2(100),
birth date DATE,
MAP MEMBER FUNCTION age RETURN NUMBER
);
/

we can compare Person objects using ORDER BY on age function


ORDER MEMBER: Compares two objects of the same type. It returns
an integer:
▶ -1 → If the first object is less than the second.
▶ 0 → If the objects are equal.
▶ 1 → If the first object is greater than the second.
CREATE OR REPLACE TYPE Person AS OBJECT (
id NUMBER,
name VARCHAR2(100),
birth date DATE,
ORDER MEMBER FUNCTION compare(p Person) RETURN INTEGER
);
/

A. Chikhaoui User-Defined Functions (UDFs) 58 / 88


Declaration

Methods are declared when creating TADs.


Syntax:
CREATE OR REPLACE TYPE TYPE NAME AS OBJECT (
ATT1 TYPE1,
ATT2 TYPE2,
...
MEMBER FUNCTION|PROCEDURE METHOD1 SIGNATURE,
STATIC FUNCTION|PROCEDURE METHOD2 SIGNATURE,
....
);
/

A. Chikhaoui User-Defined Functions (UDFs) 59 / 88


Implementation

The body of the methods is defined by:


CREATE OR REPLACE TYPE BODY TYPE NAME AS
MEMBER METHOD NAME IS
BEGIN
...
END ;
...
END;
/

A. Chikhaoui User-Defined Functions (UDFs) 60 / 88


Example

CREATE OR REPLACE TYPE PERSON AS OBJECT (


PNAME VARCHAR2(25),
DATE BIRTH DATE,
MEMBER FUNCTION AGE RETURN NUMBER
);
/

CREATE OR REPLACE TYPE BODY PERSON AS


MEMBER FUNCTION AGE RETURN NUMBER IS
BEGIN
RETURN ROUND((SYSDATE - SELF.DATE BIRTH) / 365);
END;
END;
/

A. Chikhaoui User-Defined Functions (UDFs) 61 / 88


Invocation

Methods are invoked using dot notation, just like attributes.


Example:
SELECT P.PNAME, P.AGE()
FROM PERSON P;

A. Chikhaoui User-Defined Functions (UDFs) 62 / 88


Overloading

Method names can be overloaded, meaning that multiple methods can


share the same name as long as they have different parameter lists.
Oracle automatically determines which method to execute based on the
provided arguments.
Example:
CREATE OR REPLACE TYPE PERSON AS OBJECT (
PNAME VARCHAR2(25),
DATE BIRTH DATE,
MEMBER FUNCTION age RETURN NUMBER,
MEMBER FUNCTION age(on date DATE) RETURN NUMBER
);
/

A. Chikhaoui User-Defined Functions (UDFs) 63 / 88


Inheritance
Inheritance I
Inheritance allows to specialize a type via the NOT FINAL clause.
Note: By default, an object type is final, meaning it cannot be
inherited. To allow inheritance, we must explicitly declare it as NOT
FINAL
It is possible to create subtypes via the UNDER clause:
1.Declaring a Superclass (Base Type)

CREATE OR REPLACE TYPE TYPE NAME AS OBJECT (


...
Or: ALTER TYPE TYPE NAME NOT FINAL ;
) NOT FINAL;
/

2. Declaring a Subclass (UNDER)

CREATE TYPE SUB TYPE UNDER TYPE NAME (


– Additional attributes
SPECIALIZED ATTRIBUTE 1 TYPE,
SPECIALIZED ATTRIBUTE 2 TYPE
...
);
/

A. Chikhaoui Inheritance 65 / 88
Inheritance II

Subtypes inherit all attributes and methods from their supertype.


Methods can be overloaded (same name, different parameters).
Methods can also be overridden in subtypes.

A. Chikhaoui Inheritance 66 / 88
Not instantiable type

In the case of generalization, it is possible to declare a type as NOT


INSTANTIABLE.
Example:
CREATE TYPE PERSON AS OBJECT (
PNAME VARCHAR2(50),
DATE BIRTH DATE
) NOT INSTANTIABLE NOT FINAL;
/
This means:
▶ PERSON cannot be instantiated directly.
▶ Subtypes can still be created from PERSON.

A. Chikhaoui Inheritance 67 / 88
Table Storage for Supertypes and Subtypes I I

When a table is created for a supertype, it can store both supertypes


and subtypes.
This means a subtype instance can be inserted into the supertype’s
table.
For example, if we consider the type PERSON and the subtype
STUDENT, we can insert students into PERSON.

A. Chikhaoui Inheritance 68 / 88
Table Storage for Supertypes and Subtypes I
II

TREAT is used to cast a row to a specific subtype. This allows us to


access subtype-specific attributes.
Example:
CREATE TYPE PERSON AS OBJECT (
pname VARCHAR2(50), CREATE TYPE STUDENT UNDER PERSON (
date birth DATE student id NUMBER
) NOT FINAL; );
/ /
CREATE TABLE person table OF PERSON;

SELECT TREAT(VALUE(p) AS STUDENT).student id


FROM person table p
WHERE TREAT(VALUE(p) AS STUDENT) IS NOT NULL;

A. Chikhaoui Inheritance 69 / 88
Large Object-LOB
Large Object-LOB

A Large Object (LOB) is a data type that can store large amounts of
data, such as:
▶ Text files (e.g., books, articles, documents)
▶ Images (e.g., PNG, JPEG)
▶ Videos
▶ Audio files
SQL3 defines three main types of LOBs:
LOBs are useful when dealing with multimedia data or large text storage
in databases.

A. Chikhaoui Large Object-LOB 71 / 88


LOB Types
SQL3 defines three main types of LOBs:
1. Binary Large Object (BLOB)
◦ Stores binary data (e.g., images, videos, audio files).
◦ Does not have a character set.
◦ Example usage: storing images in a database.
2. Character Large Object (CLOB)
◦ Stores large text data (e.g., books, logs, articles).
◦ Uses a character set (e.g., UTF-8, ASCII).
◦ Example usage: storing large text documents.
3. National Character Large Object (NCLOB)
◦ Stores large text data with support for multiple languages.
◦ Uses a national character set (e.g., Unicode).
◦ Example usage: storing multilingual text.
4. Example:
ALTER TABLE Staff
ADD COLUMN summary CLOB(50K);
ALTER TABLE Staff
ADD COLUMN photo BLOB(12M)

A. Chikhaoui Large Object-LOB 72 / 88


Views
Object Views

Object Views in Oracle are used to apply an object-oriented structure on


top of relational tables without changing the underlying physical storage.
This principle is very interesting since it allows to coexist: An old
relational database with a new object database, or to keep the acquired
relational while showing an object database to the user.

A. Chikhaoui Views 74 / 88
Steps for creating object views I

To create such an object view, we will proceed according to the


following steps:
1. Relational model:
CREATE TABLE PERSON (
NUM NUMBER CONSTRAINT PK PERSON PRIMARY KEY,
FIRST NAME VARCHAR2(25),
LAST NAME VARCHAR2(25)
);

CREATE TABLE LIVE (NUM ...);

A. Chikhaoui Views 75 / 88
Steps for creating object views II
2. Creating abstract data types:
CREATE TYPE TADDRESS AS OBJECT (
STREET VARCHAR2(50),
CITY VARCHAR(25),
ZIPCODE NUMBER );
/

CREATE TYPE TLIST ADDRESSES AS VARRAY(10) OF TADDRESS;


/

CREATE TYPE TPERSON AS OBJECT(


NUM NUMBER,
FIRSTNAME VARCHAR2(25),
LASTNAME VARCHAR2(25),
ADDRESSES TLIST ADDRESSES
);
/

A. Chikhaoui Views 76 / 88
Steps for creating object views III

3. Creating the object view:


CREATE VIEW VPERSON OF TPERSON
WITH OBJECT IDENTIFIER (NUM)
AS
(SELECT NUM, LASTNAME, FIRSTNAME, CAST(
MULTISET(
SELECT TADDRESS(STREET, CITY, ZIPCODE)
FROM LIVE L
WHERE P.NUM = L.NUM)
AS TLIST ADDRESSES)
FROM PERSON P );
◦ The OBJECT OID clause tells Oracle which column to rely on to build
the OIDs.
◦ CAST and MULTISET are used to handle elements that do not conform
to the 2nd normal form in the type.

A. Chikhaoui Views 77 / 88
TRIGGERS
TRIGGERS I
A trigger is an active database rule that follows the
event-condition-action (ECA) model. This means:
▶ Event → A specific change occurs in the database (e.g., INSERT,
UPDATE, DELETE).
▶ Condition (optional) → A condition must be met before executing the
trigger.
▶ Action → The trigger performs an automatic operation (e.g., logging
changes, enforcing constraints).
They are stored procedures that execute automatically based on events.
Triggers allows to:
▶ Prevent Data Inconsistency (e.g., an order cannot be processed if the
stock is insufficient).
▶ Automatically Record Certain Events (tracking changes in a table. E.g. if
a user’s role is changed from ”Employee” to ”Admin,” tracking can alert
security teams.).
▶ Specify constraints related to data evolution (e.g. a salary can only
increase).

A. Chikhaoui TRIGGERS 79 / 88
TRIGGERS II

The following syntax is used to create a trigger:


CREATE [OR REPLACE] TRIGGER trigger name
BEFORE | AFTER Event [OF attribute name]
ON table name
REFERENCING OLD AS/NEW AS
< Action >
To delete a Trigger:
DROP TRIGGER Trigger name

A. Chikhaoui TRIGGERS 80 / 88
TRIGGERS III

Example 1: Checking that a price cannot decrease.


CREATE OR REPLACE TRIGGER not lowering price
BEFORE UPDATE OF unitprice ON Item
FOR EACH ROW
WHEN (:OLD.unitprice > :NEW.unitprice)
BEGIN
RAISE APPLICATION ERROR(-20100, ’An item”s price cannot be lowered’);
END;
RAISE APPLICATION ERROR is a built-in function that allows
developers to generate user-defined error messages and associate them
with specific error codes.
The error number in RAISE APPLICATION ERROR must be between
-20000 and -20999 (to ensure that custom errors do not conflict with
Oracle’s predefined error codes).

A. Chikhaoui TRIGGERS 81 / 88
TRIGGERS IV

Example 2: Recording all salary changes in an audit table:


CREATE TABLE salary audit (
emp id NUMBER,
old salary NUMBER,
new salary NUMBER,
change date DATE
);

CREATE OR REPLACE TRIGGER salary update trigger


AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary audit (emp id, old salary, new salary, change date)
VALUES (:OLD.emp id, :OLD.salary, :NEW.salary, SYSDATE);
END;

A. Chikhaoui TRIGGERS 82 / 88
Association in SQL3
Transformation of associations I

A. Chikhaoui Association in SQL3 84 / 88


Transformation of associations II

For each association, both


roles must be defined.
Any association with
teacher course
association class must be Std eval student course
transformed into two
associations, look at the
case of the evaluation course student
association. course teacher

Course eval

Eval std
Eval course

A. Chikhaoui Association in SQL3 85 / 88


Father-son association 1..* I

For the parent class (course), we add an attribute that stores the
references of the children (teachers) who taught this course, where
course teacher represents a nested table of teacher references.
For the child(teacher) class, we add an attribute that stores the
reference of the parent (course) taught by this teacher, where
teacher course represents the reference to the course taught.

A. Chikhaoui Association in SQL3 86 / 88


Father-son association 1..* II
– Forward declaration of Course Type
CREATE OR REPLACE TYPE Course Type;
/

CREATE OR REPLACE TYPE Teacher Type AS OBJECT (


Teacher ID NUMBER,
Account Number VARCHAR2(20),
Bank VARCHAR2(50),
Teacher Course REF Course Type -- Stores a reference to the course taught
); /

-- Define a nested table type to store multiple teacher references in a course


CREATE OR REPLACE TYPE Teacher Set AS TABLE OF REF Teacher Type;
/

-- Define Course Type with a nested table of teacher references


CREATE OR REPLACE TYPE Course Type AS OBJECT (
Course ID NUMBER,
Title VARCHAR2(100),
Credit NUMBER,
Course Teachers Teacher Set -- Stores multiple references to Teacher Type
);
/

A. Chikhaoui Association in SQL3 87 / 88


Many-to-many association *..*

For the student class, we add an attribute that stores the references of
the courses in which the student is enrolled, where student cours
represents a nested table of course references.
For the course class, we add an attribute that stores the references of
students enrolled in this course, where course student represents a
nested table of student references.

A. Chikhaoui Association in SQL3 88 / 88

You might also like