Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 37

Unit 5: Integrity and security

Dhanashree Huddedar
Index
• Domain Constraint
• Referential Integrity
• Assertions
• Triggers and Assertions in SQL
• Security and Authorization in SQL
Overview
Ensuring a Robust System
• To ensure the implemented system will be robust and cater for future
enhancements many other questions need to be addressed, some of
which are:
• How will the final system be audited?
• What security features are needed?
• Can the database handle the user requirements now and in the future?
• How can you ensure the integrity of the data within the database?
Auditing

• Auditing needs to be considered before the database is implemented. It shouldn't be


an afterthought. Often auditing is a business requirement; sometimes it is a legal
obligation.
• Questions need to be asked, such as, how should the system:
• Audit user data accesses, both legal and illegal?
• Audit user data changes, both legal and illegal?
• Audit resource usage, eg disk accesses, bottlenecks?
• Report on the above in a detailed and timely manner?
• Most RDBMS have some method of auditing to a greater or lesser degree. You need to
know your auditing requirements as they may form part of your criteria for selecting a
RDBMS.
• Many RDBMSs will audit user accesses, eg successful / unsuccessful logons, accesses
to data, changes to database structures, modifications of authority, etc.
• However, it is more difficult to audit the changes to the data itself, eg before and after
images of a record update.
Auditing continued…

• A simple auditing system can be implemented by the use of control


items added to the data tables requiring auditing.
• Username of user who inserted the data row
• Date and time the row was inserted
• Username of user who last modified the data row
• Date and time the row was last modified
• For some systems this is sufficient auditing. However, this does not
maintain a complete audit trail, ie all the changes over time.
Security

• Security is the mechanism whereby authorised database access is


provided. Several levels may be implemented, eg network access
security, database access security, data access security and data
modification security. The last three are covered in the next section.
• Security also includes safety measures of the physical server (eg in a
locked room), use of PCs without access to external drives, etc.
• As part of the design of the system you may be involved in security
investigations.
Time Effects

• A database is not a static object. It is always changing. Data is continually


being added, changed and deleted. New business requirements and laws
may require the structure to be changed.
• The designed system needs to be able to handle user requirements now and
in the future. The system should allow for enhancements to be easily
incorporated.
• A well designed system, ie following the normalisation process as described,
should simplify the process of including system and data changes.
• The data analysis process identifies the current business rules. The
subsequent design then should allow for future data changes and storage. 
Time Effects continued….
• an example of this can be found in the Painting Hire system.
• Business rules dictated that:
• Over time a customer may hire the same painting more than once.
• Any paintings not hired within six months are returned to the owner. However,
after three months, an owner may resubmit a returned painting.
• The resulting keys allowed for these time requirements:
• Rental (customer no,painting number,date of hire, date due back, return flag)
• Return (owner no, painting no, return date)
• Including the date of hire allows a customer to rent the same painting more than
once.
• Including the return date allows an owner to resubmit a returned painting.
Data Integrity
• Integrity ensures that the data in a database is both accurate and
complete, in other words, that the data makes sense. There are at
least five different types of integrity that needs to be considered:
• Domain constraints
• Entity integrity
• Column constraints
• User-defined integrity constraints
• Referential integrity
• The data analysis stage will identify the requirements of these.
Domain Constraints
• A domain is defined as the set of all unique values permitted for an attribute.
For example, a domain of date is the set of all possible valid dates, a domain of
integer is all possible whole numbers, a domain of day-of-week is Monday,
Tuesday ... Sunday.
• This in effect is defining rules for a particular attribute. If it is determined that
an attribute is a date then it should be implemented in the database to prevent
invalid dates being entered.
• A classic example of this is where the data from a legacy system is loaded into a
newly designed database. The new system is well designed. Columns that hold
dates are defined as such whereas, in the old system, they were held as
character strings. Much data is rejected because of invalid dates, eg 30 February
2000.
• If the system supports domain constraints then this invalid data would not have
stored in the first place. That is, the integrity of the database is being preserved.
• Integrity constraints guard against accidental damage to the database,
by ensuring that authorized changes to the database do not result in a
loss of data consistency.
• Domain constraints are the most elementary form of integrity
constraint.
• They test values inserted in the database, and test queries to ensure
that the comparisons make sense.
• New domains can be created from existing data types "
• create domain Dollars numeric(12, 2)
• create domain Pounds numeric(12,2)
• The check clause in SQL-92 permits domains to be restricted:
• " Use check clause to ensure that an hourly-wage domain allows only values greater
than a specified value.
• create domain hourly-wage numeric(5,2) constraint value-test check(value > = 4.00) "
The domain has a constraint that ensures that the hourly-wage is greater than 4.00 "
• The clause constraint value-test is optional; useful to indicate which constraint an
update violated.
• Can have complex conditions in domain check
• Create domain AccountType char(10)
• constraint account-type-test
• check (value in (‘Checking’, ‘Saving’))
• check (branch-name in (select branch-name from branch))
Example
• Domain constraints are user defined data type and we can define them like this:
• Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY /
CHECK / DEFAULT)

