You are on page 1of 146

Object relational

data model
By Lielet G.
File system
RDBMS,OODBMS,ORDBMS
Object relational data models
Oracle Relational Model

• Structures : tables, views, indexes, etc.


• Operations : actions that manipulate data
stored in structures
• Integrity rules : laws that determine which
operations are allowed on data and
structures.
Schema
•  Collection of database objects available to
the users
• • Schema objects: tables, views, indexes,
stored procedures, etc.
Structures(1)
•  Tables: basic unit of data storage. They can
be queried, updated, inserted into, deleted
from, etc.
• Views: custom-tailored presentation of the
data in one or more table. They do not really
contain any data. They can be queried,
updated, inserted into, deleted from, etc.
• Materialized views: store the result of a
query in a separate schema object.
Structures(2): Indexes 
• Optional structures associated with tables which
can be created to increase the performance of
queries
• They are created on one or more columns of a
table
• Once created, they are automatically
maintained and used by Oracle
• Changes to tables are transferred to all relevant
indexes (in a transparent way to users)
Object-Oriented Concepts
• Abstraction and Encapsulation (Provided by
Abstract Data Types (ADT))
– Abstraction is the process of identifying the
essential aspects of an entity and ignoring the
unimportant properties. Focus on what an object is
and what it does, rather than how it should be
implemented.
– Encapsulation (or information hiding) provides data
independence by separating the external aspects of
an object from its internal details, which is hidden
from the outside world.
• Classes: A class is a blueprint or prototype from
which objects are created.
• A group of objects with the same attributes and
methods. Hence, the attributes and the associated
methods are defined once for the class rather than
separately for each object.
• Attributes (or instance variables) describe the current
state of an object (the notation for attribute: object-
name.attribute-name).
• Methods: define the behavior of the object.
They can be used to change the object’s state
by modifying its attribute values, or to query the
value of the selected attributes. A method
consists of a name and a body that performs the
behavior associated with the method name
(notation: objectname.method-name).
• The instances of a class are those objects
belonging to a class.
Advantages of ORDBMS
• Enables reuse and sharing.
– Ability to extend the DBMS server to perform
standard functionality centrally, rather than have
it coded in each application. Example: Embedded
Functions, it saves having to define it in each
application that needs it.
• Ability and support for complex objects and
rich data types, termed abstract data types
(ADTs)
• Complex applications such as Oracle Spatial
• Support for Inheritance
– Inherent attributes and behavior of the
pre-existing classes, hence ease of definition
and programming
Oracle Objects
• Oracle object types are user-defined types that
make it possible to model real-world entities,
such as customers and purchase orders, as
objects in the database
• Advantages of Objects
■ Objects Can Encapsulate Operations Along with Data
■ Objects Are Efficient
■ Objects Can Represent Part-Whole Relationships
Oracle Object-Relational
Model
•  Allows to:
– define object types specifying
• the structure of the data (property/state ) and
• the methods of operating on the data
– use these data types within the relational
model
• Object types are abstractions of the real-
world entities
Object Types 
• Three components:
– Name: to identify the object type uniquely
– Attributes: to model the structure of the entity.
They are built-in or user-defined datatypes
– Methods: functions/procedures written in
PL/SQL or Java and stored in the DB or written
in a different language and stored externally.
– NOTE: every object type has a constructor
method to create a new object of that type
An Object Type and Object Instances
Object
•  Object: variable of an object type
• Characterized by attributes and methods
based on its type
• Possible to assign values to object
attributes and call object methods
Object Type Definition
• Objects are created using the CREATE
[OR REPLACE] TYPE statement.
Creating the person_typ Object Type

CREATE or Replace TYPE person_typ AS OBJECT


(
idno NUMBER,
first_name VARCHAR2(20),
last_name VARCHAR2(25),-- Attribute declared
email VARCHAR2(25),
phone VARCHAR2(20),
MAP MEMBER FUNCTION get_idno RETURN NUMBER,
MEMBER PROCEDURE display_details ( SELF IN OUT NOCOPY
person_typ ) -- method
);
/-- This slash needed to get Oracle process this statement.
--Defining an object type does not allocate any storage. --The body of
method is defined in a separate CREATE --TYPE BODY statement,
written in PL/SQL or any other languages.
DROP TYPE person_type; --First drop all tables and other types using
person_type.
Oracle Methods
• Are Functions/procedures declared in the object type
definition to implement behavior of the object of that
type.
• Written in PL/SQL or virtually any other languages
(Java, C…)
• Method types
– Member
– Static /comparison
– Constructor
– The body of method is defined in a separate CREATE TYPE
BODY statement, written in PL/SQL or any other languages
Member Methods
• Defined on object instance’s data.
• Using member methods, we can provide access to the
data of an object, and otherwise define operations that
an application performs on the data.
• Function or procedure that always has an implicit SELF
parameter and can work with the attributes of a specific
object
• Invoked with dot notation: object_variable.method()
• Useful to write methods where the operation affects a
specific object and you do not need to pass parameters
• To perform an operation, the application calls the
appropriate method on the appropriate object.
Static Method 
• Function or procedure that does not have
an implicit SELF parameter
• Invoked with dot notation using the type
name: type_name.method()
• Useful for procedures that work with
global data rather than a specific object or
functions that return the same value
independently of the particular object
comparison Method

• Oracle has facilities for comparing two data


