dato table data base application code 1° controllo procedure client side 3° controllo integrity...

35
Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS RULES CONTROL

Upload: agnese-lolli

Post on 02-May-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Dato

Table

Data BaseApplication Code

1° Controllo

Procedure Client Side

3° Controllo

Integrity Constraint

Trigger Code

2° Controllo

Event Driven

BUSINESS RULES CONTROL

Page 2: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Pericolo sui Dati

Un R.D.B.M.S. deve proteggere i dati da una svariata serie di insidie.

• Errori Accidentali (programming errors): Integrity issues.

• Utilizzo Illecito: Security issue.

• Hardware e Software Failures: Restart issues.

Types SQL constraints-) NOT NULL-) UNIQUE-) PRIMARY KEY-) Referential integrity (FOREIGN KEY)-) General assertion (CHECK’s)

Status SQL constraints-) Enabled-) Disabled

Using Index – Storage Option

Page 3: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Qualche Caratteristica SQL Constraints

• Migliorano le Performances• Facili da dichiarare / modificare• Centralizzano i controlli• Immediatamente producono un feed back utente• Flessibili (enabled / disabled)• Pienamente documentati nel dizionario dati• Definibili daI SQL Statement CREATE TABLE / ALTER TABLE• Definibili a livello di Tabella o di Colonna

• XXX_CONSTRAINTS• XXX_CONS_COLUMNS

• USER – Relativi alle tabelle poste nello schema dello user con il quale siamo connessi

• ALL – Relativi alle tabelle accessibili dall’utente con il quale siamo connessi

• DBA – Relativi a tutte le tabelle

Page 4: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Status SQL Constraints

DISABLED

ENABLED

Sospesi i controlli

Gli indici associati sono rimossi

Stato giustificato da:

--- grosse operazioni batch

--- loader massivi

--- import di oggetti tabellari separate

Con la tabella in “Lock” vengono effettuati i controlli sui record esistenti

Gli indici associati sono ricreati

Riprendono i controlli sulle nuove DML

Page 5: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Un TABLE CONSTRAINT è identico, sintatticamente alla stesura che vedremo per l’azione su colonna con l’unica differenza che può gestire più campi della stessa tabella.

[CONSTRAINT constraint] {[NOT] NULL | [ {UNIQUE | PRIMARY KEY} (column[, column])[FOREIGN KEY (column[, column]) [REFERENCES [user.] table[ (column[, column]) ] [ON DELETE CASCADE] [CHECK (condition) ]

Oracle Integrity Constraints: Table

Page 6: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Un integrity constraint applica una politica restrittiva sui valori relativi ad una o più colonne in una tavola.

Column CONSTRAINT clauses può apparire in CREATE TABLE ALTER TABLE SQL statement.

[CONSTRAINT constraint] [[NOT] NULL | UNIQUE | PRIMARY KEY ] [REFERENCES [user.] table[ (column) ] [ON DELETE CASCADE] [CHECK (condition) ]

Oracle Integrity Constraints: Column

Page 7: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Il constraint di UNIQUE designa una colonna, o una combinazione di esse, ad assumere, nel caso risultassero valorizzate, valori univoci.

Una “unique key column” non può essere di tipologia LONG o LONG RAW.

Non è tecnicamente fattibile designare lo stesso insieme di colonne sia per una unique key che per una primary key o una cluster key.

E’ possibile designare lo stesso insieme di colonne sia per una “unique key” che per una “foreign key”.

UNIQUE Constraints in Oracle

Page 8: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9) CONSTRAINT unq_dname UNIQUE, loc VARCHAR2(10) ) ;

In alternativa, è possibile utilizzare la seguente constraint syntax:

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9), loc VARCHAR2(10), CONSTRAINT unq_dname UNIQUE (dname) USING INDEX TABLESPACE ……. STORAGE (…..) PCTFREE … ) ;

Examples of Unique in Oracle

Page 9: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Una PRIMARY KEY caratterizza una colonna, o un insieme di esse, in grado di individuare il RECORD per tutta la permanenza nella Base Dati.

In sintesi si tratta di un set di colonne i cui valori devono risultare:

Univoci Totali Immutabili.

Una table può avere una ed esclusivamente una chiave primaria.

Una “primary key column” non può essere di tipologia: LONG o LONG RAW.

PRIMARY KEY Constraints in Oracle

Page 10: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE dept (deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY, dname VARCHAR2(9), loc VARCHAR2(10) )

Defining Primary Keys in Oracle

CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9), loc VARCHAR2(10), CONSTRAINT pk_dept PRIMARY KEY (deptno) USING INDEX TABLESPACE ……. STORAGE (…..) PCTFREE … )