create domain id_value int


constraint id_test
check(value > 100);

create table student_info (


stu_id id_value PRIMARY KEY,
stu_name varchar(30),
stu_age int
);
• Primary and candidate keys and foreign keys can be specified as part of the SQL
create table statement:
• The primary key clause lists attributes that comprise the primary key.
• The unique key clause lists attributes that comprise a candidate key.
• The foreign key clause lists the attributes that comprise the foreign key and the name of the
relation referenced by the foreign key.
• By default, a foreign key references the primary key attributes of the referenced
table foreign key (account-number) references account
• Short form for specifying a single column as foreign key account-number char (10)
references account
• Reference columns in the referenced table can be explicitly specified " but must be declared as
primary/candidate keys foreign key (account-number) references account(account-number)
Referential Integrity in SQL
• Referential Integrity Constraint
• The referential integrity constraint is specified between two tables and it is
used to maintain the consistency among rows between the two tables.

The rules are:


1. You can't delete a record from a primary table if matching records exist in
a related table.
2. You can't change a primary key value in the primary table if that record
has related records.
3. You can't enter a value in the foreign key field of the related table that
doesn't exist in the primary key of the primary table.
4. However, you can enter a Null value in the foreign key, specifying that the
records are unrelated.
Examples
Examples
Rule 1. You can't delete any of the rows in the CarType table that are
visible in the picture since all the car types are in use in the Car table.

Rule 2. You can't change any of the model_ids in the CarType table
since all the car types are in use in the Car table.

Rule 3. The values that you can enter in the model_id field in the Car
table must be in the model_id field in the CarType table.

Rule 4. The model_id field in the Car table can have a null value which
means that the car type of that car in not known
Foreign Key Integrity Constraint

• There are two foreign key integrity constraints:


• cascade update related fields
• cascade delete related rows.
• These constraints affect the referential integrity constraint.
Cascade Update Related Fields
• Cascade Any time you change the primary key of a row in the primary table,
the foreign key values are updated in the matching rows in the related table.
• This constraint overrules rule 2 in the referential integrity constraints. 
• If this constraint is defined in the relationship between the tables Car and
CarType, it is possible to change the model_id in the CarType table.
• If one should change the model_id 1 (Ford Focus) to model_id 100 in the
CarType table, the model_ids in the Car table would change from 1 to 100
(cars ABC-112, ABC-122, ABC-123).
Update Related Fields
Cascade Delete Related Rows
• Any time you delete a row in the primary table, the matching rows are
automatically deleted in the related table. This constraint overrules
rule 1 in the referential integrity constraints. 

If this constraint is defined in the relationship between the tables Car


and CarType, it is possible to delete rows from the CarType table. If
one should delete the Ford Focus row from the CarType table, the
cars ABC-112, ABC-122, ABC-123 would be deleted from the Car table,
too.
Assertions
• An assertion is a predicate expressing a condition that we wish the
database always to satisfy.
• An assertion in SQL takes the form create assertion check ! When an
assertion is made, the system tests it for validity, and tests it again on
every update that may violate the assertion
• This testing may introduce a significant amount of overhead; hence
assertions should be used with great care
Assertion Example
• The sum of all loan amounts for each branch must be less than the
sum of all account balances at the branch.
create assertion sum-constraint check
(not exists (select * from branch
where (select sum(amount) from loan
where loan.branch-name = branch.branch-name)
>= (select sum(amount) from account
where loan.branch-name = branch.branch-name)))
Triggers
• A trigger is a statement that is executed automatically by the system
as a side effect of a modification to the database.
• To design a trigger mechanism, we must:
• Specify the conditions under which the trigger is to be executed.
• Specify the actions to be taken when the trigger executes.
• Triggers introduced to SQL standard in SQL:1999, but supported even
earlier using non-standard syntax by most databases.
Triggers: Introduction
 The application constraints need to be captured inside the database

 Some constraints can be captured by:


 Primary Keys, Foreign Keys, Unique, Not NULL, and domain constraints

CREATE TABLE Students


(sid: CHAR(20),
name: CHAR(20) NOT NULL,
These constraints are
login: CHAR(10),
age: INTEGER,
defined in CREATE TABLE
gpa: REAL Default 0, or ALTER TABLE
Constraint pk Primary Key (sid),
Constraint u1 Unique (login),
Constraint gpaMax check (gpa <= 4.0) );