items of a given built-in type and determining
whether one is greater than, equal to, or less
than the other.
• To compare two objects of a user-defined type,
the creator of the type must define comparison
methods
• Two types: map methods or order methods.
• They allow you to establish rules so that SQL
statements and PL/SQL programs can order,
group, and otherwise compare object instances.
• Comparison methods are always functions.
Map Methods 
• Map methods produce a single value of a
built-in type that can be used for
comparisons and sorting.
• For example, if you define an object type
called RECTANGLE, the map method AREA
can multiply its HEIGHT and WIDTH
attributes and return the answer.
• Oracle can then compare two rectangles by
comparing their areas.
Order Methods
•  They use their own internal logic to compare two
objects of a given object type and return a value that
encodes the order relationship:
– 1 if the first is smaller,
– 0 if they are equal,
– and 1 if the first is larger.

• For example, an order method can allow you to sort


a set of addresses based on their distance from a
fixed point, or some other operation more
complicated than comparing individual values.
• In defining an object type, you can specify either a
map method or an order method for it, but not both.
Other Comparisons
•  If an object type has no comparison method, Oracle
cannot determine a greater-than or less-than relationship
between two objects of that type
• It can, however, attempt to determine whether two
objects of the type are equal. Oracle compares two
objects of a type that lacks a comparison method by
comparing corresponding attributes:
– If all the attributes are non-null and equal, the objects are
considered equal.  
– If there is an attribute for which the two objects have unequal
non- null values, the objects are considered unequal.
– Otherwise, the objects are considered unequal.
Constructor Methods
• constructor method is called on a type to construct or
create an object instance of the type.
• The default constructor, supplied automatically when
you create an object type, allows you to create an object
of the corresponding type.
• You have no direct control over this function (aside from
how you have defined the attributes of the object type).
• The constructor is the only type of method that does not
operate on an existing object.
Method Definition
Where,
•function-name specifies the name of the
function.
•[OR REPLACE] option allows the
modification of an existing function.
•The optional parameter list contains name,
mode and types of the parameters.
• IN represents the value that will be passed from
outside and OUT represents the parameter that will
be used to return a value outside of the procedure.
• The function must contain a return statement.
• The RETURN clause specifies the data type you
are going to return from the function.
• function-body contains the executable part.
• The AS keyword is used instead of the IS keyword
for creating a standalone function.
Cont..
CREATE TYPE BODY person_typ AS

MAP MEMBER FUNCTION get_idno RETURN NUMBER IS


BEGIN
RETURN idno;
END;

MEMBER PROCEDURE display_details ( SELF IN OUT NOCOPY person_typ )


IS
BEGIN

DBMS_OUTPUT.PUT_LINE(TO_CHAR(idno) || ' ' || first_name || ' ' || last_name);

DBMS_OUTPUT.PUT_LINE(email || ' ' || phone);

END;

END;
/
Creating Object Tables
• Creating an object type is not the same as
creating a table.
• Creating a type merely defines a logical
structure; it does not create storage.
• To use an object-relational interface to your data,
you must create object types whether you intend
to store your
data in object tables or leave it in relational tables
and access it through object views.
• Object views and object tables alike
presuppose object types: an object table
or object view is always a table or view of
a certain object type.
Generally, you can think of the relationship
between the "objects" and "object tables"
in the following way:
• Classes, which represent entities, map to
object tables
• Attributes map to columns
• Objects map to rows
Object type as a data type
CREATE TABLE contacts
(
contact person_typ, -- object type can be used like any other built-in data types.
contact_date DATE );

--The contacts table is a relational table with an object type as the data type of its
contact column.

INSERT INTO contacts VALUES


(person_typ (65, 'Verna', 'Mills', 'vmills@example.com', '1-650-555-0125'),--Instance
'24 Jun 2003' );

Note:
--person_type is instantiated and values are assigned to the attributes of the object
instance.
How Objects are Stored in Tables

Objects can be stored in two types of tables:


■ Object tables: store only objects
– In an object table, each row represents an object,
which is referred to as a row
■ Relational tables: store objects with other table
data
– Objects that are stored as columns of a relational
table, or are attributes of other
EX:- the contacts table which stores an instance of the
person_typ object.
Object Tables
• An object table is a special kind of table in which each row
represents an object. For example, the following
statement defines an object table for objects of the
PERSON type:
CREATE TABLE person_obj_table OF person_typ;
• Oracle allows you to view this table in two ways:
• A single-column table in which each row is a
PERSON object, allowing you to perform object-
oriented operations.
• As a multi-column table, in which each attribute of
the object type person_typ such as idno, first_name,
last_name, and so on, occupies a column, allowing to
perform relational operations.
Operations on the person_obj_table Object Table

INSERT INTO person_obj_table VALUES