Page 11: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

DEPTDno DnameD5 ResearchD6 AdvertisingD7 Newprojects

EMPEno Ename DnoE1 Smith D5E2 Black D6E3 Jones D6

E4 Brown deve essere inserito. Quali check devo considerare al fine di mantenere l’integrità della base dati?

Un tentativo di “delete” D5 Research occorre. Quali possibili azioni devo considerare al fine di mantenere l’integrità della base dati?

DEPT

EMP

FOREIGN KEY Constraints in Oracle

Page 12: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Maintain Referential IntegrityEvent

Delete corresponding Child records(Cascading Delete)

Delete of Parent

Action

Parent

Child

Set the Foreign Key to null in the corresponding Child records(Delete Nullifies)

Do not allow the delete of the Parent record if any corresponding Child records exist (Restricted Delete)

Page 13: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Maintain Referential IntegrityEvent

Update Foreign Key of corresponding Child records (Cascading Update)

Delete of Parent

Update of PrimaryKey of Parent

Action

Parent

Child

Set the Foreign Key to null in the corresponding Child records(Update Nullifies)

Do not allow the update of the Parent record if any corresponding Child records exist (Restricted Update)

Page 14: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Maintain Referential IntegrityEvent

Delete of Parent

Update of PrimaryKey of Parent

Insert of Child

Action

Parent

Child

Check that null or a valid Primary Key from the Parent has been specified for the Foreign Key

Page 15: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) CONSTRAINT fk_deptno REFERENCES dept(deptno) )

La FOREIGN KEY deve referenziare un insieme di colonne sulle quali agisceUna PRIMARY KEY oppure un UNIQUE CONSTRAINT

Oracle Referential Integrity Constraints

Page 16: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) CONSTRAINT fk_deptno REFERENCES dept(deptno) ON DELETE CASCADE )

ON DELETE CASCADE Option

Page 17: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE dept (deptno NUMBER CONSTRAINT check_deptno CHECK (deptno BETWEEN 10 AND 99) DISABLE, dname VARCHAR2(9) CONSTRAINT check_dname CHECK (dname = UPPER(dname)) DISABLE, loc VARCHAR2(10) CONSTRAINT check_loc CHECK (loc IN ('DALLAS','BOSTON', 'NEW YORK','CHICAGO')) DISABLE)

CHECK Constraint on a Column

Page 18: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

CREATE TABLE emp (empno NUMBER(4), ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2), CHECK (sal + comm <= 5000) )

Example of a CHECK Constraint on a Table

Page 19: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Triggers contrasted with routines

Procedures are called explicitly

Triggers are event-driven

Page 20: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Database Triggers

• Centralized actions can be defined using a non declarative approach (writing PL/SQL code) with database triggers.

• A database trigger is a stored procedure that is fired (implicitly executed) when an INSERT, UPDATE, or DELETE statement is issued against the associated table.

• Database triggers can be used to customize a database management system:– value-based auditing – automated data generation– the enforcement of complex security checks– enforce integrity rules– enforce complex business rules

Page 21: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

TRIGGER STRUCTURE

Regola di Scatto

Effetto

triggering event