24
Triggers: Introduction
Other application constraints are more complex
 Need for assertions and triggers

Examples:
 Sum of loans taken by a customer does not exceed 100,000
 Student cannot take the same course after getting a pass grade in it
 Age field is derived automatically from the Date-of-Birth field

25
Triggers
A procedure that runs automatically when a certain
event occurs in the DBMS

The procedure performs some actions, e.g.,


 Check certain values
 Fill in some values
 Inserts/deletes/updates other records
 Check that some business constraints are satisfied
 Commit (approve the transaction) or roll back (cancel the
transaction)

26
Trigger Components
Three components
 Event: When this event happens, the trigger is activated
 Condition (optional): If the condition is true, the trigger
executes, otherwise skipped
 Action: The actions performed by the trigger

Semantics
 When the Event occurs and Condition is true, execute the
Action

Lets see how to define these


components

27
Trigger: Events
 Three event types
 Insert
 Update
 Delete

 Two triggering times


 Before the event
 After the event

 Two granularities
 Execute for each row
 Execute for each statement

28
1) Trigger: Event
Trigger name
Create Trigger <name>
Before|After Insert|Update|Delete ON <tablename> That is the event

….

Example
Create Trigger ABC Create Trigger XYZ
Before Insert On Students After Update On Students
…. ….

This trigger is activated when an This trigger is activated when an


insert statement is issued, but update statement is issued and
before the new record is inserted after the update is executed

29
Granularity of Event
 A single SQL statement may update, delete, or insert many records
at the same time
 E.g., Update student set gpa = gpa x 0.8;

 Does the trigger execute for each updated or deleted record, or


once for the entire statement ?
 We define such granularity

Create Trigger <name> This is the event


Before| After Insert| Update| Delete

For Each Row | For Each Statement


…. This is the granularity

30
Example: Granularity of Event

Create Trigger XYZ


Create Trigger XYZ
After Update ON <tablename>
Before Delete ON <tablename>

For each statement


For each row
….
….
This trigger is activated once (per This trigger is activated before
UPDATE statement) after all deleting each record
records are updated

31
2) Trigger: Condition
This component is optional
Create Trigger <name>
Before| After Insert| Update| Delete On <tableName>
For Each Row | For Each Statement

When <condition> That is the condition


If the employee salary > 150,000 then some actions will be taken

Create Trigger EmpSal


After Insert or Update On Employee
For Each Row
When (new.salary >150,000)

32
3) Trigger: Action
Action depends on what you want to do, e.g.:
 Check certain values
 Fill in some values
 Inserts/deletes/updates other records
 Check that some business constraints are satisfied
 Commit (approve the transaction) or roll back (cancel the
transaction)

In the action, you may want to reference:


 The new values of inserted or updated records (:new)
 The old values of deleted or updated records (:old)

33
Trigger: Referencing Values
In the action, you may want to reference:
 The new values of inserted or updated records (:new)
 The old values of deleted or updated records (:old)

Create Trigger EmpSal


After Insert or Update On Employee Inside “When”, the “new” and
For Each Row “old” should not have “:”
When (new.salary >150,000)
Begin
Trigger
if (:new.salary < 100,000) …
body End;

Inside the trigger body, they


should have “:”

34
Trigger: Referencing Values (Cont’d)
 Insert Event
 Has only :new defined

 Delete Event
 Has only :old defined

 Update Event
 Has both :new and :old defined

 Before triggering (for insert/update)


 Can update the values in :new
 Changing :old values does not make sense

 After triggering
 Should not change :new because the event is already done

35
Example 1
If the employee salary increased by more than 10%, make sure the ‘rank’
field is not empty and its value has changed, otherwise reject the update

If the trigger exists, then drop it first

Create or Replace Trigger EmpSal


Before Update On Employee
For Each Row Compare the old and new salaries
Begin
IF (:new.salary > (:old.salary * 1.1)) Then
IF (:new.rank is null or :new.rank = :old.rank) Then
RAISE_APPLICATION_ERROR(-20004, 'rank field not correct');
End IF;
End IF;
End;
/ Make sure to have the “/” to run the command

36
Example 2
If the employee salary increased by more than 10%, then increment the rank field
by 1.

In the case of Update event only, we can specify which columns

Create or Replace Trigger EmpSal


Before Update Of salary On Employee
For Each Row
Begin
IF (:new.salary > (:old.salary * 1.1)) Then
:new.rank := :old.rank + 1;
End IF;
We changed the new value of rank field
End;
/

The assignment operator has “:”

37

You might also like