( person_type(101, 'John', ' Smith' , ' jsmith@example.com ' ,
' 1-605-555-0135 ' );
SELECT VALUE(p)
FROM person_obj_table p
WHERE p.last_name = 'Smith';
-- The first instruction inserts a Person_typ object
into person_obj_table as a multi-column table.
-- The second selects from person_obj_table as a
single column table.
Declaration Initialization of
Object Type
• Like other components in PL/SQL, object
types are also needed to be declared
before using them in the program.
• Once the object type is created it can be
used in subprogram declarative section to
declare a variable of that object type.
• Defining an object type provides a
blueprint for the object. To use this object,
you need to create instances of this object.
You can access the attributes and
methods of the object using the instance
name and the access operator (.) 
• Whenever any variable is declared in the
subprogram as object type, at run-time a
new instance of the object type will be
created, and this newly created instance
can be referred to the variable name. By
this way, a single object type can store
multiple values under different instances.
Cont..
SET SERVEROUTPUT ON
declare
perobj person_typ;
begin
perobj:=person_typ(101, 'John', 'Smith',
'jsmith@example.com', '1-650-555-0135');
perobj.display_details();
end;
/
Cont.
Using the get_idno Object Method on the
above object type

SELECT c.contact.get_idno() FROM contacts c;


Retrieving Records
# 1. SELECT * FROM person_obj_table;
#2. SELECT * FROM contacts;
#3. SELECT value(a)
FROM person_obj_table a; --‘a’ is called
‘Alias’
# 4. SELECT value(c) FROM contacts; --x
the function “value(alias)” works only for
retriving records from object tables
• Getting particular column data
# 5. SELECT first_name
FROM person_obj_table;

#6. SELECT c.contact.first_name


FROM contacts c;
• Accessing particular rows
• In Object Table
# 6. SELECT first_name
FROM person_obj_table
WHERE idno=101;
#7. SELECT VALUE(p)
FROM person_obj_table p
WHERE p.last_name = 'Smith';
• In tables which has column
objects
#8. SELECT c.contact.first_name
FROM contacts c
WHERE c.contact.first_name = ‘verna’ AND
c.contact.first_name idno<230;
Updating object records
• In Object Table
UPDATE person_obj_table
SET first_name=‘kebede’
WHERE idno=101;

• In tables which has column objects


UPDATE contacts c
SET c.contact.first_name =‘aster’
WHERE c.first_name=‘verna’;
Deleting Records
• In Object Table
DELETE FROM person_obj_table
WHERE first_name=‘kebede’;
• In tables which has column objects
DELETE FROM contacts c
WHERE c.contact.first_name=‘aster’;
or
DELETE FROM contacts c
WHERE c.first_name=‘aster’;
Droping object type
DROP TYPE type_name;
E.x. DROP TYPE person_obj_table;
-- before dropping object types, don’t forget
to drop all the dependent types or tables
 The REF function take row objects as its argument
Object Type and returns their OID value
 The ‘REF’ function does not give any useful
information by itself.
Object Tabl
 Ex.
 Take the object table ‘person_obj_table’ found on
Column slide 3
Object SELECT REF(a)
FROM person_obj_table a;
“REF” & “DEREF” --this query displays the OID of each row objects/records found on
“person_obj_table”
 Notice that the above statement will not work for
Type column objects
Inherita
 The DEREF function does the opposite of REF: it
Object Type takes a reference value(OID generated from the REF
function) and returns the value of the row object
Ex.
Object Tabl  Take the object table ‘address_tbl’ found on
slide 3
Column CREATE TABLE contacts
Object ( contact ref person_typ,
contact_date DATE );
“REF” & “DEREF” --the attribute contactpoints to any object table of person_typ
which is person_obj_table in this case and it stores OID’s not the actual
values of the row objects
Type
);
Inherita
Creating a Member Method
CREATE OR REPLACE TYPE solid_typ AS OBJECT (
len INTEGER,
wth INTEGER,
hgt INTEGER,
MEMBER FUNCTION surface RETURN INTEGER,
MEMBER FUNCTION volume RETURN INTEGER,
MEMBER PROCEDURE display (SELF IN OUT NOCOPY solid_typ) );
/

CREATE OR REPLACE TYPE BODY solid_typ AS


MEMBER FUNCTION volume RETURN INTEGER IS
BEGIN
RETURN len * wth * hgt;
Or RETURN SELF.len * SELF.wth * SELF.hgt;
END;
Cont..
MEMBER FUNCTION surface RETURN INTEGER IS
BEGIN
RETURN 2 * (len * wth + len * hgt + wth * hgt);
END;

MEMBER PROCEDURE display (SELF IN OUT NOCOPY solid_typ) IS


BEGIN
DBMS_OUTPUT.PUT_LINE('Length: ' || len || ' - ' || 'Width: ' || wth
|| ' - ' || 'Height: ' || hgt);

DBMS_OUTPUT.PUT_LINE('Volume: ' || volume || ' - ' || 'Surface area: '


|| surface);

END;
END;
/
Cont..
CREATE TABLE solids of solid_typ;

INSERT INTO solids VALUES(10, 10, 10);

INSERT INTO solids VALUES(3, 4, 5);

SELECT * FROM solids;

SELECT s.volume(), s.surface() FROM solids s WHERE s.len = 10;

SET SERVEROUTPUT ON
DECLARE
solid solid_typ;
BEGIN
SELECT VALUE(s) INTO solid FROM solids s WHERE s.len = 10;

solid.display();

END;
Member Methods for Comparing
Objects
• Map Methods Map methods return values
that can be used for comparing and
sorting.
• obj_1 > obj_2 is equivalent to:
obj_1.map() > obj_2.map()
Creating a Map Method
CREATE OR REPLACE TYPE rectangle_typ AS OBJECT (
len NUMBER,
wid NUMBER,
MAP MEMBER FUNCTION area RETURN NUMBER);
/

CREATE OR REPLACE TYPE BODY rectangle_typ AS


