Upload
bonifacio-corso
View
214
Download
0
Embed Size (px)
Citation preview
Application Code
Dato
Table
Data Base
Trigger Code
1° Controllo
Procedure Client Side
3° Controllo
Integrity Constraint
2° Controllo
Event Driven
BUSINESS RULES CONTROL
Pericolo sui DatiPericolo sui Dati
Un R.D.B.M.S. deve proteggere i dati da una svariata serie di insidie.Un R.D.B.M.S. deve proteggere i dati da una svariata serie di insidie.
Errori Accidentali (programming errors): Integrity issues.Errori Accidentali (programming errors): Integrity issues.
Utilizzo Illecito: Security issue.Utilizzo Illecito: Security issue.
Hardware e Software Failures: Restart issues.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
Qualche Caratteristica SQL ConstraintsQualche Caratteristica SQL Constraints
Migliorano le PerformancesMigliorano le PerformancesFacili da dichiarare / modificareFacili da dichiarare / modificareCentralizzano i controlliCentralizzano i controlliImmediatamente producono un feed back utenteImmediatamente producono un feed back utenteFlessibili (enabled / disabled)Flessibili (enabled / disabled)Pienamente documentati nel dizionario datiPienamente documentati nel dizionario datiDefinibili daI SQL Statement CREATE TABLE / ALTER TABLEDefinibili daI SQL Statement CREATE TABLE / ALTER TABLEDefinibili a livello di Tabella o di ColonnaDefinibili a livello di Tabella o di Colonna
XXX_CONSTRAINTSXXX_CONSTRAINTSXXX_CONS_COLUMNSXXX_CONS_COLUMNS
USERUSER – Relativi alle tabelle poste nello schema dello – Relativi alle tabelle poste nello schema dello user con il quale siamo connessiuser con il quale siamo connessiALLALL – Relativi alle tabelle accessibili dall’utente con – Relativi alle tabelle accessibili dall’utente con il quale siamo connessiil quale siamo connessiDBADBA – Relativi a tutte le tabelle – Relativi a tutte le tabelle
Status SQL ConstraintsStatus 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
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: ColumnOracle Integrity Constraints: Column
Un TABLE CONSTRAINT è identico, sintatticamente alla stesura vista 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: TableOracle Integrity Constraints: Table
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
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
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
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 … )
DEPTEMP
Dno DnameEno Ename Dno
D5 ResearchD6 AdvertisingD7 Newprojects
E1 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
Maintain Referential IntegrityEvent
Delete corresponding Child records(Cascading Delete) ORUpdate Foreign Key of corresponding Child records (Cascading Update)
Delete of Parent
Update of PrimaryKey of Parent
Insert of Child
Action
Parent
Child
Set the Foreign Key to null in the corresponding Child records(Delete or Update Nullifies)
Do not allow the delete or update of the Parent record if any corresponding Child records exist(ie. the event fails to proceed)(Restricted Delete or Update)
Check that null or a valid Primary Key from the Parent has been specified for the Foreign Key
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
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
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
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
Triggers contrasted with routines
Procedures are called explicitly
Triggers are event-driven
Database TriggersDatabase Triggers
Centralized actions can be defined using a non declarative Centralized actions can be defined using a non declarative approach (writing PL/SQL code) with database triggers. approach (writing PL/SQL code) with database triggers.
A database trigger is a stored procedure that is fired A database trigger is a stored procedure that is fired (implicitly executed) when an INSERT, UPDATE, or DELETE (implicitly executed) when an INSERT, UPDATE, or DELETE statement is issued against the associated table. statement is issued against the associated table.
Database triggers can be used to customize a database Database triggers can be used to customize a database management system:management system:
value-based auditing value-based auditing automated data generationautomated data generation the enforcement of complex security checksthe enforcement of complex security checks enforce integrity rulesenforce integrity rules enforce complex business rules enforce complex business rules
PL/SQL Code
TRIGGER STRUCTURE
Regola di Scatto
Effetto
After
Before
Insert
Update of
Delete
triggering event trigger action
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.
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.
Example : maintaining derived valuesExample : maintaining derived values
CREATE OR REPLACE TRIGGER increment_coursesCREATE OR REPLACE TRIGGER increment_courses AFTER INSERT ON enrolAFTER INSERT ON enrol
FOR EACH ROWFOR EACH ROWBEGINBEGINupdate studentsupdate students
set numofcourses = numofcourses + 1set numofcourses = numofcourses + 1where students.studno = :new.studnowhere students.studno = :new.studno
END;END;
Event
Condition
Action
row trigger
column values for current rowand new/old correlation names
Example Integrity Trigger in OracleExample Integrity Trigger in Oracle
CREATE TRIGGER labmark_checkCREATE TRIGGER labmark_check BEFORE INSERT OR UPDATE OF labmark ON enrol BEFORE INSERT OR UPDATE OF labmark ON enrolDECLARE DECLARE
bad_value exception;bad_value exception;
WHEN (old.labmark IS NOT NULL OR new.labmark IS NOT WHEN (old.labmark IS NOT NULL OR new.labmark IS NOT NULL)NULL)
FOR EACH ROW FOR EACH ROW BEGINBEGIN
IF :new.labmark < :old.labmarkIF :new.labmark < :old.labmarkTHEN raise bad_value ;THEN raise bad_value ;END IF;END IF;EXCEPTIONEXCEPTIONWHEN bad_value THENWHEN bad_value THEN
raise_application_error(-20221,‘New raise_application_error(-20221,‘New labmark lower labmark lower than old labmark’ );than old labmark’ );
END;END;
Event
Condition
Actionrow trigger
Some Cautionary Notes about Triggers Some Cautionary Notes about Triggers
Triggers are useful for customizing a Triggers are useful for customizing a database. database.
But the excessive use of triggers can result But the excessive use of triggers can result in complex interdependencies, which may in complex interdependencies, which may be difficult to maintain in a large be difficult to maintain in a large application. application.
E.g., when a trigger is fired, a SQL E.g., when a trigger is fired, a SQL statement within its trigger action statement within its trigger action potentially can fire other triggers. When a potentially can fire other triggers. When a statement in a trigger body causes another statement in a trigger body causes another trigger to be fired, the triggers are said to trigger to be fired, the triggers are said to be be cascadingcascading. .
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
Triggers and Views Triggers and Views
Triggers can be defined only on tables, not on views but triggers on 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 the base table(s) of a view are fired if an INSERT, UPDATE, or DELETE statement is issued against a view. statement is issued against a view. INSTEAD OF triggers provide a transparent way of modifying views INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through SQL DML statements that cannot be modified directly through SQL DML statements (INSERT, UPDATE, and DELETE). (INSERT, UPDATE, and DELETE). Oracle fires the INSTEAD OF trigger instead of executing the triggering Oracle fires the INSTEAD OF trigger instead of executing the triggering statement. The trigger performs update, insert, or delete operations statement. The trigger performs update, insert, or delete operations directly on the underlying tables. directly on the underlying tables. Users write normal INSERT, DELETE, and UPDATE statements against Users write normal INSERT, DELETE, and UPDATE statements against the view and the INSTEAD OF trigger works invisibly in the background the view and the INSTEAD OF trigger works invisibly in the background to make the right actions take place. to make the right actions take place. By default, INSTEAD OF triggers are activated for each row. By default, INSTEAD OF triggers are activated for each row.
CREATE VIEW tutor_info AS CREATE VIEW tutor_info AS SELECT s.name,s.studno,s.tutor,t.roomnoSELECT s.name,s.studno,s.tutor,t.roomnoFROM student s, staff t FROM student s, staff t WHERE s.tutor = t.lecturer;WHERE s.tutor = t.lecturer;
Example of an INSTEAD OF Trigger Example of an INSTEAD OF Trigger
CREATE TRIGGER tutor_info_insert CREATE TRIGGER tutor_info_insert
INSTEAD OF INSERT ON tutor_infoINSTEAD OF INSERT ON tutor_info
REFERENCING NEW AS n REFERENCING NEW AS n -- new tutor -- new tutor
FOR EACH ROWFOR EACH ROW
BEGINBEGIN
IF NOT EXISTS SELECT * FROM student WHERE student.studno = :n.studnoIF NOT EXISTS SELECT * FROM student WHERE student.studno = :n.studno
THEN INSERT INTO student(studentno,name,tutor) THEN INSERT INTO student(studentno,name,tutor)
VALUES(:n.studno, :n.name, :n.tutor);VALUES(:n.studno, :n.name, :n.tutor);
ELSE UPDATE student SET student.tutor = :n.tutor ELSE UPDATE student SET student.tutor = :n.tutor
WHERE student.studno = :n.studno;WHERE student.studno = :n.studno;
END IF;END IF;
IF NOT EXISTS SELECT * FROM staff WHERE staff.lecturer = :n.tutorIF NOT EXISTS SELECT * FROM staff WHERE staff.lecturer = :n.tutor
THEN INSERT INTO staff VALUES(:n. staff.tutor, :n.roomno);THEN INSERT INTO staff VALUES(:n. staff.tutor, :n.roomno);
ELSE UPDATE staff SET staff.roomno = :n.roomno WHERE staff.lecturer ELSE UPDATE staff SET staff.roomno = :n.roomno WHERE staff.lecturer = :n.tutor;= :n.tutor;
END IF; END IF;
END;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.
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.
Set the initial password:Set the initial password: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
Monitoring UsersMonitoring UsersMonitoring 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
System Privileges: System Privileges: ExamplesExamples
System Privileges: System Privileges: ExamplesExamplesCategory 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
Displaying System Displaying System PrivilegesPrivileges
Displaying System Displaying System PrivilegesPrivileges
DBA_SYS_PRIVS
• GRANTEE
• PRIVILEGE
• ADMIN OPTION
SESSION_PRIVS
• PRIVILEGE
Database LevelDatabase Level Session LevelSession Level
Object PrivilegesObject PrivilegesObject PrivilegesObject Privileges
Object priv.Object priv. TableTable SequenceSequence ProcedureProcedure
ALTERALTER
DELETEDELETE
EXECUTEEXECUTE
INSERTINSERT
SELECT SELECT
UPDATEUPDATE
DBA_TAB_PRIVS
Displaying Object PrivilegesDisplaying Object PrivilegesDisplaying Object PrivilegesDisplaying Object Privileges
DBA_COL_PRIVS
GRANTEEOWNERTABLE_NAMEGRANTORPRIVILEGEGRANTABLE
GRANTEEOWNERTABLE_NAMECOLUMN_NAME GRANTORPRIVILEGEGRANTABLE
GRANT create session TO scott;GRANT create session TO scott;
REVOKE create session FROM scott;REVOKE create session FROM scott;
RolesRolesRolesRoles
UsersUsers
PrivilegesPrivileges
RolesRoles
UPDATE ON EMP
INSERT ON EMP
SELECT ON EMP
CREATE TABLE
CREATE SESSION
HR_CLERKHR_MGR
King ScottRoger