Scaricare la presentazione
La presentazione è in caricamento. Aspetta per favore
PubblicatoAgnese Lolli Modificato 10 anni fa
1
Dato Table Data Base Application Code 1° Controllo Procedure Client Side 3° Controllo Integrity Constraint Trigger Code 2° Controllo Event Driven BUSINESS RULES CONTROL
2
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
3
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
4
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
5
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
6
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
7
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
8
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
9
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
10
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 … )
11
DEPT Dno Dname D5Research D6Advertising D7Newprojects EMP Eno Ename Dno E1 Smith D5 E2 Black D6 E3 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
12
Maintain Referential Integrity Event 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)
13
Maintain Referential Integrity Event Update Foreign Key of corresponding Child records (Cascading Update) Delete of Parent Update of Primary Key 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)
14
Maintain Referential Integrity Event Delete of Parent Update of Primary Key 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
15
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 Oracle Referential Integrity Constraints
16
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
17
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
18
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
19
Triggers contrasted with routines Procedures are called explicitly Triggers are event-driven
20
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
21
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 statements and PL/SQL code to be executed when a triggering statement is issued and the trigger restriction evaluates to TRUE.
22
Example : maintaining derived values 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; Event Condition Action row trigger column values for current row and new/old correlation names
23
Example Integrity Trigger in Oracle 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; Event Condition Action row trigger
24
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 statement UPDATE T1 SET …; UPDATE_T1 Trigger BEFORE UPDATE ON T1 FOR EACH ROW BEGIN... INSERT INTO t2 VALUES (...);... END; INSERT_T2 Trigger BEFORE UPDATE ON T2 FOR EACH ROW BEGIN... INSERT INTO... VALUES (...);... END; Fires the UPDATE-T1 Trigger Fires the INSERT-T2 Trigger
25
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. 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.
26
Set the initial password: CREATE USER scott IDENTIFIED BY tiger DEFAULT TABLESPACE user_data TEMPORARY TABLESPACE temp QUOTA 15m ON user_data; CREATE USER scott IDENTIFIED BY tiger DEFAULT TABLESPACE user_data TEMPORARY TABLESPACE temp QUOTA 15m ON user_data; DROP USER peter CASCADE; Creating Users
27
Monitoring 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
28
System Privileges: Examples CategoryExamples INDEXCREATE 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 SESSIONCREATE SESSION ALTER SESSION RESTRICTED SESSION TABLESPACECREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE UNLIMITED TABLESPACE
29
Displaying System Privileges DBA_SYS_PRIVS GRANTEE PRIVILEGE ADMIN OPTION SESSION_PRIVS PRIVILEGE Database Level Session Level
30
Object Privileges Object priv. TableSequenceProcedure ALTER DELETE EXECUTE INSERT SELECT UPDATE
31
DBA_TAB_PRIVS Displaying Object Privileges DBA_COL_PRIVS GRANTEE OWNER TABLE_NAME GRANTOR PRIVILEGE GRANTABLE GRANTEE OWNER TABLE_NAME COLUMN_NAME GRANTOR PRIVILEGE GRANTABLE
32
GRANT create session TO scott; REVOKE create session FROM scott;
33
Roles Users Privileges Roles UPDATE ON EMP INSERT ON EMP SELECT ON EMP CREATE TABLE CREATE SESSION HR_CLERKHR_MGR King Scott Roger
34
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;
35
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.
Presentazioni simili
© 2024 SlidePlayer.it Inc.
All rights reserved.