MAP MEMBER FUNCTION area RETURN NUMBER IS
BEGIN
RETURN len * wid;
END area;
END;
/
Invoking a Map Method
DECLARE
po rectangle_typ;
BEGIN
po :=NEW rectangle_typ(10,5);
DBMS_OUTPUT.PUT_LINE('AREA:' || po.area()); -- prints AREA:50
END;
Order Methods
• Order methods make direct one-to-one
object comparisons. Unlike map methods,
they cannot determine the order of a
number of objects.
• They simply tell the current object is less
than, equal to, or greater than the object
that it is being compared to, based on the
criterion used.
Creating and Invoking an Order
Method
--shows an order method that compares locations by building number:
CREATE OR REPLACE TYPE location_typ AS OBJECT (
building_no NUMBER,
city VARCHAR2(40),
ORDER MEMBER FUNCTION match (l location_typ) RETURN INTEGER );
/
CREATE OR REPLACE TYPE BODY location_typ AS
ORDER MEMBER FUNCTION match (l location_typ) RETURN INTEGER IS
BEGIN
IF building_no < l.building_no THEN
RETURN -1;
ELSIF building_no > l.building_no THEN
RETURN 1;
ELSE
RETURN 0;
END IF;
END;
END;
/
-- invoking match method
DECLARE
loc location_typ;
secloc location_typ;
a number;
BEGIN
loc :=NEW location_typ(300, 'San Francisco');
secloc :=NEW location_typ(200, 'Redwood Shores');
a := loc.match(secloc);
DBMS_OUTPUT.PUT_LINE('order (1 is greater, -1 is lesser):' ||a); --
prints order:1
END; /
Oracle  Constructor Functions
Methods
 Are functions that return a new instance of
Member an object type and used to set up the values
Methods of its attributes, known in PL/SQL as self
Comparison  Every object type has a default constructor
Methods method
 The name of the constructor method is the
Constructor same as the name of the object type
Methods  Beside the default constructor we can
define other constructors
Metho
 CREATE TYPE shape_typ AS OBJECT(
name varchar2(12),
area number
) NOT FINAL;
/
 CREATE TYPE rectangle_typ UNDER shape_typ(
len number,
wth number,

CONSTRUCTOR FUNCTION rectangle_typ (name VARCHAR2, len NUMBER, wth NUMBER)


RETURN SELF AS RESULT,

CONSTRUCTOR FUNCTION rectangle _typ(name VARCHAR2, side NUMBER)


RETURN SELF AS RESULT
--notice that every constructor function return type is ‘SELF AS RESULT’
);
/
CREATE TYPE BODY rectangle_typ AS
CONSTRUCTOR FUNCTION rectangle_typ (name VARCHAR2, len NUMBER, wth NUMBER)

AS RESULT IS
RETURN SELFBEGIN
SELF.name := name;
SELF.area := len*wth;
SELF.len := len;
SELF.wth := wth;
RETURN ;
END;
CONSTRUCTOR FUNCTION rectangle_typ (name VARCHAR2, side NUMBER) RETURN SELF AS
RESULT IS
BEGIN
SELF.name := name;
SELF.area := side * side;
SELF.len := side;
SELF.wth := side;
RETURN ;
END;
END;
/
CREATE TABLE shape_tbl OF shape_typ;

INSERT INTO shape_tbl VALUES(shape_typ('shape2', 20)); -- using default constructor


INSERT INTO shape_tbl VALUES(rectangle_typ('rectangle',2, 5)); -- using constructor 1
INSERT INTO shape_tbl VALUES(rectangle-typ('quadrangle',40,12, 3)); -- using default
constructor
INSERT INTO shape_tbl VALUES(rectangle_typ('square', 12)); -- using constructor 2

SELECT VALUE(s) FROM shape_tbl s;


Result Set
VALUE(S)(NAME, AREA)
---------------------------------------------
SHAPE_typ('shape2', 20)
RECTANGLE_typ('rectangle', 10, 2, 5)
RECTANGLE_typ('quadrangle', 40, 12, 3)
RECTANGLE_typ('square', 144, 12, 12)
Object Type  In the derived subtype you can
 Add new attributes that its parent does
not have.
Object Tabl
 Add entirely new methods that the
Column parent does not have.
Object
“Ref”  Change the implementation of some of
“Dere the methods that a subtype inherits so that
the subtype's version executes different
TYPE
code from the parent's.
INHERITANCE
Object Type
 If a type is defined as FINAL(which is
the default), it means that no subtypes
Object Tabl
can be derived from it & NOT FINAL
Column means subtypes can be derived
Object
“Ref”
“Dere
 The UNDER keyword used to inherit
a type
TYPE
INHERITANCE
 CREATE TYPE person_typ AS OBJECT(
name varchar2(12),
sex char(1),
bdate date) NOT FINAL; -- if you forget to specify this clause you can’t
create a subtype under this type
 To change a FINAL type to NOT FINAL after creation use this command

ALTER TYPE person_typ NOT FINAL;

 CREATE TYPE employee_typ UNDER person_typ(


eid number,
salary number(5,2));
--The default constructor of employee_typ accept five attribute values :2 for their own
attributes and 3 for the attributes inherited from the super type person_typ,
Creating the person_typ Object
Type as NOT FINAL
DROP TYPE person_typ FORCE;
CREATE OR REPLACE TYPE person_typ
AS OBJECT ( idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20))
NOT FINAL;
/
Creating an Object Type as NOT
FINAL with a FINAL Member
Function
CREATE OR REPLACE TYPE person_typ
AS OBJECT (
idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20),
FINAL MAP MEMBER FUNCTION get_idno RETURN NUMBER)

