Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity...

40
Integrity and Security in Databases Database Management System AIKTC Prof Muhammed Salman Shamsi

Transcript of Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity...

Page 1: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

IntegrityandSecurityinDatabases

Database Management System

AIKTC

Prof Muhammed Salman Shamsi

Page 2: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Disclaimer• Allthematerialsusedinthispresentationbelongstotherespectiveauthorsmentionedinreferencesection.

• ThispresentationistoonlyhelpthestudentscommunityofMumbaiUniversityforthesubjectofDatabaseManagementSystemandisforprivatecirculationonly.

• Ineitherclaimthismaterialoruseitforcommercialpurpose.

• Thispresentationispurelyforeducationpurpose.

Page 3: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

IntegrityConstraints

• Integrityconstraintsguardagainstaccidentaldamagetothedatabase,byensuringthatauthorizedchangestothedatabasedonotresultinalossofdataconsistency.

• Itisthemechanismtopreventinvaliddataentryintothetable.

• Henceintegrityconstraintsarelimitationsorsetofrulesimposedondataofdatabaseinordertokeepdatabaseinconsistentorcorrectstate.

• DomainConstraints&ReferentialIntegrityConstraintsarethetypesofIntegrityConstraints.

Page 4: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

DomainConstraints• Domainconstraintsarethemostelementryformofintegrityconstraints.

• Theytestthevaluesinsertedinthedatabase,andtestqueriestoensurethatthecomparisionmakesense.

• Newdomainscanbecreatedfromtheexistingdatatypes:• createdomain<new_domain_name>as<new_data_type>

createdomain Dollarsasnumeric(12,2)createdomain Poundsasnumeric(12,2)

• Note:wecannotassignorcompareavalueoftypeDollarstoavalueoftypePounds.Howeverwecanconverttypeasbelow:

(cast r.Aas Pounds)

Page 5: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

ReferentialIntegrity• Ensuresthatavaluethatappearsinonerelationforagivensetofattributesalsoappearsforacertainsetofattributesinanotherrelation.

• LetAbeasetofattributes.LetRandSbetworelationsthatcontainattributesAandwhereAistheprimarykeyofS.Aissaidtobeaforeignkey ofRifforanyvaluesofAappearinginRthesevaluesalsoappearinS.RandSarenotnecessarilydistinct.

• IfaforeignkeyFinatableRreferstoandmatchestheprimarykeyPoftableStheneveryvalueofFmusteitherbeequaltovalueofPorwhollyNULL.

Page 6: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

CascadingActionsinReferentialIntegrity• createtablecourse(

course_id char(5)primarykey,titlevarchar(20),dept_name varchar(20)referencesdepartment

)• createtablecourse(

…dept_name varchar(20),foreignkey(dept_name) referencesdepartment

ondeletecascadeonupdatecascade,

...)

• alternativeactionstocascade:setnull,setdefault

Page 7: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

7

ColumnConstraintsandTableConstraints

Iftheconstraintsaredefined along withthe acolumndefinitionofatable,than they arecalledcolumnconstraints.Theseconstraintsinvolveonlyoneattribute.Ifmorethanoneattributeisinvolvedthetableconstraintmustbeused.Acolumnconstraintwillnotbecheckedifvaluesinothercolumnsarebeingupdated.Ifthedataconstraintsattachedtoaspecificcolumninatablereferencesthecontentsofaanothercolumninthetablethentheyarecalledastableconstraints.

Page 8: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

ExamplesofdifferentConstraints

• NotNullconstraint• PrimaryKeyconstraint• UniqueConstraint• DefaultvalueConstraint• ForeignKeyConstraint• CheckIntegrityConstraints

Page 9: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

PKasaColumnConstraintA column constraint is usually used when the PK is a single attribute.

Constraint: Data entered in the column must be unique and not null.

CREATE TABLE Match(MatchID INT PRIMARY KEY, Team1 CHAR(15), Team2 CHAR(15), Ground CHAR(20), Date CHAR(10), Result CHAR(10));

Page 10: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

PKasaTableConstraint

AtableconstraintisusuallyusedwhenthePKismorethanasingleattribute.