PL/SQL Code

trigger action

Insert

Update of

Delete

After

Before

trigger restriction

the SQL statement that causes a trigger to be fired

specifies a Boolean expression that must be TRUE

for the trigger to fire. The trigger action is not executed if the

trigger restriction evaluates to FALSE or UNKNOWN

the procedure (PL/SQL block) that contains the SQL statementsand PL/SQL code to be executed when a triggering statement is issued and the trigger restriction evaluates to TRUE.

Page 22: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Example : maintaining derived values CREATE OR REPLACE TRIGGER increment_courses AFTER INSERT ON enrol

FOR EACH ROWBEGINupdate students

set numofcourses = numofcourses + 1where students.studno = :new.studno

END;

Event

Condition

Action

row trigger

column values for current rowand new/old correlation names

Page 23: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Example Integrity Trigger in Oracle

CREATE TRIGGER labmark_check BEFORE INSERT OR UPDATE OF labmark ON enrolDECLARE

bad_value exception;

WHEN (old.labmark IS NOT NULL OR new.labmark IS NOT NULL)

FOR EACH ROW BEGIN

IF :new.labmark < :old.labmarkTHEN raise bad_value ;END IF;EXCEPTIONWHEN bad_value THEN

raise_application_error(-20221,‘New labmark lower than old labmark’ );

END;

Event

Condition

Actionrow trigger

Page 24: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Some Cautionary Notes about Triggers

• Triggers are useful for customizing a database.

• But the excessive use of triggers can result in complex interdependencies, which may be difficult to maintain in a large application.

• E.g., when a trigger is fired, a SQL statement within its trigger action potentially can fire other triggers. When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading.

SQL statementUPDATE T1 SET …;

UPDATE_T1 TriggerBEFORE UPDATE ON T1FOR EACH ROWBEGIN...INSERT INTO t2 VALUES (...);...

END;

INSERT_T2 TriggerBEFORE UPDATE ON T2FOR EACH ROWBEGIN...INSERT INTO ... VALUES (...);...

END;

Fires the UPDATE-T1 Trigger

Fires the INSERT-T2 Trigger

Page 25: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Checklist for Creating UsersChecklist for Creating Users

1. Choose a username and authentication mechanism.

2. Identify tablespaces in which the user needs to store objects.

3. Decide on quotas for each tablespace.

4. Assign a default tablespace and temporary tablespace.

5. Create a user.

6. Grant privileges and roles to the user.

1. Choose a username and authentication mechanism.

2. Identify tablespaces in which the user needs to store objects.

3. Decide on quotas for each tablespace.

4. Assign a default tablespace and temporary tablespace.

5. Create a user.

6. Grant privileges and roles to the user.

Page 26: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Set the initial password:Set the initial password:

CREATE USER scottIDENTIFIED BY tigerDEFAULT TABLESPACE user_dataTEMPORARY TABLESPACE tempQUOTA 15m ON user_data;

CREATE USER scottIDENTIFIED BY tigerDEFAULT TABLESPACE user_dataTEMPORARY TABLESPACE tempQUOTA 15m ON user_data;

DROP USER peter CASCADE;DROP USER peter CASCADE;

Creating UsersCreating Users

Page 27: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Monitoring UsersMonitoring Users

DBA_USERS

USERNAME

USER_ID

CREATED

ACCOUNT_STATUS

LOCK_DATE

EXPIRY_DATE

DEFAULT_TABLESPACE

TEMPORARY_TABLESPACE

DBA_USERS

USERNAME

USER_ID

CREATED

ACCOUNT_STATUS

LOCK_DATE

EXPIRY_DATE

DEFAULT_TABLESPACE

TEMPORARY_TABLESPACE

DBA_TS_QUOTAS

USERNAME

TABLESPACE_NAME

BYTES

MAX_BYTES

BLOCKS

MAX_BLOCKS

DBA_TS_QUOTAS

USERNAME