NOT FINAL;
/
Creating the Parent or Supertype person_typ
Object
CREATE OR REPLACE TYPE person_typ AS OBJECT (
idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20),
MAP MEMBER FUNCTION get_idno RETURN NUMBER,
MEMBER FUNCTION show RETURN VARCHAR2)
NOT FINAL;
/
CREATE OR REPLACE TYPE BODY person_typ AS
MAP MEMBER FUNCTION get_idno RETURN NUMBER IS
BEGIN
RETURN idno;
END;
-- function that can be overriden by subtypes
MEMBER FUNCTION show RETURN VARCHAR2 IS
BEGIN
RETURN 'Id: ' || TO_CHAR(idno) || ', Name: ' || name;
END;
END;
/
Creating a Subtype Object
CREATE TYPE student_typ UNDER person_typ (
dept_id NUMBER,
major VARCHAR2(30),
OVERRIDING MEMBER FUNCTION show RETURN VARCHAR2)
NOT FINAL;
/

CREATE TYPE BODY student_typ AS


OVERRIDING MEMBER FUNCTION show RETURN VARCHAR2 IS
BEGIN
RETURN (self AS person_typ).show || ' -- Major: ' || major ;
END;
END;
/
Multiple types
CREATE OR REPLACE TYPE employee_typ UNDER person_typ (
emp_id NUMBER,
mgr VARCHAR2(30),
OVERRIDING MEMBER FUNCTION show RETURN VARCHAR2);
/
CREATE OR REPLACE TYPE BODY employee_typ AS
OVERRIDING MEMBER FUNCTION show RETURN VARCHAR2 IS
BEGIN
RETURN (SELF AS person_typ).show|| ' -- Employee Id: '
|| TO_CHAR(emp_id) || ', Manager: ' || mgr ;
END;
END;
/
Creating a table that contains super
type and sub type objects
INSERT INTO person_obj_table
VALUES (person_typ(12, 'Bob Jones', '650-555-0130'));

INSERT INTO person_obj_table


VALUES (student_typ(51, 'Joe Lane', '1-650-555-0140', 12,
'HISTORY'));

INSERT INTO person_obj_table


VALUES (employee_typ(55, 'Jane Smith', '1-650-555-0144',
100, 'Jennifer Nelson'));

You can call the show() function for the supertype and subtypes in the table with the
following:
SELECT p.show() FROM person_obj_table p;
Redefining an inherited
property by defining the
same property differently at
the subtype level

Adding new methods that have


For a method, FINAL means
the same name as the the subtypes cannot override
inherited ones to the subtype it by providing their own
is called overloading. implementation. NOT FINAL
(default) means that you can
override the method of the
Methods that have the same
supertype.
name, but different signatures
are called overloads.
CREATE TYPE shape_typ AS OBJECT(
name varchar2(12),
area number,

FINAL MEMBER FUNCTION get_name RETURN


NUMBER, --this method can not be override by subtypes

MEMBER FUNCTION get_area RETURN NUMBER

MEMBER PROCEDURE display


) NOT FINAL;
/
CREATE TYPE BODY shape_typ AS
FINAL MEMBER FUNCTION get_name RETURN NUMBER IS
BEGIN
RE
TURN name;
END get_name;
MEMBER FUNCTION get_area RETURN NUMBER IS
BEGIN
R
ETURN area;
END get_area;
MEMBER PROCEDURE display IS
BEGIN
dbms_output.put_line(‘Name:’ || name ||’Area:’ ||area);
END display;
END;
CREATE TYPE rectangle_typ UNDER shape_typ(
len number,
wth number,

MEMBER FUNCTION get_area(len number,wth number) RETURN


number, -- while overloading methods all you have to do is change the
parameters

OVERRIDING MEMBER PROCEDURE display


--while overriding methods you have to use the ‘OVERRIDING’ key word in

front of the signature to tell the processor that this method is going to be
overrided
);
/
CREATE TABLE rectangle_tbl OF rectangle_typ;
INSERT INTO rectangle_tbl VALUES(rectangle_typ(‘rec01’,5,4,3));
INSERT INTO rectangle_tbl VALUES(rectangle_typ('rec02',10,1 ,4));
-- using default constructor of rectangle_typ

SELECT r.get_name()
FROM rectangle_tbl r
WHERE r.get_area()<5; - - this method is called from the super type

SELECT *
FROM rectangle_tbl r
WHERE r.get_area(r.len,r.wth)<5; - - this method is called from the sub type
CREATE TYPE BODY rectangle_typ AS
MEMBER FUNCTION get_area(len number,wth number)
RETURN number IS
BEGIN
RETURN
len*wth;
END get_area;
OVERRIDING MEMBER PROCEDURE display IS
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Name’||name||’area’||
get_area(LEN, WID)‘length’||len||’width’||wth);
END display;
END;
/
 Only methods that are not declared to be final
in the supertype can be overridden.

 Order methods may appear only in the root


type of a type hierarchy: they may not be
redefined (overridden) in subtypes.

 If a method being overridden provides default


values for any parameters, then the overriding
method must provide the same default values for
the same parameters.
If a type is NOT INSTANTIABLE, it means there is no
constructor (default or user-defined) for it, and you cannot
instantiate instances of that type

If a method is NOT INSTANTIABLE, it means the body of the


method is not going to be implemented in that type body
definition

You might define a non-instantiable method when you expect


every subtype to override the method in a different way.

 A type that contains a non-instantiable method must itself be