CREATETABLEBowling(MID INT,PID INT,NOvers INT,Maidens INT,NRuns INT,NWickets INT,PRIMARYKEY(MID,PID));

Page 11: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

FKasaColumnConstraint

AcolumnconstraintisusuallyusedwhentheFKisasingleattribute.

CREATETABLEEmployee(EmpID NUMERIC(6)PRIMARYKEY,Name CHAR(20),Dept CHAR(10),REFERENCESDepartment (DeptID),Address CHAR(50)Position CHAR(20));

Page 12: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

FKasaTableConstraintAtableconstraintisusuallyrequiredwhentheFKismorethanasingleattribute.

CREATETABLEBowling(MatchID INT,PID INTEGER,NOvers INT,Maidens INT,NRuns INT,NWickets INT,PRIMARYKEY(MID,PID)FOREIGNKEY(MatchID)REFERENCESMatch,FOREIGNKEY(PID)REFERENCESPlayer);

Page 13: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

NULLasaColumnConstraint

CREATE TABLE Match(MatchID INT PRIMARY KEY, Team1 CHAR(15) NOT NULL,Team2 CHAR(15) NOT NULL,Ground CHAR(20), Date CHAR(10), Result CHAR(10));

Page 14: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

DEFAULTasaColumnConstraint

CREATETABLEMatch(MatchID INTPRIMARYKEYTeam1 CHAR(15)DEFAULT‘India’,Team2 CHAR(15),Ground CHAR(20),Date CHAR(10),Result CHAR(10));

Page 15: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

UNIQUEasaColumnConstraint

AcolumnconstraintisusuallyusedwhenUNIQUEisasingleattribute.