TABLESPACE_NAME

BYTES

MAX_BYTES

BLOCKS

MAX_BLOCKS

Page 28: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

System Privileges: ExamplesSystem Privileges: ExamplesCategory Examples

INDEX CREATE ANY INDEXALTER ANY INDEXDROP ANY INDEX

TABLE CREATE TABLECREATE ANY TABLEALTER ANY TABLEDROP ANY TABLESELECT ANY TABLEUPDATE ANY TABLEDELETE ANY TABLE

SESSION CREATE SESSIONALTER SESSIONRESTRICTED SESSION

TABLESPACE CREATE TABLESPACEALTER TABLESPACEDROP TABLESPACEUNLIMITED TABLESPACE

Page 29: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Displaying System PrivilegesDisplaying System Privileges

DBA_SYS_PRIVS

• GRANTEE

• PRIVILEGE

• ADMIN OPTION

SESSION_PRIVS

• PRIVILEGE

Database LevelDatabase Level Session LevelSession Level

Page 30: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Object PrivilegesObject Privileges

Object priv. Table Sequence Procedure

ALTER

DELETE

EXECUTE

INSERT

SELECT

UPDATE

Page 31: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

DBA_TAB_PRIVS

Displaying Object PrivilegesDisplaying Object Privileges

DBA_COL_PRIVS

GRANTEEOWNERTABLE_NAMEGRANTORPRIVILEGEGRANTABLE

GRANTEEOWNERTABLE_NAMECOLUMN_NAME GRANTORPRIVILEGEGRANTABLE

Page 32: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

GRANT create session TO scott;GRANT create session TO scott;

REVOKE create session FROM scott;REVOKE create session FROM scott;

Page 33: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

RolesRolesUsersUsers

PrivilegesPrivileges

RolesRoles

UPDATE ON EMP

INSERT ON EMP

SELECT ON EMP

CREATE TABLE

CREATE SESSION

HR_CLERKHR_MGR

King ScottRoger

Page 34: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Triggers and Views

• Triggers can be defined only on tables, not on views but triggers on the base table(s) of a view are fired if an INSERT, UPDATE, or DELETE statement is issued against a view.

• INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through SQL DML statements (INSERT, UPDATE, and DELETE).

• Oracle fires the INSTEAD OF trigger instead of executing the triggering statement. The trigger performs update, insert, or delete operations directly on the underlying tables.

• Users write normal INSERT, DELETE, and UPDATE statements against the view and the INSTEAD OF trigger works invisibly in the background to make the right actions take place.

• By default, INSTEAD OF triggers are activated for each row.

CREATE VIEW tutor_info AS SELECT s.name,s.studno,s.tutor,t.roomnoFROM student s, staff t WHERE s.tutor = t.lecturer;

Page 35: Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS

Example of an INSTEAD OF Trigger

CREATE TRIGGER tutor_info_insert

INSTEAD OF INSERT ON tutor_info

REFERENCING NEW AS n -- new tutor

FOR EACH ROW

BEGIN

IF NOT EXISTS SELECT * FROM student WHERE student.studno = :n.studno

THEN INSERT INTO student(studentno,name,tutor)

VALUES(:n.studno, :n.name, :n.tutor);

ELSE UPDATE student SET student.tutor = :n.tutor

WHERE student.studno = :n.studno;

END IF;

IF NOT EXISTS SELECT * FROM staff WHERE staff.lecturer = :n.tutor

THEN INSERT INTO staff VALUES(:n. staff.tutor, :n.roomno);

ELSE UPDATE staff SET staff.roomno = :n.roomno WHERE staff.lecturer = :n.tutor;

END IF;

END;

The actions shown for rows being inserted into the TUTOR_INFO view first test to see if appropriate rows already exist in the base tables from which TUTOR_INFO is derived. The actions then insert new rows or update existing rows, as appropriate. Similar triggers can specify appropriate actions for UPDATE and DELETE.