declared not instantiable.
Creating an Object Type that is
NOT INSTANTIABLE
CREATE OR REPLACE TYPE person_typ AS
OBJECT (
idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20),
NOT INSTANTIABLE MEMBER FUNCTION
get_idno RETURN NUMBER)
NOT INSTANTIABLE NOT FINAL;
/
Altering an Object Type to
INSTANTIABLE

CREATE OR REPLACE TYPE person_typ AS


OBJECT (
idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20))
NOT INSTANTIABLE NOT FINAL;
/
ALTER TYPE person_typ INSTANTIABLE;
CREATE TYPE shape_typ AS OBJECT(
name varchar2(12),
NOT INSTANTIABLE MEMBER FUNCTION area
RETURN number
)NOT INSTANTIABLE NOT FINAL;
/
CREATE TYPE BODY rectangle_typ AS
OVERRIDING MEMBER
FUNCTION area
RETURN number IS
BEGIN
RETURN
len*wth;
END; END area;
/
CREATE TYPE circle_typ UNDER shape_typ (
radius number,
OVERRIDING MEMBER FUNCTION area
RETURN number
);
/
CREATE TYPE BODY circle_typ AS
OVERRIDING MEMBER
FUNCTION area
RETURN number IS
BEGIN
RETURN 3.14 *(radius*radius);
END area;
END;
/
CREATE TABLE rectangle OF rectangle_typ;
CREATE TABLE circle OF circle_typ;

INSERT INTO rectangle


VALUES(rectangle_typ(‘rec01’,4,3));
INSERT INTO circle VALUES(circle_typ(‘cir01‘,4));

SELECT r.name, r.area() FROM rectangle r;


SELECT c.name, c.area() FROM circle c;
If a subtype does not provide an implementation
for every inherited non-instantiable method, the
subtype itself, like the supertype, must be declared
not instantiable.

A non-instantiable subtype can be defined under


an instantiable supertype.

You cannot declare a non-instantiable type to be


FINAL
 In oracle you can have two types of views
 Relational views :
 views whose bases are relational tables
 Object views :
 Views whose bases are either relational tables or object
tables
 Object views that are derived from relational tables
allows the user to perform object oriented features
Creating an Object View
CREATE TYPE employee_t AS OBJECT (
empno NUMBER (5),
ename VARCHAR2 (20),
salary NUMBER (9,2),
job VARCHAR2 (20));
/
CREATE TABLE emp_table (
empnum NUMBER (5),
ename VARCHAR2 (20),
salary NUMBER (9,2),
job VARCHAR2 (20));
Cont..
CREATE VIEW emp_view1 OF employee_t
WITH OBJECT IDENTIFIER (empno) AS
SELECT e.empnum, e.ename, e.salary, e.job
FROM emp_table e
WHERE job = 'Developer';
Cont..
CREATE VIEW dept_view OF dept_t WITH
OBJECT IDENTIFIER (deptno) AS
SELECT d.deptno, d.deptname,
address_t(d.deptstreet,d.deptcity,d.deptstate
,d.deptzip) AS
deptaddr
FROM dept d;
Nesting Objects in Object Views
CREATE TABLE dept (
deptno NUMBER PRIMARY KEY,
deptname VARCHAR2(20),
deptstreet VARCHAR2(20),
deptcity VARCHAR2(10),
deptstate CHAR(2),
deptzip VARCHAR2(10));

CREATE TYPE address_t AS OBJECT (


street VARCHAR2(20),
city VARCHAR2(10),
state CHAR(2),
zip VARCHAR2(10));
/

CREATE TYPE dept_t AS OBJECT (


deptno NUMBER,
deptname VARCHAR2(20),
address address_t );
Security
 Security - protection from malicious attempts to steal or modify
data.
 Database system level
 Authentication and authorization mechanisms to allow specific
users access only to required data
 We concentrate on authorization in the rest of this chapter
 Operating system level
 Operating system super-users can do anything they want to the
database! Good operating system level security is required.
 Network level: must use encryption to prevent
 Eavesdropping (unauthorized reading of messages)
 Masquerading (pretending to be an authorized user or sending
messages supposedly from authorized users)

111
Security (Cont.)
 Physical level
 Physical access to computers allows destruction of
data by intruders; traditional lock-and-key security is
needed
 Computers must also be protected from floods, fire,
etc.
 More in Chapter 17 (Recovery)
 Human level
 Users must be screened to ensure that an authorized
users do not give access to intruders
 Users should be trained on password selection and
secrecy

112
Operating System Authentication (continued)

113
Authorization
Forms of authorization on parts of the database:

 Read authorization - allows reading, but not


modification of data.
 Insert authorization - allows insertion of new data, but
not modification of existing data.
 Update authorization - allows modification, but not
deletion of data.
 Delete authorization - allows deletion of data

114
Authorization (Cont.)
Forms of authorization to modify the database schema:
 Index authorization - allows creation and deletion of
indices.
 Resources authorization - allows creation of new
relations.
 Alteration authorization - allows addition or deletion of
attributes in a relation.
 Drop authorization - allows deletion of relations.

115
Authorization and Views
 Users can be given authorization on views, without being
given any authorization on the relations used in the view
definition
 Ability of views to hide data serves both to simplify usage
of the system and to enhance security by allowing users
access only to data they need for their job
 A combination or relational-level security and view-level
security can be used to limit a user’s access to precisely
the data that user needs.

116
View Example
 Suppose a bank clerk needs to know the names of