CREATETABLEEmployee(EmpID NUMBER(6)PRIMARYKEY,Name CHAR(20),DeptID CHAR(10),Telephone INTUNIQUE,Address CHAR(50),Position CHAR(20);

Page 16: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

UNIQUEasaTableConstraint

AtableconstraintisusuallyrequiredwhenUNIQUEismorethanasingleattribute.

CREATETABLEPlayer(PlayerID INTPRIMARYKEY,LName CHAR(15),FName CHAR(15),Country CHAR(20),YBorn INT,BPlace CHAR(20)FTest INT,UNIQUE(LName,FName));

Page 17: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

CHECKConstraint

Possible conditions in the CHECK clause

1 attribute A > value v

2 attribute A between value v1 and value v2

3 attribute A IN (list of values)

4 Attribute A IN subquery

5 attribute A condition C1 OR condition C2

6 attribute A condition C1 AND condition C2

Page 18: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

CHECKasaColumnConstraint

CREATETABLEPlayer(PlayerID INTPRIMARYKEY,LName CHAR(15),FName CHAR(15),Country CHAR(20),YBorn INTCHECK(YBorn >1950),BPlace CHAR(20),FTest INT);

Page 19: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

CHECKasaTableConstraintAtableconstraintisusedwhentheCHECKconstrainthasmorethanasingleattribute.

CREATETABLEPlayer(PlayerID INTPRIMARYKEY,LName CHAR(15)NOTNULL,FName CHAR(1)NOTNULL,Country CHAR(20),YBorn INT,BPlace CHAR(20),FTest INT,CHECK(FTest >YBorn +15));

Page 20: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Alternativewaystocreateconstraints

• Syntax:constraint[<constraint_name>]constraint_definition;

• IncreatecommandcreatetableStudent(sidvarchar(20),mobilenovarchar(10),....................................,constraintstud_pkprimarykey(sid),constraintm_uniqueunique(mobileno));

• InAltercommandAltertableStudentADDCONSTRAINTcheck_ageCHECK(age>16);

• DroppingaconstraintAltertableStudentDROPCONSTRAINTcheck_age;

Page 21: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

ComplexCheckClauses• Complexcheckconditionscanbeusefulwhenwewanttoensureintegrityofdata,butmaybecostlytotest.check (timeslot_idin (select timeslot_idfrom timeslot))

• Forexample,thepredicateinthecheckclausewouldnotonlyhavetobeevaluatedwhenamodificationismadetothesectionrelation,butmayhavetobecheckedifamodificationismadetothetimeslotrelationbecausethatrelationisreferencedinthesubquery.

• Unfortunately:subqueryincheckclausenotsupportedbyprettymuchanydatabase

Page 22: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Assertion• Anassertion isapredicateexpressingaconditionthatwewishthedatabasealwaystosatisfy.

• Domainconstraints andreferential-integrityconstraints arespecialformsofassertions.

• createassertion<assertion-name>check<predicate>;• Alsorarely supportedbyanyone

• Twoexamplesofsuchconstraintsare:•Foreachtupleinthestudentrelation,thevalueoftheattributetot_credmustequalthesumofcreditsofcoursesthatthestudenthascompletedsuccessfully.• Aninstructorcannotteachintwodifferentclassroomsinasemesterinthesametimeslot.

Page 23: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

AssertionExample

createassertion credits_earned constraintcheck(notexists(select ID

from studentwhere tot_cred<>(select sum(credits)from takesnatural join coursewhere student.ID=takes.ID

and gradeisnot nulland grade<>’F’);

Page 24: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Triggers• Atrigger isastatementthatisexecutedautomaticallybythesystemasasideeffectofamodificationtothedatabase.

• Todesignatriggermechanism,wemust:• Specifytheconditionsunderwhichthetriggeristobeexecuted.

• Specifytheactionstobetakenwhenthetriggerexecutes.

• Theabovemodeloftriggersisreferredtoastheevent-condition-action modelfortrigger.

Page 25: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

NeedforTriggers

• TriggerscanbeusedtoimplementcertainintegrityconstraintsthatcannotbespecifiedusingtheconstraintmechanismofSQL.

• Triggersarealsousefulmechanismsforalertinghumansorforstartingcertaintasksautomaticallywhencertainconditionsaremet.

• Asanillustration,wecoulddesignatriggerthat,wheneveratupleisinsertedintothetakesrelation,updatesthetupleinthestudentrelationforthestudenttakingthecoursebyaddingthenumberofcreditsforthecoursetothestudent’stotalcredits.

Page 26: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

TriggerSyntax[MySQL]

CREATE[DEFINER ={user|CURRENT_USER }]TRIGGER trigger_nametrigger_timetrigger_eventON tbl_nameFOREACHROWtrigger_body

trigger_time:{BEFORE |AFTER }trigger_event:{INSERT |UPDATE |DELETE }

Page 27: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

TriggeringEventsandActionsinSQLTriggeringeventcanbeinsert,delete orupdateTriggersonupdatecanberestrictedtospecificattributesFor example, after update of takes on gradeValuesofattributesbeforeandafteranupdatecanbereferencedreferencing old row as : for deletes and updatesreferencing new row as : for inserts and updatesTriggerscanbeactivatedbeforeanevent,whichcanserveasextraconstraints.Forexample,convertblankgradestonull.

Page 28: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

TriggerExampleIBMDB2

createtrigger setnullbeforeupdateon takesreferencingnewrowas nrowforeachrowwhen (nrow.grade=’’)beginatomic

set nrow.grade=null;end;

Page 29: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

TriggerExampleMySQL

createtrigger setnullbeforeupdateontakesforeachrowbegin

ifnew.grade=''thensetnew.grade=null;

endif;end;

Page 30: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

createtrigger credits_earnedafterupdateof takeson (grade)referencingnewrowas nrowreferencingoldrowas orowforeachrowwhen nrow.grade<>’F’and nrow.gradeisnotnulland (orow.grade=’F’or orow.gradeisnull)beginatomicupdate studentset tot_cred=tot_cred+(select creditsfrom coursewhere course.course_id=

nrow.course_id)where student.id=nrow.id;

end;

Page 31: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Triggersformaintainingreferentialintegrity

createtrigger timeslot_check1afterinserton sectionreferencingnewrowas nrowforeachrowwhen (nrow.time_slot_idnotin (

select time_slot_idfrom time_slot))/*timeslotidnot

presentintimeslot*/begin

rollbackend;

Page 32: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

WhenNottoUseTriggers• Noneedto implementtheondeletecascadefeatureofaforeign-key

constraintbyusingatrigger,insteadofuse thecascadefeature.• Thereisnoneedtowritetriggercodeformaintainingmaterializedviews.• Moderndatabasesystems,providebuilt-infacilitiesfordatabase

replication,makingtriggersunnecessaryforreplicationinmostcases.• Triggersshouldbewrittenwithgreatcare,sinceatriggererrordetectedat

runtimecausesthefailureoftheactionstatementthatsetoffthetrigger.Furthermore,theactionofonetriggercansetoffanothertrigger.Intheworstcase,thiscouldevenleadtoaninfinitechainoftriggering.

• Manytriggerapplicationscanbesubstitutedbyappropriateuseofstoredprocedures

Page 33: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Security

• Securityisaprotectionfrommaliciousattemptstostealormodifydata.Thesecurityshouldbeprovidedatfollowinglevels:

• 1)Databasesystemlevel.(useracessonlyrequireddata)• 2)Operatingsystemlevel.(superuser)• 3)Networklevel.

