380 likes | 717 Views
Application Code. 1° Controllo. 3° Controllo. Procedure Client Side. Integrity Constraint. 2° Controllo. Event Driven. Trigger Code. BUSINESS RULES CONTROL. Dato. Data Base. Table. Using Index – Storage Option. Pericolo sui Dati.
E N D
Application Code 1° Controllo 3° Controllo Procedure Client Side Integrity Constraint 2° Controllo Event Driven Trigger Code BUSINESS RULES CONTROL Dato Data Base Table
Using Index – Storage Option 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
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 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
DISABLED 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 ENABLED Gli indici associati sono ricreati Riprendono i controlli sulle nuove DML Status SQL Constraints
Oracle Integrity Constraints: Table 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: Column 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) ]
UNIQUE Constraints in Oracle 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”.
Examples of Unique 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 … ) ;
PRIMARY KEY Constraints 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.
Defining Primary Keys in Oracle CREATE TABLE dept (deptno NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY, dname VARCHAR2(9), loc VARCHAR2(10) ) CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(9), loc VARCHAR2(10), CONSTRAINT pk_dept PRIMARY KEY (deptno) USING INDEX TABLESPACE ……. STORAGE (…..) PCTFREE … )
EMP DEPT Eno Ename Dno Dno Dname E1 Smith D5 E2 Black D6 E3 Jones D6 D5 Research D6 Advertising D7 Newprojects FOREIGN KEY Constraints in Oracle DEPT EMP 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?
Maintain Referential Integrity Event Action Delete corresponding Child records (Cascading Delete) Delete of Parent Set the Foreign Key to null in the corresponding Child records (Delete Nullifies) Parent Do not allow the delete of the Parent record if any corresponding Child records exist (Restricted Delete) Child
Maintain Referential Integrity Event Action Update Foreign Key of corresponding Child records (Cascading Update) Delete of Parent Update of Primary Key of Parent Set the Foreign Key to null in the corresponding Child records (Update Nullifies) Parent Do not allow the update of the Parent record if any corresponding Child records exist (Restricted Update) Child
Maintain Referential Integrity Event Action Delete of Parent Update of Primary Key of Parent Insert of Child Parent Child Check that null or a valid Primary Key from the Parent has been specified for the Foreign Key
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) ) La FOREIGN KEY deve referenziare un insieme di colonne sulle quali agisce Una PRIMARY KEY oppure un UNIQUE CONSTRAINT
ON DELETE CASCADE Option 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 )
CHECK Constraint on a Column 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)
Example of a CHECK Constraint on a Table 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) )
Triggers contrasted with routines Procedures are called explicitly Triggers are event-driven
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
trigger restriction PL/SQL Code Effetto trigger action • the procedure (PL/SQL block) that contains the SQL statements • and PL/SQL code to be executed when a triggering statement • is issued and the trigger restriction evaluates to TRUE. 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 Insert After Update of Before Delete TRIGGER STRUCTURE • the SQL statement that causes a trigger to be fired Regola di Scatto triggering event
Example : maintaining derived values Event CREATE OR REPLACE TRIGGER increment_courses AFTER INSERT ON enrol FOR EACH ROW BEGIN update students set numofcourses = numofcourses + 1 where students.studno = :new.studno END; Condition row trigger column values for current row and new/old correlation names Action
Example Integrity Trigger in Oracle Event CREATE TRIGGER labmark_check BEFORE INSERT OR UPDATE OF labmark ON enrol DECLARE bad_value exception; WHEN (old.labmark IS NOT NULL OR new.labmark IS NOT NULL) FOR EACH ROW BEGIN IF :new.labmark < :old.labmark THEN raise bad_value ; END IF; EXCEPTION WHEN bad_value THEN raise_application_error(-20221,‘New labmark lower than old labmark’ ); END; Condition row trigger Action
Some Cautionary Notes about Triggers SQL statement UPDATE T1 SET …; Fires the UPDATE-T1 Trigger • 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. UPDATE_T1 Trigger BEFORE UPDATE ON T1 FOR EACH ROW BEGIN ... INSERT INTO t2 VALUES (...); ... END; Fires the INSERT-T2 Trigger INSERT_T2 Trigger BEFORE UPDATE ON T2 FOR EACH ROW BEGIN ... INSERT INTO ... VALUES (...); ... END;
Checklist 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.
Creating Users Set the initial password: CREATE USER scott IDENTIFIED BY tiger DEFAULT TABLESPACE user_data TEMPORARY TABLESPACE temp QUOTA 15m ON user_data; DROP USER peter CASCADE;
Monitoring Users 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
System Privileges: Examples Category Examples INDEX CREATE ANY INDEX ALTER ANY INDEX DROP ANY INDEX TABLE CREATE TABLE CREATE ANY TABLE ALTER ANY TABLE DROP ANY TABLE SELECT ANY TABLE UPDATE ANY TABLE DELETE ANY TABLE SESSION CREATE SESSION ALTER SESSION RESTRICTED SESSION TABLESPACE CREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE UNLIMITED TABLESPACE
Displaying System Privileges Database Level Session Level • DBA_SYS_PRIVS • GRANTEE • PRIVILEGE • ADMIN OPTION • SESSION_PRIVS • PRIVILEGE
Object Privileges Object priv. Table Sequence Procedure ALTER Ö Ö DELETE Ö EXECUTE Ö INSERT Ö SELECT Ö Ö UPDATE Ö
Displaying Object Privileges DBA_COL_PRIVS DBA_TAB_PRIVS GRANTEEOWNERTABLE_NAMECOLUMN_NAME GRANTORPRIVILEGEGRANTABLE GRANTEEOWNERTABLE_NAMEGRANTORPRIVILEGEGRANTABLE
GRANT create session TO scott; REVOKE create session FROM scott;
Roles Users Roger King Scott Roles HR_MGR HR_CLERK Privileges SELECTON EMP INSERT ON EMP CREATE TABLE CREATE SESSION UPDATEON EMP
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.roomno FROM student s, staff t WHERE s.tutor = t.lecturer;
Example of an INSTEAD OF Trigger 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. 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;