the customers of each branch, but is not authorized to
see specific loan information.
 Approach: Deny direct access to the loan relation, but
grant access to the view cust-loan, which consists only
of the names of customers and the branches at which
they have a loan.
 The cust-loan view is defined in SQL as follows:
create view cust-loan as
select branchname, customer-name
from borrower, loan
where borrower.loan-number = loan.loan-
number
117
View Example (Cont.)
 The clerk is authorized to see the result of the query:
select *
from cust-loan
 When the query processor translates the result into a
query on the actual relations in the database, we
obtain a query on borrower and loan.
 Authorization must be checked on the clerk’s query
before query processing begins.

118
Authorization on Views

 Creation of view does not require resources authorization since


no real relation is being created
 The creator of a view gets only those privileges that provide no
additional authorization beyond that he already had.
 E.g. if creator of view cust-loan had only read authorization on
borrower and loan, he gets only read authorization on cust-loan

119
Granting of Privileges
 The passage of authorization from one user to
another may be represented by an authorization
graph.
 The nodes of this graph are the users.
 The root of the graph is the database administrator.
 Consider graph for update authorization on loan.
 An edge Ui Uj indicates that user Ui has granted
update authorization on loan to Uj.
U1 U4

DBA U2 U5

U3
120
Authorization Grant Graph
 Requirement: All edges in an authorization graph must be
part of some path originating with the database
administrator
 If DBA revokes grant from U1:
 Grant must be revoked from U4 since U1 no longer has
authorization
 Grant must not be revoked from U5 since U5 has another
authorization path from DBA through U2
 Must prevent cycles of grants with no path from the root:
 DBA grants authorization to U7
 U7 grants authorization to U8
 U8 grants authorization to U7
 DBA revokes authorization from U7
 Must revoke grant U7 to U8 and from U8 to U7 since there is
no path from DBA to U7 or to U8 anymore.

121
Security Specification in SQL
 The grant statement is used to provide authorization
grant <privilege list>
on <relation name or view name> to <user list>
 <user list> is:
 a user-id
 public, which allows all valid users the privilege granted
 A role (more on this later)
 Granting a privilege on a view does not imply granting
any privileges on the underlying relations.
 The grantor of the privilege must already hold the
privilege on the specified item (or be the database
administrator).

122
Privileges in SQL
 select: allows read access to relation,or the ability to query using
the view
 Example: grant users U1, U2, and U3 select authorization on
the branch relation:
grant select on branch to U1, U2, U3
 insert: the ability to insert tuples
 update: the ability to update using the SQL update statement
 delete: the ability to delete tuples.
 references: ability to declare foreign keys when creating
relations.
 usage: In SQL-92; authorizes a user to use a specified domain
 all privileges: used as a short form for all the allowable
privileges

123
Creating Users

 You create a database user with the CREATE USER statement.

 To create a user, you must have the CREATE USER system


privilege.

 Because it is a powerful privilege, a DBA or security administrator is


normally the only user who has the CREATE USER system
privilege.

 A newly created user cannot connect to the database until granted


the CREATE SESSION system privilege.
CREATE USER - Syntax
Creating an Oracle User (continued)

126
CREATE USER– An example

CREATE USER Abebe


IDENTIFIED BY abebe99
DEFAULT TABLESPACE DBS_space
QUOTA 10M ON DBS_space
TEMPORARY TABLESPACE temp_space
PROFILE STAFF
PASSWORD EXPIRE
;

Database Systems Slide 127


How to Create a User and Grant Permissions in Oracle
CREATE USER Abebe IDENTIFIED BY password;
GRANT CONNECT TO Abebe;
GRANT CONNECT, RESOURCE, DBA TO Abebe;
GRANT CREATE SESSION GRANT ANY PRIVILEGE TO
Abebe;//Grant create session to abebe;
GRANT UNLIMITED TABLESPACE TO Abebe;
GRANT SELECT, INSERT, UPDATE, DELETE ON
schema.books TO Abebe;
Conn abebe/password;//Connect Abebe/password @
<database name>
Helpful Data Dictionary Views

 USER_USERS
 ALL_USERS
 DBA_USERS
 USER_TS_QUOTAS
 DBA_TS_QUOTAS

 Information about the database user who is currently logged on, can
be seen by examining the USER_USERS data dictionary view.
Querying System Privileges
ALL_SYS_PRIVS
SESSION_PRIVS
USER_SYS_PRIVS
DBA_SYS_PRIVS
SYSTEM_PRIVILEGE_MAP
Modifying Users
 Modifications involve:
– Changing passwords
– Locking an account
– Increasing a storage quota
 ALTER USER DDL statement

Removing an Oracle User

DROP command

Lock the account or revoke the CREATE SESSION privilege

130
Privilege To Grant Privileges
 with grant option: allows a user who is granted a
privilege to pass the privilege on to other users.
 Example:
grant select on branch to U1 with grant option
gives U1 the select privileges on branch and allows U1 to
grant this
privilege to others

131
Roles

 Managing and controlling privileges is made easier by using roles,


which are named groups of related privileges that you grant, as a
group, to users or other roles.

 Within a database, each role name must be unique, different from all
user names and all other role names.

 Unlike schema objects, roles are not contained in any schema.


Therefore, a user who creates a role can be dropped with no effect
on the role.

 Roles ease the administration of end-user system and schema


object privileges.

 However, roles are not meant to be used by application developers,