(encryption,eavesdropping,masquerading)• 4)Physicallevel.• 5)Humanlevel.(usertraining)

Page 34: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Authorization

Formsofauthorizationonpartsofthedatabase:

Read - allowsreading,butnotmodificationofdata.Insert - allowsinsertionofnewdata,butnotmodificationofexistingdata.Update - allowsmodification,butnotdeletionofdata.Delete - allowsdeletionofdata.

Formsofauthorizationtomodifythedatabaseschema

Index - allowscreationanddeletionofindices.Resources - allowscreationofnewrelations.Alteration - allowsadditionordeletionofattributesinarelation.Drop - allowsdeletionofrelations.

Page 35: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

AuthorizationSpecificationinSQL

Thegrant statementisusedtoconferauthorization

grant <privilegelist>on<relationnameorviewname>to <userlist><user list> is: a user-idpublic, which allows all valid users the privilege grantedA role (more on this later)

Grantingaprivilegeonaviewdoesnotimplygrantinganyprivilegesontheunderlyingrelations.Thegrantoroftheprivilegemustalreadyholdthe

Page 36: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

PrivilegesinSQLselect: allowsreadaccesstorelation,ortheabilitytoqueryusingtheview

Example: grant users U1, U2, and U3 select authorization on the instructor relation:

grantselectoninstructortoU1,U2,U3

insert:theabilitytoinserttuplesupdate:theabilitytoupdateusingtheSQLupdatestatementdelete:theabilitytodeletetuples.all privileges:usedasashortformforalltheallowableprivileges

Page 37: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

RevokingAuthorizationinSQLTherevoke statementisusedtorevokeauthorization.

revoke <privilege list>on <relation name or view name> from <user list>

Example:

revoke select on branch from U1, U2, U3<privilege-list>maybealltorevokeallprivilegestherevokeemayhold.If<revokee-list>includespublic,alluserslosetheprivilegeexceptthosegranteditexplicitly.Ifthesameprivilegewasgrantedtwicetothesameuserbydifferentgrantees,theusermayretaintheprivilegeaftertherevocation.Allprivilegesthatdependontheprivilegebeingrevokedarealsorevoked.

Page 38: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

Roles• createrole instructor;• grant instructor toAmit;• Privilegescanbegrantedtoroles:

• grant select on takes to instructor;• Rolescanbegrantedtousers,aswellastootherroles

• create role teaching_assistant• grant teaching_assistant to instructor;

• Instructor inheritsallprivilegesofteaching_assistant• Chainofroles

• create role dean;• grant instructor to dean;• grant dean to Satoshi;

Page 39: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

LimitationsofSQLAuthorization• SQLdoesnotsupportauthorizationatatuplelevel.• Allendusersofanapplicationmaybemappedtoasingledatabaseuser.

• Thetaskofauthorizationinabovecasesfallsontheapplicationprogram,withnosupportfromSQL:

Benefits:Finegrainedauthorizationsimplementedbyapplications

Drawback:Authorizationloopholesarecreatedwhichbecomesdifficulttofindduetolargeamount

ofapplicationcode

Page 40: Database Management System - AIKTC › wp-content › uploads › 2019 › ... · Integrity Constraints •Integrity constraints guard against accidental damage to the database, by

References

• DatabaseManagementSystem,G.KGupta,TataMcGrawHill• DatabaseSystemConcepts,Korth,Sudarshan et.al.,TataMcGrawHill