because the privileges to access schema objects within stored
programmatic constructs must be granted directly.
Creating Roles

 In order to create database roles it is necessary to use the


CREATE ROLE command.
 Syntax of the CREATE ROLE Command

CREATE ROLE role


NOT IDENTIFIED

IDENTIFIED BY password
 Where: EXTERNALLY
– Role Name of the role to be created
– NOT IDENTIFIED Users granted the role do not need to be verified by
ORACLE to enable it
– IDENTIFIED Indicates that the users granted the role must be verified
by ORACLE to enable the role
– BY password Specifies the password that authorizes enabling the role
– EXTERNALLY Specifies that ORACLE will verify user access to the role
using an operating system utility

Note : If the IDENTIFIED option is chosen, users can enable/disable the role
by using the SET ROLE command.
Benefits of Using Roles
 Reduced privilege administration
– Rather than granting the same set of privileges explicitly to several
users, you can grant the privileges for a group of related users to a role,
and then only the role needs to be granted to each member of the
group.
 Dynamic privilege management
– If the privileges of a group must change, then only the privileges of the
role need to be modified. The security domains of all users granted the
group’s role automatically reflect the changes made to the role.
 Selective availability of privileges
– You can selectively enable or disable the roles granted to a user. This
allows specific control of a user’s privileges in any given situation.
 Application awareness
– The data dictionary records which roles exist, so you can design
applications to query the dictionary and automatically enable (or
disable) selective roles when a user attempts to run the application by
way of a given user name.
Displaying Information About Roles

The following data dictionary views contain information about


privileges granted to roles, roles granted to users etc.

 ROLE_SYS_PRIVS System privileges granted to roles


 ROLE_TAB_PRIVS Table privileges granted to roles
 ROLE_ROLE_PRIVS Roles granted to other roles
 SESSION_ROLES Roles that the user currently has enabled
 USER_ROLE_PRIVS Roles granted to the user
 DBA_ROLES All roles existing in the database
 DBA_SYS_PRIVS System privileges granted to users and to
roles
Roles Creation Examples

create role teller


create role manager

grant select on branch to teller


grant update (balance) on account to teller
grant all privileges on account to manager

grant teller to manager

grant teller to alice, bob


grant manager to avi

136
Revoking Authorization in SQL
 The revoke statement is used to revoke authorization.
revoke<privilege list>
on <relation name or view name> from <user list> [restrict|
cascade]
 Example:
revoke select on branch from U1, U2, U3 cascade
 Revocation of a privilege from a user may cause other
users also to lose that privilege; referred to as cascading of
the revoke.
 We can prevent cascading by specifying restrict:
revoke select on branch from U1, U2, U3 restrict
With restrict, the revoke command fails if cascading
revokes are required.

137
Revoking Authorization in SQL
(Cont.)
 <privilege-list> may be all to revoke all privileges the
revokee may hold.
 If <revokee-list> includes public all users lose the
privilege except those granted it explicitly.
 If the same privilege was granted twice to the same
user by different grantees, the user may retain the
privilege after the revocation.
 All privileges that depend on the privilege being
revoked are also revoked.

138
Object Privileges

Note 1: Oracle Database


treats a Java class, source,
or resource as if it were a
procedure for purposes of
granting object privileges.
Note 2: Job scheduler
objects are created using
the DBMS_SCHEDULER
package. Once these
objects are created, you
can grant the EXECUTE
object privilege on job
scheduler classes and
programs. You can grant
ALTER privilege on job
scheduler jobs, programs,
and schedules.
Note 3: The DELETE,
INSERT, and UPDATE
privileges can be granted
only to updatable
materialized views.
Granting Object Privileges
, ,

GRANT Object_priv ON Object TO user

Schema. role
PUBLIC

WITH GRANT OPTION


Where:
– Object_priv: Is an object privilege to be granted
– ON: Identifies the object on which the privileges are granted. if the
“schema.” prefix is not used then ORACLE assumes the current
user’s schema.
– TO: Identifies the users or roles to which the object privilege is
granted
– PUBLIC: Grants object privileges to all users
– WITH GRANT OPTION : Allows the grantee to grant the object
privileges to other users and roles. The grantee must be a user or
PUBLIC. GRANT OPTION cannot be granted to a role.
Object Privileges Cascade

 Grantors can revoke privileges from only those users to whom they
had granted the privileges in the first place.
 Revoking an object privilege may have a cascading effect that
should be investigated before a REVOKE statement is issued.

GRANT REVOKE RESULT

A B C A B C A B C
Displaying Object Privileges
 The object privileges that have been granted can be displayed by
querying the data dictionary.
 Available to DBAs
– DBA_TAB_PRIVS All privileges on all tables in
the database
 Available to the User
– USER_TAB_PRIVS Privileges on tables for
which the user Is the owner, grantor, or
grantee

– USER_TAB_PRIVS_MADE All privileges on tables


owned by the user

– USER_TAB_PRIVS_RECD All privileges on tables for


which the user is the grantee
Limitations of SQL Authorization
 SQL does not support authorization at a tuple level
 E.g. we cannot restrict students to see only (the tuples
storing) their own grades
 All end-users of an application (such as a web
application) may be mapped to a single database user
 The task of authorization in above cases falls on the
application program, with no support from SQL
 Authorization must be done in application code, and
may be dispersed all over an application
 Checking for absence of authorization loopholes
becomes very difficult since it requires reading large
amounts of application code

145
Thank You!

You might also like